Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make compatible with PSR-12 formatting standard #82

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .phpcs.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0"?>
<ruleset name="PSR12 Coding Standards">
<description>A custom set of code standard rules</description>

<rule ref="PSR12"/>
<rule ref="Generic.Arrays.DisallowLongArraySyntax"/>

<rule ref="Squiz.Classes.ValidClassName.NotCamelCaps">
<exclude-pattern>tests/*</exclude-pattern>
</rule>

<rule ref="PSR1.Methods.CamelCapsMethodName.NotCamelCaps">
<exclude-pattern>tests/*</exclude-pattern>
</rule>

<rule ref="PSR1.Classes.ClassDeclaration.MultipleClasses">
<exclude-pattern>tests/*</exclude-pattern>
</rule>

<exclude-pattern>*\.(?!php$)</exclude-pattern>
<exclude-pattern>vendor/*</exclude-pattern>
</ruleset>
11 changes: 10 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"ext-gd": "*"
"ext-gd": "*",
"squizlabs/php_codesniffer": "^3.6"
},
"scripts": {
"phpcs": "vendor/bin/phpcs -s --standard=./.phpcs.xml ./",
"phpcbf": "vendor/bin/phpcbf --standard=./.phpcs.xml ./",
"test": [
"composer validate --strict",
"@phpcs"
]
}
}
16 changes: 11 additions & 5 deletions src/ImageOptimizer/ChainOptimizer.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer;
Expand All @@ -25,19 +26,24 @@ public function __construct(array $optimizers, bool $executeFirst, LoggerInterfa
public function optimize(string $filepath): void
{
$exceptions = [];
foreach($this->optimizers as $optimizer) {
foreach ($this->optimizers as $optimizer) {
try {
$optimizer->optimize($filepath);

if($this->executeFirst) break;
if ($this->executeFirst) {
break;
}
} catch (Exception $e) {
$this->logger->error('Error during image optimization. See exception for more details.', [ 'exception' => $e ]);
$this->logger->error(
'Error during image optimization. See exception for more details.',
['exception' => $e]
);
$exceptions[] = $e;
}
}

if(count($exceptions) === count($this->optimizers)) {
if (count($exceptions) === count($this->optimizers)) {
throw new Exception(sprintf('All optimizers failed to optimize the file: %s', $filepath));
}
}
}
}
7 changes: 6 additions & 1 deletion src/ImageOptimizer/ChangedOutputOptimizer.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer;
Expand All @@ -19,7 +20,11 @@ public function optimize(string $filepath): void
$fileInfo = pathinfo($filepath);
$outputFilepath = str_replace(
['%basename%', '%filename%', '%ext%'],
[$fileInfo['dirname'], $fileInfo['filename'], isset($fileInfo['extension']) ? '.'.$fileInfo['extension'] : ''],
[
$fileInfo['dirname'],
$fileInfo['filename'],
isset($fileInfo['extension']) ? '.' . $fileInfo['extension'] : ''
],
$this->outputPattern
);

Expand Down
35 changes: 24 additions & 11 deletions src/ImageOptimizer/Command.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer;

use function function_exists;
use ImageOptimizer\Exception\CommandNotFound;
use ImageOptimizer\Exception\Exception;
use Symfony\Component\Process\Exception\RuntimeException;
Expand All @@ -17,12 +17,18 @@ final class Command

public function __construct(string $bin, array $args = [], ?float $timeout = null)
{
if(!function_exists('exec')) {
throw new Exception('"exec" function is not available. Please check if it is not listed as "disable_functions" in your "php.ini" file.');
if (!function_exists('exec')) {
throw new Exception(
'"exec" function is not available. ' .
'Please check if it is not listed as "disable_functions" in your "php.ini" file.'
);
}

if(!function_exists('proc_open')) {
throw new RuntimeException('"proc_open" function is not available. Please check if it is not listed as "disable_functions" in your "php.ini" file.');
if (!function_exists('proc_open')) {
throw new RuntimeException(
'"proc_open" function is not available. ' .
'Please check if it is not listed as "disable_functions" in your "php.ini" file.'
);
}

$this->cmd = $bin;
Expand All @@ -38,17 +44,24 @@ public function execute(array $customArgs = []): void
try {
$exitCode = $process->run();
$commandLine = $process->getCommandLine();
$output = $process->getOutput().PHP_EOL.$process->getErrorOutput();
$output = $process->getOutput() . PHP_EOL . $process->getErrorOutput();

if($exitCode == 127) {
if ($exitCode == 127) {
throw new CommandNotFound(sprintf('Command "%s" not found.', $this->cmd));
}

if($exitCode !== 0 || stripos($output, 'error') !== false || stripos($output, 'permission') !== false) {
throw new Exception(sprintf('Command failed, return code: %d, command: %s, stderr: %s', $exitCode, $commandLine, trim($output)));
if ($exitCode !== 0 || stripos($output, 'error') !== false || stripos($output, 'permission') !== false) {
throw new Exception(
sprintf(
'Command failed, return code: %d, command: %s, stderr: %s',
$exitCode,
$commandLine,
trim($output)
)
);
}
} catch(RuntimeException $e) {
} catch (RuntimeException $e) {
throw new Exception($e->getMessage(), $e->getCode(), $e);
}
}
}
}
6 changes: 3 additions & 3 deletions src/ImageOptimizer/CommandOptimizer.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer;


class CommandOptimizer implements Optimizer
{
private $command;
Expand All @@ -19,7 +19,7 @@ public function optimize(string $filepath): void
{
$customArgs = [$filepath];

if($this->extraArgs) {
if ($this->extraArgs) {
$customArgs = array_merge(
is_callable($this->extraArgs) ? call_user_func($this->extraArgs, $filepath) : $this->extraArgs,
$customArgs
Expand All @@ -28,4 +28,4 @@ public function optimize(string $filepath): void

$this->command->execute($customArgs);
}
}
}
3 changes: 2 additions & 1 deletion src/ImageOptimizer/Exception/CommandNotFound.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer\Exception;

class CommandNotFound extends Exception
{
}
}
3 changes: 2 additions & 1 deletion src/ImageOptimizer/Exception/Exception.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer\Exception;

class Exception extends \RuntimeException
{
}
}
4 changes: 2 additions & 2 deletions src/ImageOptimizer/Optimizer.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer;


use ImageOptimizer\Exception\Exception;

interface Optimizer
Expand All @@ -14,4 +14,4 @@ interface Optimizer
* @throws Exception
*/
public function optimize(string $filepath): void;
}
}
38 changes: 26 additions & 12 deletions src/ImageOptimizer/OptimizerFactory.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer;


use ImageOptimizer\Exception\Exception;
use ImageOptimizer\TypeGuesser\TypeGuesser;
use Psr\Log\LoggerInterface;
Expand All @@ -13,7 +13,7 @@

class OptimizerFactory
{
const OPTIMIZER_SMART = 'smart';
public const OPTIMIZER_SMART = 'smart';

private $optimizers = [];
private $options;
Expand Down Expand Up @@ -78,10 +78,12 @@ protected function setUpOptimizers(): void
$this->commandOptimizer('optipng', $this->options['optipng_options'])
);
$this->optimizers['pngquant'] = $this->wrap(
$this->commandOptimizer('pngquant', $this->options['pngquant_options'],
function($filepath){
$this->commandOptimizer(
'pngquant',
$this->options['pngquant_options'],
function ($filepath) {
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
return ['--ext='.($ext ? '.'.$ext : ''), '--'];
return ['--ext=' . ($ext ? '.' . $ext : ''), '--'];
}
)
);
Expand Down Expand Up @@ -109,7 +111,9 @@ function($filepath){
$this->commandOptimizer('jpegoptim', $this->options['jpegoptim_options'])
);
$this->optimizers['jpegtran'] = $this->wrap(
$this->commandOptimizer('jpegtran', $this->options['jpegtran_options'],
$this->commandOptimizer(
'jpegtran',
$this->options['jpegtran_options'],
function ($filepath) {
return ['-outfile', $filepath];
}
Expand All @@ -121,14 +125,16 @@ function ($filepath) {
], $this->options['execute_only_first_jpeg_optimizer'], $this->logger));

$this->optimizers['svg'] = $this->optimizers['svgo'] = $this->wrap(
$this->commandOptimizer('svgo', $this->options['svgo_options'],
$this->commandOptimizer(
'svgo',
$this->options['svgo_options'],
function ($filepath) {
return ['--input' => $filepath, '--output' => $filepath];
}
)
);

foreach($this->options['custom_optimizers'] as $key => $options) {
foreach ($this->options['custom_optimizers'] as $key => $options) {
$this->optimizers[$key] = $this->wrap(
$this->commandOptimizer($options['command'], isset($options['args']) ? $options['args'] : [])
);
Expand All @@ -152,8 +158,16 @@ private function commandOptimizer(string $command, array $args, $extraArgs = nul

private function wrap(Optimizer $optimizer): Optimizer
{
$optimizer = $optimizer instanceof ChangedOutputOptimizer ? $optimizer : new ChangedOutputOptimizer($this->option('output_filepath_pattern'), $optimizer);
return $this->option('ignore_errors', true) ? new SuppressErrorOptimizer($optimizer, $this->logger) : $optimizer;
$optimizer = $optimizer instanceof ChangedOutputOptimizer ?
$optimizer :
new ChangedOutputOptimizer(
$this->option('output_filepath_pattern'),
$optimizer
);

return $this->option('ignore_errors', true) ?
new SuppressErrorOptimizer($optimizer, $this->logger) :
$optimizer;
}

private function unwrap(Optimizer $optimizer): Optimizer
Expand All @@ -164,7 +178,7 @@ private function unwrap(Optimizer $optimizer): Optimizer
private function executable(string $name): string
{
$executableFinder = $this->executableFinder;
return $this->option($name.'_bin', function() use($name, $executableFinder){
return $this->option($name . '_bin', function () use ($name, $executableFinder) {
return $executableFinder->find($name, $name);
});
}
Expand All @@ -181,7 +195,7 @@ private function option(string $name, $default = null)
*/
public function get(string $name = self::OPTIMIZER_SMART): Optimizer
{
if(!isset($this->optimizers[$name])) {
if (!isset($this->optimizers[$name])) {
throw new Exception(sprintf('Optimizer "%s" not found', $name));
}

Expand Down
5 changes: 3 additions & 2 deletions src/ImageOptimizer/SmartOptimizer.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer;
Expand All @@ -25,10 +26,10 @@ public function optimize(string $filepath): void
{
$type = $this->typeGuesser->guess($filepath);

if(!isset($this->optimizers[$type])) {
if (!isset($this->optimizers[$type])) {
throw new Exception(sprintf('Optimizer for type "%s" not found.', $type));
}

$this->optimizers[$type]->optimize($filepath);
}
}
}
9 changes: 6 additions & 3 deletions src/ImageOptimizer/SuppressErrorOptimizer.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?php

declare(strict_types=1);

namespace ImageOptimizer;


use ImageOptimizer\Exception\Exception;
use Psr\Log\LoggerInterface;

Expand All @@ -23,12 +23,15 @@ public function optimize(string $filepath): void
try {
$this->optimizer->optimize($filepath);
} catch (Exception $e) {
$this->logger->error('Error during image optimization. See exception for more details.', [ 'exception' => $e ]);
$this->logger->error(
'Error during image optimization. See exception for more details.',
['exception' => $e]
);
}
}

public function unwrap(): Optimizer
{
return $this->optimizer instanceof WrapperOptimizer ? $this->optimizer->unwrap() : $this->optimizer;
}
}
}
Loading