Completed
Push — master ( 80b762...b17462 )
by Bjørn
05:19
created

ImageMagick::createCommandLineOptions()   B

Complexity

Conditions 7
Paths 64

Size

Total Lines 38
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7.0671

Importance

Changes 0
Metric Value
cc 7
eloc 18
nc 64
nop 0
dl 0
loc 38
ccs 16
cts 18
cp 0.8889
crap 7.0671
rs 8.8333
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\Converters\ConverterTraits\ExecTrait;
7
use WebPConvert\Convert\Converters\ConverterTraits\EncodingAutoTrait;
8
use WebPConvert\Convert\Exceptions\ConversionFailed\ConverterNotOperational\SystemRequirementsNotMetException;
9
use WebPConvert\Convert\Exceptions\ConversionFailedException;
10
11
//use WebPConvert\Convert\Exceptions\ConversionFailed\InvalidInput\TargetNotFoundException;
12
13
/**
14
 * Convert images to webp by calling imagick binary.
15
 *
16
 * @package    WebPConvert
17
 * @author     Bjørn Rosell <[email protected]>
18
 * @since      Class available since Release 2.0.0
19
 */
20
class ImageMagick extends AbstractConverter
21
{
22
    use ExecTrait;
23
    use EncodingAutoTrait;
24
25
    protected function getUnsupportedDefaultOptions()
26
    {
27
        return [
28
            'near-lossless',
29
            'preset',
30
            'size-in-percentage',
31
        ];
32
    }
33
34
    // To futher improve this converter, I could check out:
35
    // https://github.com/Orbitale/ImageMagickPHP
36
37 2
    public static function imagickInstalled()
38
    {
39 2
        exec('convert -version', $output, $returnCode);
40 2
        return ($returnCode == 0);
41
    }
42
43
    // Check if webp delegate is installed
44 2
    public static function webPDelegateInstalled()
45
    {
46
47 2
        exec('convert -list delegate', $output, $returnCode);
48 2
        foreach ($output as $line) {
49 2
            if (preg_match('#webp\\s*=#i', $line)) {
50 2
                return true;
51
            }
52
        }
53
54
        // try other command
55
        exec('convert -list configure', $output, $returnCode);
56
        foreach ($output as $line) {
57
            if (preg_match('#DELEGATE.*webp#i', $line)) {
58
                return true;
59
            }
60
        }
61
62
        return false;
63
64
        // PS, convert -version does not output delegates on travis, so it is not reliable
65
    }
66
67
    /**
68
     * Check (general) operationality of imagack converter executable
69
     *
70
     * @throws SystemRequirementsNotMetException  if system requirements are not met
71
     */
72 2
    public function checkOperationality()
73
    {
74 2
        $this->checkOperationalityExecTrait();
75
76 2
        if (!self::imagickInstalled()) {
77
            throw new SystemRequirementsNotMetException('imagick is not installed');
78
        }
79 2
        if (!self::webPDelegateInstalled()) {
80
            throw new SystemRequirementsNotMetException('webp delegate missing');
81
        }
82 2
    }
83
84
    /**
85
     * Build command line options
86
     *
87
     * @return string
88
     */
89 2
    private function createCommandLineOptions()
90
    {
91
        // PS: Available webp options for imagick are documented here:
92
        // https://imagemagick.org/script/webp.php
93
94 2
        $commandArguments = [];
95 2
        if ($this->isQualityDetectionRequiredButFailing()) {
96
            // quality:auto was specified, but could not be determined.
97
            // we cannot apply the max-quality logic, but we can provide auto quality
98
            // simply by not specifying the quality option.
99
        } else {
100 2
            $commandArguments[] = '-quality ' . escapeshellarg($this->getCalculatedQuality());
101
        }
102 2
        if ($this->options['encoding'] == 'lossless') {
103 1
            $commandArguments[] = '-define webp:lossless=true';
104
        }
105 2
        if ($this->options['low-memory']) {
106
            $commandArguments[] = '-define webp:low-memory=true';
107
        }
108 2
        if ($this->options['auto-filter'] === true) {
109
            $commandArguments[] = '-define webp:auto-filter=true';
110
        }
111 2
        if ($this->options['metadata'] == 'none') {
112 2
            $commandArguments[] = '-strip';
113
        }
114 2
        if ($this->options['alpha-quality'] !== 100) {
115 2
            $commandArguments[] = '-define webp:alpha-quality=' . strval($this->options['alpha-quality']);
116
        }
117
118
        // Unfortunately, near-lossless does not seem to be supported.
119
        // it does have a "preprocessing" option, which may be doing something similar
120
121 2
        $commandArguments[] = '-define webp:method=' . $this->options['method'];
122
123 2
        $commandArguments[] = escapeshellarg($this->source);
124 2
        $commandArguments[] = escapeshellarg('webp:' . $this->destination);
125
126 2
        return implode(' ', $commandArguments);
127
    }
128
129 2
    protected function doActualConvert()
130
    {
131
        //$this->logLn('Using quality:' . $this->getCalculatedQuality());
132
133
        // Should we use "magick" or "convert" command?
134
        // It seems they do the same. But which is best supported? Which is mostly available (whitelisted)?
135
        // Should we perhaps try both?
136
        // For now, we just go with "convert"
137
138 2
        $command = 'convert ' . $this->createCommandLineOptions();
139
140
        // also try common system paths?, or perhaps allow path to be set in environment?
141
        //$command = '/home/rosell/opt/bin/magick ' . implode(' ', $commandArguments);
142
143 2
        $useNice = (($this->options['use-nice']) && self::hasNiceSupport()) ? true : false;
144 2
        if ($useNice) {
145 1
            $this->logLn('using nice');
146 1
            $command = 'nice ' . $command;
147
        }
148 2
        $this->logLn('command: ' . $command);
149 2
        exec($command, $output, $returnCode);
150 2
        if ($returnCode == 127) {
151
            throw new SystemRequirementsNotMetException('imagick is not installed');
152
        }
153 2
        if ($returnCode != 0) {
154
            //$this->logLn('command:' . $command);
155 2
            $this->logLn('return code:' . $returnCode);
156 2
            $this->logLn('output:' . print_r(implode("\n", $output), true));
157 2
            throw new SystemRequirementsNotMetException('The exec call failed');
158
        }
159
    }
160
}
161