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