Completed
Pull Request — master (#212)
by
unknown
13:53 queued 11:42
created

Encode   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
lcom 1
cbo 3
dl 0
loc 70
ccs 0
cts 42
cp 0
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 18 3
A getFormat() 0 19 3
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
    public function run(Image $image)
19
    {
20
        $format = $this->getFormat($image);
21
        $quality = $this->getQuality();
22
23
        if (in_array($format, ['jpg', 'pjpg'], true)) {
24
            $image = $image->getDriver()
25
                           ->newImage($image->width(), $image->height(), '#fff')
26
                           ->insert($image, 'top-left', 0, 0);
27
        }
28
29
        if ($format === 'pjpg') {
30
            $image->interlace();
31
            $format = 'jpg';
32
        }
33
34
        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
    public function getFormat(Image $image)
43
    {
44
        $allowed = [
45
            'gif' => 'image/gif',
46
            'jpg' => 'image/jpeg',
47
            'pjpg' => 'image/jpeg',
48
            'png' => 'image/png',
49
        ];
50
51
        if (array_key_exists($this->fm, $allowed)) {
52
            return $this->fm;
53
        }
54
55
        if ($format = array_search($image->mime(), $allowed, true)) {
56
            return $format;
57
        }
58
59
        return 'jpg';
60
    }
61
62
    /**
63
     * Resolve quality.
64
     * @return string The resolved quality.
65
     */
66
    public function getQuality()
67
    {
68
        $default = 90;
69
70
        if (!is_numeric($this->q)) {
71
            return $default;
72
        }
73
74
        if ($this->q < 0 or $this->q > 100) {
75
            return $default;
76
        }
77
78
        return (int) $this->q;
79
    }
80
}
81