Skip to content

Commit

Permalink
Merge pull request #211 from Sonicrrrr/main
Browse files Browse the repository at this point in the history
Update Image.php
  • Loading branch information
timvandijck authored May 3, 2024
2 parents a639919 + 53011ba commit 89847b5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
26 changes: 25 additions & 1 deletion src/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

Expand All @@ -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);
}
}
8 changes: 4 additions & 4 deletions src/OptimizerChain.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 89847b5

Please sign in to comment.