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

ImageResizer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 35
ccs 13
cts 14
cp 0.9286
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A resize() 0 18 5
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