Failed Conditions
Pull Request — master (#17)
by Adrien
13:01
created

ImageResizer::resize()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 19
ccs 10
cts 11
cp 0.9091
rs 9.9332
cc 4
nc 5
nop 3
crap 4.0119
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 19
    }
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
The constant Ecodev\Felix\Service\1_000_000 was not found. Maybe you did not declare it correctly or list all dependencies?
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;
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

67
        return realpath('.') . '/' . self::CACHE_IMAGE_PATH . /** @scrutinizer ignore-type */ $basename . $suffix;
Loading history...
68
    }
69
}
70