Passed
Push — master ( ce0bb5...074d95 )
by Adrien
10:39
created

ImageResizer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 93.33%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 37
ccs 14
cts 15
cp 0.9333
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A resize() 0 20 4
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 18
    public function __construct(ImagineInterface $imagine)
24
    {
25 18
        $this->imagine = $imagine;
26 18
    }
27
28
    /**
29
     * Resize image as JPG or WEBP and return the path to the resized version
30
     */
31 18
    public function resize(Image $image, int $maxHeight, bool $useWebp): string
32
    {
33 18
        if ($image->getMime() === 'image/svg+xml') {
34 6
            return $image->getPath();
35
        }
36
37 12
        $maxHeight = min($maxHeight, $image->getHeight());
38
39 12
        $basename = pathinfo($image->getFilename(), PATHINFO_FILENAME);
40 12
        $extension = $useWebp ? '.webp' : '.jpg';
41 12
        $path = realpath('.') . '/' . self::CACHE_IMAGE_PATH . $basename . '-' . $maxHeight . $extension;
0 ignored issues
show
Bug introduced by
Are you sure $basename of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

41
        $path = realpath('.') . '/' . self::CACHE_IMAGE_PATH . /** @scrutinizer ignore-type */ $basename . '-' . $maxHeight . $extension;
Loading history...
42
43 12
        if (file_exists($path)) {
44
            return $path;
45
        }
46
47 12
        $image = $this->imagine->open($image->getPath());
48 12
        $image->thumbnail(new Box(1000000, $maxHeight))->save($path);
49
50 12
        return $path;
51
    }
52
}
53