1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace yiicod\easyimage\tools; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Imagine\Image\Box; |
7
|
|
|
use Imagine\Image\BoxInterface; |
8
|
|
|
use Imagine\Image\ManipulatorInterface; |
9
|
|
|
use Imagine\Image\Point; |
10
|
|
|
use yiicod\easyimage\base\ToolInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class Thumbnail |
14
|
|
|
* Thumbnail image tool |
15
|
|
|
* |
16
|
|
|
* @author Virchenko Maksim <[email protected]> |
17
|
|
|
* |
18
|
|
|
* @package yiicod\easyimage\tools |
19
|
|
|
*/ |
20
|
|
|
class Thumbnail implements ToolInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* Handle image |
24
|
|
|
* |
25
|
|
|
* @param ManipulatorInterface $image |
26
|
|
|
* @param array $params |
27
|
|
|
* |
28
|
|
|
* @return ManipulatorInterface |
29
|
|
|
* |
30
|
|
|
* @throws Exception |
31
|
|
|
*/ |
32
|
|
|
public static function handle(ManipulatorInterface $image, array $params = []): ManipulatorInterface |
33
|
|
|
{ |
34
|
|
|
if (false === isset($params['width']) && false === isset($params['height'])) { |
35
|
|
|
throw new Exception('Params "width" or "height" is required for action "Thumbnail"'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** @var BoxInterface $size */ |
39
|
|
|
$size = $image->getSize(); |
|
|
|
|
40
|
|
|
|
41
|
|
|
if (isset($params['width'], $params['height'])) { |
42
|
|
|
$newSize = $size->widen($params['width']); |
43
|
|
|
|
44
|
|
|
if ($newSize->getHeight() < $params['height']) { |
45
|
|
|
$newSize = $newSize->heighten($params['height']); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$image->resize($newSize); |
49
|
|
|
$result = $image->crop(new Point( |
50
|
|
|
max(0, round(($newSize->getWidth() - $params['width']) / 2)), |
51
|
|
|
max(0, round(($newSize->getHeight() - $params['height']) / 2)) |
52
|
|
|
), new Box($params['width'], $params['height'])); |
53
|
|
|
} elseif (isset($params['width'])) { |
54
|
|
|
$result = $image->resize($size->widen($params['width'])); |
55
|
|
|
} elseif (isset($params['height'])) { |
56
|
|
|
$result = $image->resize($size->heighten($params['height'])); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $result; |
|
|
|
|
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: