Completed
Push — master ( 8a6cb8...70a6e8 )
by Bjørn
03:20
created

Gmagick   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 128
Duplicated Lines 0 %

Test Coverage

Coverage 6%

Importance

Changes 0
Metric Value
eloc 50
dl 0
loc 128
ccs 3
cts 50
cp 0.06
rs 10
c 0
b 0
f 0
wmc 16

3 Methods

Rating   Name   Duplication   Size   Complexity  
A checkOperationality() 0 16 4
B doActualConvert() 0 66 7
A checkConvertability() 0 19 5
1
<?php
2
3
namespace WebPConvert\Convert\Converters;
4
5
use WebPConvert\Convert\Converters\AbstractConverter;
6
use WebPConvert\Convert\Exceptions\ConversionFailedException;
7
use WebPConvert\Convert\Exceptions\ConversionFailed\ConverterNotOperational\SystemRequirementsNotMetException;
8
use WebPConvert\Convert\Converters\ConverterTraits\EncodingAutoTrait;
9
10
//use WebPConvert\Convert\Exceptions\ConversionFailed\InvalidInput\TargetNotFoundException;
11
12
/**
13
 * Convert images to webp using Gmagick extension.
14
 *
15
 * @package    WebPConvert
16
 * @author     Bjørn Rosell <[email protected]>
17
 * @since      Class available since Release 2.0.0
18
 */
19
class Gmagick extends AbstractConverter
20
{
21
    use EncodingAutoTrait;
22
23
    /**
24
     * Check (general) operationality of Gmagick converter.
25
     *
26
     * Note:
27
     * It may be that Gd has been compiled without jpeg support or png support.
28
     * We do not check for this here, as the converter could still be used for the other.
29
     *
30
     * @throws SystemRequirementsNotMetException  if system requirements are not met
31
     */
32 1
    public function checkOperationality()
33
    {
34 1
        if (!extension_loaded('Gmagick')) {
35 1
            throw new SystemRequirementsNotMetException('Required Gmagick extension is not available.');
36
        }
37
38
        if (!class_exists('Gmagick')) {
39
            throw new SystemRequirementsNotMetException(
40
                'Gmagick is installed, but not correctly. The class Gmagick is not available'
41
            );
42
        }
43
44
        $im = new \Gmagick($this->source);
45
46
        if (!in_array('WEBP', $im->queryformats())) {
47
            throw new SystemRequirementsNotMetException('Gmagick was compiled without WebP support.');
48
        }
49
    }
50
51
    /**
52
     * Check if specific file is convertable with current converter / converter settings.
53
     *
54
     * @throws SystemRequirementsNotMetException  if Gmagick does not support image type
55
     */
56
    public function checkConvertability()
57
    {
58
        $im = new \Gmagick();
59
        $mimeType = $this->getMimeTypeOfSource();
60
        switch ($mimeType) {
61
            case 'image/png':
62
                if (!in_array('PNG', $im->queryFormats())) {
63
                    throw new SystemRequirementsNotMetException(
64
                        'Gmagick has been compiled without PNG support and can therefore not convert this PNG image.'
65
                    );
66
                }
67
                break;
68
            case 'image/jpeg':
69
                if (!in_array('JPEG', $im->queryFormats())) {
70
                    throw new SystemRequirementsNotMetException(
71
                        'Gmagick has been compiled without Jpeg support and can therefore not convert this Jpeg image.'
72
                    );
73
                }
74
                break;
75
        }
76
    }
77
78
    // Although this method is public, do not call directly.
79
    // You should rather call the static convert() function, defined in AbstractConverter, which
80
    // takes care of preparing stuff before calling doConvert, and validating after.
81
    protected function doActualConvert()
82
    {
83
84
        $options = $this->options;
85
86
        try {
87
            $im = new \Gmagick($this->source);
88
        } catch (\Exception $e) {
89
            throw new ConversionFailedException(
90
                'Failed creating Gmagick object of file',
91
                'Failed creating Gmagick object of file: "' . $this->source . '" - Gmagick threw an exception.',
92
                $e
93
            );
94
        }
95
96
        $im->setimageformat('WEBP');
97
98
        // Finally cracked setting webp options.
99
        // See #167 and https://stackoverflow.com/questions/47294962/how-to-write-lossless-webp-files-with-perlmagick
100
101
        $im->setimageoption('webp', 'method', $options['method']);
0 ignored issues
show
Bug introduced by
The method setimageoption() does not exist on Gmagick. Did you maybe mean setimageresolution()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

101
        $im->/** @scrutinizer ignore-call */ 
102
             setimageoption('webp', 'method', $options['method']);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
102
        $im->setimageoption('webp', 'lossless', $options['encoding'] == 'lossless' ? 'true' : 'false');
103
        $im->setimageoption('webp', 'alpha-quality', $options['alpha-quality']);
104
105
        if ($options['auto-filter'] === true) {
106
            $im->setimageoption('webp', 'auto-filter', 'true');
107
        }
108
109
        /*
110
        low-memory seems not to be supported:
111
        $im->setimageoption('webp', 'low-memory', $options['low-memory'] ? true : false);
112
        */
113
114
        if ($options['metadata'] == 'none') {
115
            // Strip metadata and profiles
116
            $im->stripImage();
117
        }
118
119
        // Ps: Imagick automatically uses same quality as source, when no quality is set
120
        // This feature is however not present in Gmagick
121
        // TODO: However, it might be possible after all - see #91
122
        $im->setcompressionquality($this->getCalculatedQuality());
123
124
        try {
125
            // We call getImageBlob().
126
            // That method is undocumented, but it is there!
127
            // - just like it is in imagick, as pointed out here:
128
            //   https://www.php.net/manual/ru/gmagick.readimageblob.php
129
130
            /** @scrutinizer ignore-call */
131
            $imageBlob = $im->getImageBlob();
132
        } catch (\ImagickException $e) {
133
            throw new ConversionFailedException(
134
                'Gmagick failed converting - getImageBlob() threw an exception)',
135
                0,
136
                $e
137
            );
138
        }
139
140
141
        //$success = $im->writeimagefile(fopen($destination, 'wb'));
142
        $success = @file_put_contents($this->destination, $imageBlob);
143
144
        if (!$success) {
145
            throw new ConversionFailedException('Failed writing file');
146
        } else {
147
            //$logger->logLn('sooms we made it!');
148
        }
149
    }
150
}
151