Passed
Push — master ( 73bfc2...a878a7 )
by Adrien
13:45 queued 10:48
created

ImageResizer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 31
ccs 12
cts 13
cp 0.9231
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 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 18
    public function __construct(private readonly ImagineInterface $imagine)
19
    {
20
    }
21
22
    /**
23
     * Resize image as JPG or WEBP and return the path to the resized version.
24
     */
25 18
    public function resize(Image $image, int $maxHeight, bool $useWebp): string
26
    {
27 18
        if ($image->getMime() === 'image/svg+xml') {
28 6
            return $image->getPath();
29
        }
30
31 12
        $maxHeight = min($maxHeight, $image->getHeight());
32
33 12
        $basename = pathinfo($image->getFilename(), PATHINFO_FILENAME);
34 12
        $extension = $useWebp ? '.webp' : '.jpg';
35 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

35
        $path = realpath('.') . '/' . self::CACHE_IMAGE_PATH . /** @scrutinizer ignore-type */ $basename . '-' . $maxHeight . $extension;
Loading history...
36
37 12
        if (file_exists($path)) {
38
            return $path;
39
        }
40
41 12
        $image = $this->imagine->open($image->getPath());
42 12
        $image->thumbnail(new Box(1_000_000, $maxHeight))->save($path);
0 ignored issues
show
Bug introduced by
The constant Ecodev\Felix\Service\1_000_000 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
43
44 12
        return $path;
45
    }
46
}
47