1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace tkanstantsin\fileupload\formatter\adapter; |
5
|
|
|
|
6
|
|
|
use ImageOptimizer\Optimizer; |
7
|
|
|
use ImageOptimizer\OptimizerFactory; |
8
|
|
|
use tkanstantsin\fileupload\model\BaseObject; |
9
|
|
|
use tkanstantsin\fileupload\model\IFile; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class ImageOptimizer |
13
|
|
|
* Optimize images using `ps/image-optimizer` |
14
|
|
|
* @see https://github.com/psliwa/image-optimizer |
15
|
|
|
*/ |
16
|
|
|
class PsImageOptimizer extends BaseObject implements IFormatAdapter |
17
|
|
|
{ |
18
|
|
|
public const DEFAULT_CONFIG = [ |
19
|
|
|
'ignore_errors' => true, |
20
|
|
|
'execute_only_first_jpeg_optimizer' => false, |
21
|
|
|
'execute_only_first_png_optimizer' => false, |
22
|
|
|
'jpegoptim_options' => ['-m90', '--strip-all', '--all-progressive'], |
23
|
|
|
'jpegtran_options' => ['-optimize', '-progressive', '-perfect'], |
24
|
|
|
]; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var string|null |
28
|
|
|
*/ |
29
|
|
|
public $tempDir; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var array |
33
|
|
|
*/ |
34
|
|
|
public $optimizerConfig = self::DEFAULT_CONFIG; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @inheritdoc |
38
|
|
|
*/ |
39
|
|
|
public function init(): void |
40
|
|
|
{ |
41
|
|
|
parent::init(); |
42
|
|
|
if (!class_exists(OptimizerFactory::class)) { |
43
|
|
|
trigger_error(sprintf('%s class not found', OptimizerFactory::class)); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Applies filters or something to content and return it |
50
|
|
|
* |
51
|
|
|
* @param IFile $file |
52
|
|
|
* @param $content |
53
|
|
|
* |
54
|
|
|
* @return mixed |
55
|
|
|
* @throws \ImageOptimizer\Exception\Exception |
56
|
|
|
*/ |
57
|
|
|
public function exec(IFile $file, $content) |
58
|
|
|
{ |
59
|
|
|
$tmpPath = tempnam($this->getTempDir(), ''); |
60
|
|
|
file_put_contents($tmpPath, $content); |
61
|
|
|
$this->getOptimizer()->optimize($tmpPath); |
62
|
|
|
$content = file_get_contents($tmpPath); |
63
|
|
|
|
64
|
|
|
@unlink($tmpPath); |
|
|
|
|
65
|
|
|
|
66
|
|
|
return $content; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @return string |
71
|
|
|
*/ |
72
|
|
|
protected function getTempDir(): string |
73
|
|
|
{ |
74
|
|
|
return (string) ($this->tempDir ?? sys_get_temp_dir()); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param string $name |
79
|
|
|
* |
80
|
|
|
* @return Optimizer |
81
|
|
|
* @throws \ImageOptimizer\Exception\Exception |
82
|
|
|
*/ |
83
|
|
|
protected function getOptimizer($name = OptimizerFactory::OPTIMIZER_SMART): Optimizer |
84
|
|
|
{ |
85
|
|
|
return (new OptimizerFactory($this->optimizerConfig))->get($name); |
86
|
|
|
} |
87
|
|
|
} |
If you suppress an error, we recommend checking for the error condition explicitly: