Failed Conditions
Push — master ( f2bb18...5e6761 )
by Adrien
02:12
created

ImageResizer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecodev\Felix\Service;
6
7
use Ecodev\Felix\Model\Image;
8
use Imagine\Image\Box;
9
use Imagine\Image\ImagineInterface;
10
11
/**
12
 * Service to resize image's images
13
 */
14
class ImageResizer
15
{
16
    private const CACHE_IMAGE_PATH = 'data/cache/images/';
17
18
    /**
19
     * @var ImagineInterface
20
     */
21
    private $imagine;
22
23
    public function __construct(ImagineInterface $imagine)
24
    {
25
        $this->imagine = $imagine;
26
    }
27
28
    /**
29
     * Resize image as JPG and return the path to the resized version
30
     *
31
     * @param Image $image
32
     * @param int $maxHeight
33
     *
34
     * @return string
35
     */
36
    public function resize(Image $image, int $maxHeight): string
37
    {
38
        if ($image->getHeight() <= $maxHeight || $image->getMime() === 'image/svg+xml') {
39
            return $image->getPath();
40
        }
41
42
        $basename = pathinfo($image->getFilename(), PATHINFO_FILENAME);
43
        $path = realpath('.') . '/' . self::CACHE_IMAGE_PATH . $basename . '-' . $maxHeight . '.jpg';
44
45
        if (file_exists($path)) {
46
            return $path;
47
        }
48
49
        $image = $this->imagine->open($image->getPath());
50
        $image->thumbnail(new Box(1000000, $maxHeight))->save($path);
51
52
        return $path;
53
    }
54
}
55