diff --git a/src/Image.php b/src/Image.php index b4d3981..f7def19 100644 --- a/src/Image.php +++ b/src/Image.php @@ -7,10 +7,16 @@ class Image { protected $pathToImage = ''; + protected const ALLOWED_PROTOCOLS = ['file']; + protected const WINDOWS_LOCAL_FILENAME_REGEX = '/^[a-z]:(?:[\\\\\/]?(?:[\w\s!#()-]+|[\.]{1,2})+)*[\\\\\/]?/i'; public function __construct(string $pathToImage) { - if (! file_exists($pathToImage)) { + if (!$this->isProtocolAllowed($pathToImage)) { + throw new InvalidArgumentException(\sprintf('The output file scheme is not supported. Expected one of [\'%s\'].', \implode('\', \'', self::ALLOWED_PROTOCOLS))); + } + + if (!file_exists($pathToImage)) { throw new InvalidArgumentException("`{$pathToImage}` does not exist"); } @@ -33,4 +39,22 @@ public function extension(): string return strtolower($extension); } + protected function isProtocolAllowed($filename) + { + if (false === $parsedFilename = \parse_url($filename)) { + throw new InvalidArgumentException('The filename is not valid.'); + } + + $protocol = isset($parsedFilename['scheme']) ? \mb_strtolower($parsedFilename['scheme']) : 'file'; + + if ( + \PHP_OS_FAMILY === 'Windows' + && \strlen($protocol) === 1 + && \preg_match(self::WINDOWS_LOCAL_FILENAME_REGEX, $filename) + ) { + $protocol = 'file'; + } + + return \in_array($protocol, self::ALLOWED_PROTOCOLS, true); + } } diff --git a/src/OptimizerChain.php b/src/OptimizerChain.php index 074e991..7bf4018 100644 --- a/src/OptimizerChain.php +++ b/src/OptimizerChain.php @@ -64,13 +64,13 @@ public function useLogger(LoggerInterface $log) public function optimize(string $pathToImage, string $pathToOutput = null) { if ($pathToOutput) { - copy($pathToImage, $pathToOutput); - + $check = copy($pathToImage, $pathToOutput); + if($check == false){ + throw new InvalidArgumentException("Cannot copy file"); + } $pathToImage = $pathToOutput; } - $image = new Image($pathToImage); - $this->logger->info("Start optimizing {$pathToImage}"); foreach ($this->optimizers as $optimizer) {