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