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 $imagePath) |
52
|
|
|
{ |
53
|
|
|
$this->logger->info("start optimizing {$imagePath}"); |
54
|
|
|
|
55
|
|
|
$mimeType = mime_content_type($imagePath); |
56
|
|
|
|
57
|
|
|
collect($this->optimizers) |
58
|
|
|
->filter(function (Optimizer $optimizer) use ($mimeType) { |
59
|
|
|
return $optimizer->canHandle($mimeType); |
60
|
|
|
}) |
61
|
|
|
->each(function (Optimizer $optimizer) use ($imagePath) { |
62
|
|
|
$optimizerClass = get_class($optimizer); |
63
|
|
|
|
64
|
|
|
$this->logger->info("Using optimizer: `{$optimizerClass}`"); |
65
|
|
|
|
66
|
|
|
$optimizer->setImagePath($imagePath); |
67
|
|
|
|
68
|
|
|
$command = $optimizer->getCommand(); |
69
|
|
|
|
70
|
|
|
$this->logger->info("Executing `{$command}`"); |
71
|
|
|
|
72
|
|
|
$process = new Process($optimizer->getCommand()); |
73
|
|
|
|
74
|
|
|
$process->run(); |
75
|
|
|
|
76
|
|
|
$this->logResult($process); |
77
|
|
|
}); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function logResult(Process $process) |
81
|
|
|
{ |
82
|
|
|
if ($process->isSuccessful()) { |
83
|
|
|
$this->logger->info("Process successfully ended with output `{$process->getOutput()}`"); |
84
|
|
|
|
85
|
|
|
return; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
$this->logger->error("Process errored with `{$process->getErrorOutput()}`}"); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|