Passed
Push — master ( 1e501a...58b99e )
by Adrien
08:31
created

ImageResizer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 12
    public function __construct(ImagineInterface $imagine)
24
    {
25 12
        $this->imagine = $imagine;
26 12
    }
27
28
    /**
29
     * Resize image as JPG and return the path to the resized version
30
     */
31 12
    public function resize(Image $image, int $maxHeight, bool $useWebp): string
32
    {
33 12
        if ($image->getHeight() <= $maxHeight || $image->getMime() === 'image/svg+xml') {
34 10
            return $image->getPath();
35
        }
36
37 2
        $basename = pathinfo($image->getFilename(), PATHINFO_FILENAME);
38 2
        $extension = $useWebp ? '.webp' : '.jpg';
39 2
        $path = realpath('.') . '/' . self::CACHE_IMAGE_PATH . $basename . '-' . $maxHeight . $extension;
40
41 2
        if (file_exists($path)) {
42
            return $path;
43
        }
44
45 2
        $image = $this->imagine->open($image->getPath());
46 2
        $image->thumbnail(new Box(1000000, $maxHeight))->save($path);
47
48 2
        return $path;
49
    }
50
}
51