generated from locomotivemtl/charcoal-contrib-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImageCompressor.php
102 lines (89 loc) · 2.57 KB
/
ImageCompressor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace Charcoal\ImageCompression;
use Charcoal\ImageCompression\Provider\Chain\ChainProvider;
use Charcoal\ImageCompression\Provider\ProviderException;
use Charcoal\ImageCompression\Provider\ProviderInterface;
use Exception;
use InvalidArgumentException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
/**
* Image Compressor
*/
class ImageCompressor implements
Provider\ProviderInterface,
LoggerAwareInterface
{
use LoggerAwareTrait;
private ProviderInterface $provider;
/**
* @param array<string, mixed> $data Class dependencies.
*/
public function __construct(array $data)
{
$this->setLogger($data['logger']);
$this->setProviders($data['providers']);
}
/**
* @param ProviderInterface[] $providers List of providers for the compressor.
* @throws InvalidArgumentException If no provider is defined.
*/
public function setProviders(array $providers): self
{
if (!$providers) {
throw new InvalidArgumentException(
'Expected at least one image compression provider'
);
}
if (\count($providers) === 1) {
$this->setProvider(\reset($providers));
}
$this->provider = new ChainProvider($providers);
return $this;
}
public function setProvider(ProviderInterface $provider): self
{
$this->provider = $provider;
return $this;
}
/**
* {@inheritdoc}
*
* @throws ProviderException When a provider is failing.
*/
public function compress(string $source, ?string $target = null): bool
{
try {
return $this->provider->compress($source, $target);
} catch (Exception $e) {
throw new ProviderException(
\sprintf(
'There was a problem while compressing images using [%s]',
\get_class($this->provider)
),
$e->getCode(),
$e
);
}
}
/**
* {@inheritdoc}
*
* @throws ProviderException When a provider is failing.
*/
public function compressionCount(): int
{
try {
return $this->provider->compressionCount();
} catch (Exception $e) {
throw new ProviderException(
\sprintf(
'There was a problem retrieving the compression count from [%s]',
\get_class($this->provider)
),
$e->getCode(),
$e
);
}
}
}