Passed
Push — master ( 38d4f3...30ab2e )
by Adrien
14:46
created

ImageResizer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 90.91%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 20
c 1
b 0
f 0
dl 0
loc 54
ccs 20
cts 22
cp 0.9091
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
    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
        $extension = $useWebp ? '.webp' : '.jpg';
34 12
        $path = $this->getCachePath($image, '-' . $maxHeight . $extension);
35
36 12
        if (file_exists($path)) {
37
            return $path;
38
        }
39
40 12
        $image = $this->imagine->open($image->getPath());
41 12
        $image->thumbnail(new Box(1_000_000, $maxHeight))->save($path);
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting ',' or ')' on line 41 at column 35
Loading history...
42
43 12
        return $path;
44
    }
45
46
    /**
47
     * Assumes the image is WebP, converts it to JPG, and return path to JPG version.
48
     */
49 1
    public function webpToJpg(Image $image): string
50
    {
51 1
        $path = $this->getCachePath($image, '.jpg');
52
53 1
        if (file_exists($path)) {
54
            return $path;
55
        }
56
57 1
        $image = $this->imagine->open($image->getPath());
58 1
        $image->save($path);
59
60 1
        return $path;
61
    }
62
63 13
    private function getCachePath(Image $image, string $suffix): string
64
    {
65 13
        $basename = pathinfo($image->getFilename(), PATHINFO_FILENAME);
66
67 13
        return realpath('.') . '/' . self::CACHE_IMAGE_PATH . $basename . $suffix;
68
    }
69
}
70