/
Format.php
110 lines (98 loc) · 3.02 KB
/
Format.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
declare(strict_types=1);
namespace Intervention\Image;
use Error;
use Intervention\Image\Encoders\AvifEncoder;
use Intervention\Image\Encoders\BmpEncoder;
use Intervention\Image\Encoders\GifEncoder;
use Intervention\Image\Encoders\HeicEncoder;
use Intervention\Image\Encoders\Jpeg2000Encoder;
use Intervention\Image\Encoders\JpegEncoder;
use Intervention\Image\Encoders\PngEncoder;
use Intervention\Image\Encoders\TiffEncoder;
use Intervention\Image\Encoders\WebpEncoder;
use Intervention\Image\Exceptions\NotSupportedException;
use Intervention\Image\Interfaces\EncoderInterface;
enum Format
{
case AVIF;
case BMP;
case GIF;
case HEIC;
case JP2;
case JPEG;
case PNG;
case TIFF;
case WEBP;
/**
* Create format from given identifier
*
* @param string|Format|MediaType|FileExtension $identifier
* @throws NotSupportedException
* @return Format
*/
public static function create(string|self|MediaType|FileExtension $identifier): self
{
if ($identifier instanceof self) {
return $identifier;
}
if ($identifier instanceof MediaType) {
return $identifier->format();
}
if ($identifier instanceof FileExtension) {
return $identifier->format();
}
try {
$format = MediaType::from(strtolower($identifier))->format();
} catch (Error) {
try {
$format = FileExtension::from(strtolower($identifier))->format();
} catch (Error) {
throw new NotSupportedException('Unable to create format from "' . $identifier . '".');
}
}
return $format;
}
/**
* Return the possible media (MIME) types for the current format
*
* @return array
*/
public function mediaTypes(): array
{
return array_filter(MediaType::cases(), function ($mediaType) {
return $mediaType->format() === $this;
});
}
/**
* Return the possible file extension for the current format
*
* @return array
*/
public function fileExtensions(): array
{
return array_filter(FileExtension::cases(), function ($fileExtension) {
return $fileExtension->format() === $this;
});
}
/**
* Create an encoder instance that matches the format
*
* @param mixed $options
* @return EncoderInterface
*/
public function encoder(mixed ...$options): EncoderInterface
{
return match ($this) {
self::AVIF => new AvifEncoder(...$options),
self::BMP => new BmpEncoder(...$options),
self::GIF => new GifEncoder(...$options),
self::HEIC => new HeicEncoder(...$options),
self::JP2 => new Jpeg2000Encoder(...$options),
self::JPEG => new JpegEncoder(...$options),
self::PNG => new PngEncoder(...$options),
self::TIFF => new TiffEncoder(...$options),
self::WEBP => new WebpEncoder(...$options),
};
}
}