1 | <?php |
||
2 | |||
3 | namespace Mostafaznv\Larupload\Actions; |
||
4 | |||
5 | use Exception; |
||
6 | use Illuminate\Http\UploadedFile; |
||
7 | use Spatie\ImageOptimizer\Optimizer; |
||
8 | use Spatie\ImageOptimizer\OptimizerChain; |
||
9 | use Spatie\ImageOptimizer\OptimizerChainFactory; |
||
10 | |||
11 | class OptimizeImageAction |
||
12 | { |
||
13 | private readonly array $config; |
||
14 | |||
15 | public function __construct(private readonly UploadedFile $file) |
||
16 | { |
||
17 | $this->config = config('larupload.optimize-image'); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
18 | } |
||
19 | |||
20 | public static function make(UploadedFile $file): self |
||
21 | { |
||
22 | return new self($file); |
||
23 | } |
||
24 | |||
25 | |||
26 | public function process(): UploadedFile |
||
27 | { |
||
28 | $this->optimizer()->optimize( |
||
29 | $this->file->getRealPath(), |
||
30 | ); |
||
31 | |||
32 | return new UploadedFile( |
||
33 | path: $this->file->getRealPath(), |
||
34 | originalName: $this->file->getClientOriginalName(), |
||
35 | mimeType: $this->file->getClientMimeType() |
||
36 | ); |
||
37 | } |
||
38 | |||
39 | private function optimizer(): OptimizerChain |
||
40 | { |
||
41 | $optimizer = OptimizerChainFactory::create(); |
||
42 | $optimizer->setOptimizers($this->optimizers()); |
||
43 | $optimizer->setTimeout($this->config['timeout']); |
||
44 | |||
45 | return $optimizer; |
||
46 | } |
||
47 | |||
48 | private function optimizers(): array |
||
49 | { |
||
50 | return collect($this->config['optimizers']) |
||
51 | ->mapWithKeys(function(array $options, string $optimizerClass) { |
||
52 | if (!is_a($optimizerClass, Optimizer::class, true)) { |
||
53 | $optimizerInterface = Optimizer::class; |
||
54 | |||
55 | throw new Exception("Configured optimizer `{$optimizerClass}` does not implement `{$optimizerInterface}`."); |
||
56 | } |
||
57 | |||
58 | $newOptimizerClass = new $optimizerClass(); |
||
59 | $newOptimizerClass->setOptions($options); |
||
60 | |||
61 | return [$optimizerClass => $newOptimizerClass]; |
||
62 | }) |
||
63 | ->toArray(); |
||
64 | } |
||
65 | } |
||
66 |