| 1 |
<?php |
| 2 |
|
| 3 |
namespace Spatie\ImageOptimizer; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
|
| 7 |
class Image |
| 8 |
{ |
| 9 |
protected $pathToImage = ''; |
| 10 |
protected const ALLOWED_PROTOCOLS = ['file']; |
| 11 |
|
| 12 |
protected const WINDOWS_LOCAL_FILENAME_REGEX = '/^[a-z]:(?:[\\\\\/]?(?:[\w\s!#()-]+|[\.]{1,2})+)*[\\\\\/]?/i'; |
| 13 |
|
| 14 |
public function __construct(string $pathToImage) |
| 15 |
{ |
| 16 |
if (! $this->isProtocolAllowed($pathToImage)) { |
| 17 |
throw new InvalidArgumentException(\sprintf('The output file scheme is not supported. Expected one of [\'%s\'].', \implode('\', \'', self::ALLOWED_PROTOCOLS))); |
| 18 |
} |
| 19 |
|
| 20 |
if (! file_exists($pathToImage)) { |
| 21 |
throw new InvalidArgumentException("`{$pathToImage}` does not exist"); |
| 22 |
} |
| 23 |
|
| 24 |
$this->pathToImage = $pathToImage; |
| 25 |
} |
| 26 |
|
| 27 |
public function mime(): string |
| 28 |
{ |
| 29 |
return mime_content_type($this->pathToImage); |
| 30 |
} |
| 31 |
|
| 32 |
public function path(): string |
| 33 |
{ |
| 34 |
return $this->pathToImage; |
| 35 |
} |
| 36 |
|
| 37 |
public function extension(): string |
| 38 |
{ |
| 39 |
$extension = pathinfo($this->pathToImage, PATHINFO_EXTENSION); |
| 40 |
|
| 41 |
return strtolower($extension); |
| 42 |
} |
| 43 |
|
| 44 |
protected function isProtocolAllowed($filename) |
| 45 |
{ |
| 46 |
if (false === $parsedFilename = \parse_url($filename)) { |
| 47 |
throw new InvalidArgumentException('The filename is not valid.'); |
| 48 |
} |
| 49 |
|
| 50 |
$protocol = isset($parsedFilename['scheme']) ? \mb_strtolower($parsedFilename['scheme']) : 'file'; |
| 51 |
|
| 52 |
if ( |
| 53 |
\PHP_OS_FAMILY === 'Windows' |
| 54 |
&& \strlen($protocol) === 1 |
| 55 |
&& \preg_match(self::WINDOWS_LOCAL_FILENAME_REGEX, $filename) |
| 56 |
) { |
| 57 |
$protocol = 'file'; |
| 58 |
} |
| 59 |
|
| 60 |
return \in_array($protocol, self::ALLOWED_PROTOCOLS, true); |
| 61 |
} |
| 62 |
} |
| 63 |
|