Completed
Push — master ( 36e2d9...033daa )
by Bjørn
03:15
created

Gmagick::checkOperationality()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 8.7414

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 0
dl 0
loc 16
ccs 3
cts 9
cp 0.3333
crap 8.7414
rs 10
c 0
b 0
f 0
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
9
//use WebPConvert\Convert\Exceptions\ConversionFailed\InvalidInput\TargetNotFoundException;
10
11
/**
12
 * Convert images to webp using Gmagick extension.
13
 *
14
 * @package    WebPConvert
15
 * @author     Bjørn Rosell <[email protected]>
16
 * @since      Class available since Release 2.0.0
17
 */
18
class Gmagick extends AbstractConverter
19
{
20
    public function supportsLossless()
21
    {
22
        return false;
23
    }
24
25
    /**
26
     * Check (general) operationality of Gmagick converter.
27
     *
28
     * Note:
29
     * It may be that Gd has been compiled without jpeg support or png support.
30
     * We do not check for this here, as the converter could still be used for the other.
31
     *
32
     * @throws SystemRequirementsNotMetException  if system requirements are not met
33
     */
34 1
    public function checkOperationality()
35
    {
36 1
        if (!extension_loaded('Gmagick')) {
37 1
            throw new SystemRequirementsNotMetException('Required Gmagick extension is not available.');
38
        }
39
40
        if (!class_exists('Gmagick')) {
41
            throw new SystemRequirementsNotMetException(
42
                'Gmagick is installed, but not correctly. The class Gmagick is not available'
43
            );
44
        }
45
46
        $im = new \Gmagick($this->source);
47
48
        if (!in_array('WEBP', $im->queryformats())) {
49
            throw new SystemRequirementsNotMetException('Gmagick was compiled without WebP support.');
50
        }
51
    }
52
53
    /**
54
     * Check if specific file is convertable with current converter / converter settings.
55
     *
56
     * @throws SystemRequirementsNotMetException  if Gmagick does not support image type
57
     */
58
    public function checkConvertability()
59
    {
60
        $im = new \Gmagick();
61
        $mimeType = $this->getMimeTypeOfSource();
62
        switch ($mimeType) {
63
            case 'image/png':
64
                if (!in_array('PNG', $im->queryFormats())) {
65
                    throw new SystemRequirementsNotMetException(
66
                        'Imagick has been compiled without PNG support and can therefore not convert this PNG image.'
67
                    );
68
                }
69
                break;
70
            case 'image/jpeg':
71
                if (!in_array('JPEG', $im->queryFormats())) {
72
                    throw new SystemRequirementsNotMetException(
73
                        'Imagick has been compiled without Jpeg support and can therefore not convert this Jpeg image.'
74
                    );
75
                }
76
                break;
77
        }
78
    }
79
80
    // Although this method is public, do not call directly.
81
    // You should rather call the static convert() function, defined in AbstractConverter, which
82
    // takes care of preparing stuff before calling doConvert, and validating after.
83
    protected function doActualConvert()
84
    {
85
86
        $options = $this->options;
87
88
        try {
89
            $im = new \Gmagick($this->source);
90
        } catch (\Exception $e) {
91
            throw new ConversionFailedException(
92
                'Failed creating Gmagick object of file',
93
                'Failed creating Gmagick object of file: "' . $this->source . '" - Gmagick threw an exception.',
94
                $e
95
            );
96
        }
97
98
        /*
99
        Seems there are currently no way to set webp options
100
        As noted in the following link, it should probably be done with a $im->addDefinition() method
101
        - but that isn't exposed (yet)
102
        (TODO: see if anyone has answered...)
103
        https://stackoverflow.com/questions/47294962/how-to-write-lossless-webp-files-with-perlmagick
104
        */
105
        // The following two does not have any effect... How to set WebP options?
106
        //$im->setimageoption('webp', 'webp:lossless', $options['lossless'] ? 'true' : 'false');
107
        //$im->setimageoption('WEBP', 'method', strval($options['method']));
108
109
        // It seems there is no COMPRESSION_WEBP...
110
        // http://php.net/manual/en/imagick.setimagecompression.php
111
        //$im->setImageCompression(Imagick::COMPRESSION_JPEG);
112
        //$im->setImageCompression(Imagick::COMPRESSION_UNDEFINED);
113
114
115
116
        $im->setimageformat('WEBP');
117
118
        if ($options['metadata'] == 'none') {
119
            // Strip metadata and profiles
120
            $im->stripImage();
121
        }
122
123
        // Ps: Imagick automatically uses same quality as source, when no quality is set
124
        // This feature is however not present in Gmagick
125
        // TODO: However, it might be possible after all - see #91
126
        $im->setcompressionquality($this->getCalculatedQuality());
127
128
        try {
129
            // We call getImageBlob().
130
            // That method is undocumented, but it is there!
131
            // - just like it is in imagick, as pointed out here:
132
            //   https://www.php.net/manual/ru/gmagick.readimageblob.php
133
134
            /** @scrutinizer ignore-call */
135
            $imageBlob = $im->getImageBlob();
136
        } catch (\ImagickException $e) {
137
            throw new ConversionFailedException(
138
                'Gmagick failed converting - getImageBlob() threw an exception)',
139
                0,
140
                $e
141
            );
142
        }
143
144
145
        //$success = $im->writeimagefile(fopen($destination, 'wb'));
146
        $success = @file_put_contents($this->destination, $imageBlob);
147
148
        if (!$success) {
149
            throw new ConversionFailedException('Failed writing file');
150
        } else {
151
            //$logger->logLn('sooms we made it!');
152
        }
153
    }
154
}
155