Completed
Pull Request — master (#251)
by James
04:47
created

Encode   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 64.44%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 3
dl 0
loc 75
ccs 29
cts 45
cp 0.6444
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 18 3
A getFormat() 0 24 4
A getQuality() 0 14 4
1
<?php
2
3
namespace League\Glide\Manipulators;
4
5
use Intervention\Image\Image;
6
7
/**
8
 * @property string $fm
9
 * @property string $q
10
 */
11
class Encode extends BaseManipulator
12
{
13
    /**
14
     * Perform output image manipulation.
15
     * @param  Image $image The source image.
16
     * @return Image The manipulated image.
17
     */
18 1
    public function run(Image $image)
19
    {
20 1
        $format = $this->getFormat($image);
21 1
        $quality = $this->getQuality();
22
23 1
        if (in_array($format, ['jpg', 'pjpg'], true)) {
24 1
            $image = $image->getDriver()
25 1
                           ->newImage($image->width(), $image->height(), '#fff')
26 1
                           ->insert($image, 'top-left', 0, 0);
27 1
        }
28
29 1
        if ($format === 'pjpg') {
30
            $image->interlace();
31
            $format = 'jpg';
32
        }
33
34 1
        return $image->encode($format, $quality);
35
    }
36
37
    /**
38
     * Resolve format.
39
     * @param  Image  $image The source image.
40
     * @return string The resolved format.
41
     */
42 2
    public function getFormat(Image $image)
43
    {
44
        $allowed = [
45 2
            'gif' => 'image/gif',
46 2
            'jpg' => 'image/jpeg',
47 2
            'pjpg' => 'image/jpeg',
48 2
            'png' => 'image/png',
49 2
        ];
50
51
        // PHP 5.* may not be compiled with WebP support, so check first.
52 2
        if (function_exists('imagecreatefromwebp')) {
53
            $allowed['webp'] = 'image/webp';
54
        }
55
56 2
        if (array_key_exists($this->fm, $allowed)) {
57 2
            return $this->fm;
58
        }
59
60 1
        if ($format = array_search($image->mime(), $allowed, true)) {
61 1
            return $format;
62
        }
63
64 1
        return 'jpg';
65
    }
66
67
    /**
68
     * Resolve quality.
69
     * @return string The resolved quality.
70
     */
71 2
    public function getQuality()
72
    {
73 2
        $default = 90;
74
75 2
        if (!is_numeric($this->q)) {
76 2
            return $default;
77
        }
78
79 1
        if ($this->q < 0 or $this->q > 100) {
80 1
            return $default;
81
        }
82
83 1
        return (int) $this->q;
84
    }
85
}
86