Passed
Push — master ( 1ada49...6f88dc )
by Bjørn
02:29
created

Gmagick::getOptionDefinitionsExtra()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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