-
Notifications
You must be signed in to change notification settings - Fork 4
/
ImageTypeDetector.php
80 lines (68 loc) · 1.7 KB
/
ImageTypeDetector.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
<?php
namespace Selective\ImageType;
use Selective\ImageType\Detector\DetectorInterface;
use Selective\ImageType\Provider\ProviderInterface;
use SplFileObject;
/**
* Image type detection.
*/
final class ImageTypeDetector
{
/**
* @var DetectorInterface[]
*/
private $detectors = [];
/**
* Add image detector.
*
* @param DetectorInterface $detector The detector
*/
public function addDetector(DetectorInterface $detector): void
{
$this->detectors[] = $detector;
}
/**
* Add image detector provider.
*
* @param ProviderInterface $provider The provider
*/
public function addProvider(ProviderInterface $provider): void
{
foreach ($provider->getDetectors() as $detector) {
$this->addDetector($detector);
}
}
/**
* Detect image type.
*
* @param SplFileObject $file The image file
*
* @throws ImageTypeDetectorException
*
* @return ImageType The image type
*/
public function getImageTypeFromFile(SplFileObject $file): ImageType
{
$type = $this->detectFile($file);
if ($type === null) {
throw new ImageTypeDetectorException('Image type could not be detected');
}
return $type;
}
/**
* Reads and returns the type of the image.
*
* @param SplFileObject $file The image file
*/
private function detectFile(SplFileObject $file): ?ImageType
{
foreach ($this->detectors as $detector) {
$file->rewind();
$type = $detector->detect($file);
if ($type !== null) {
return $type;
}
}
return null;
}
}