Passed
Push — master ( 240c83...03f39b )
by Mathias
06:41
created

ImageSetHandler::createImage()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 9
dl 0
loc 19
rs 9.6111
c 1
b 1
f 0
cc 5
nc 5
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Core\Service;
6
7
use Core\Entity\ImageSetInterface;
8
use Imagine\Image\Box;
9
use Imagine\Image\ImageInterface as ImagineImage;
10
use Imagine\Image\ImagineInterface;
11
12
use Psr\Container\ContainerInterface;
13
14
class ImageSetHandler
15
{
16
    /**
17
     * @var ImagineInterface
18
     */
19
    private ImagineInterface $imagine;
20
21
    public function __construct(
22
        ImagineInterface $imagine
23
    )
24
    {
25
        $this->imagine = $imagine;
26
    }
27
28
    public static function factory(ContainerInterface $container)
29
    {
30
        $imagine = $container->get('Imagine');
31
32
        return new self($imagine);
33
    }
34
35
    /**
36
     * @param $specs
37
     * @param array $imageData
38
     * @return array|ImagineImage[]
39
     */
40
    public function createImages($specs, array $imageData): array
41
    {
42
        $images = [];
43
        $imagine = $this->imagine;
44
        $tmpFile = $imageData['tmp_name'];
45
46
        $original = $imagine->open($tmpFile);
47
        $images['original'] = $original;
48
49
        foreach($specs as $key => $size){
50
            $newImage = ImageSetInterface::THUMBNAIL == $key
51
                ? $original->thumbnail(new Box($size[0], $size[1]), ImagineImage::THUMBNAIL_INSET)
52
                : $this->createImage($original, $size);
53
54
            if ($newImage) {
55
                $images[$key] = $newImage;
56
            }
57
        }
58
59
        return $images;
60
    }
61
62
    private function createImage(ImagineImage $image, $size)
63
    {
64
        $imageSize = $image->getSize();
65
66
        if ($imageSize->getWidth() <= $size[0] && $imageSize->getHeight() <= $size[1]) {
67
            return null;
68
        }
69
70
        if ($imageSize->getWidth() > $size[0]) {
71
            $imageSize = $imageSize->widen($size[0]);
72
        }
73
74
        if ($imageSize->getHeight() > $size[1]) {
75
            $imageSize = $imageSize->heighten($size[1]);
76
        }
77
78
        $image = $image->resize($imageSize);
79
80
        return $image;
81
    }
82
}