|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\ImageOptimizer; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Log\LoggerInterface; |
|
6
|
|
|
use Symfony\Component\Process\Process; |
|
7
|
|
|
use Spatie\ImageOptimizer\Optimizers\Optimizer; |
|
8
|
|
|
|
|
9
|
|
|
class ImageOptimizer |
|
10
|
|
|
{ |
|
11
|
|
|
protected $optimizers = []; |
|
12
|
|
|
|
|
13
|
|
|
/** @var \Psr\Log\LoggerInterface */ |
|
14
|
|
|
protected $logger; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct() |
|
17
|
|
|
{ |
|
18
|
|
|
$this->useLogger(new DummyLogger()); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function getOptimizers(): array |
|
22
|
|
|
{ |
|
23
|
|
|
return $this->optimizers; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function addOptimizer(Optimizer $optimizer) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->optimizers[] = $optimizer; |
|
29
|
|
|
|
|
30
|
|
|
return $this; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function setOptimizers(array $optimizers) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->optimizers = []; |
|
36
|
|
|
|
|
37
|
|
|
foreach ($optimizers as $optimizer) { |
|
38
|
|
|
$this->addOptimizer($optimizer); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return $this; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function useLogger(LoggerInterface $log) |
|
45
|
|
|
{ |
|
46
|
|
|
$this->logger = $log; |
|
47
|
|
|
|
|
48
|
|
|
return $this; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function optimize(string $pathToImage) |
|
52
|
|
|
{ |
|
53
|
|
|
$image = new Image($pathToImage); |
|
54
|
|
|
|
|
55
|
|
|
$this->logger->info("Start optimizing {$pathToImage}"); |
|
56
|
|
|
|
|
57
|
|
|
foreach($this->optimizers as $optimizer) { |
|
58
|
|
|
$this->applyOptimizer($optimizer, $image); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
protected function applyOptimizer(Optimizer $optimizer, Image $image) |
|
63
|
|
|
{ |
|
64
|
|
|
if (! $optimizer->canHandle($image)) { |
|
65
|
|
|
return; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
$optimizerClass = get_class($optimizer); |
|
69
|
|
|
|
|
70
|
|
|
$this->logger->info("Using optimizer: `{$optimizerClass}`"); |
|
71
|
|
|
|
|
72
|
|
|
$optimizer->setImagePath($image->path()); |
|
73
|
|
|
|
|
74
|
|
|
$command = $optimizer->getCommand(); |
|
75
|
|
|
|
|
76
|
|
|
$this->logger->info("Executing `{$command}`"); |
|
77
|
|
|
|
|
78
|
|
|
$process = new Process($command); |
|
79
|
|
|
|
|
80
|
|
|
$process->run(); |
|
81
|
|
|
|
|
82
|
|
|
$this->logResult($process); |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
protected function logResult(Process $process) |
|
86
|
|
|
{ |
|
87
|
|
|
if ($process->isSuccessful()) { |
|
88
|
|
|
$this->logger->info("Process successfully ended with output `{$process->getOutput()}`"); |
|
89
|
|
|
|
|
90
|
|
|
return; |
|
91
|
|
|
} |
|
92
|
|
|
|
|
93
|
|
|
$this->logger->error("Process errored with `{$process->getErrorOutput()}`}"); |
|
94
|
|
|
} |
|
95
|
|
|
} |
|
96
|
|
|
|