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

ImagickBinary::createCommandLineOptions()   B

Complexity

Conditions 7
Paths 64

Size

Total Lines 32
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 32
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\LosslessAutoTrait;
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 ImagickBinary extends AbstractConverter
21
{
22
    use ExecTrait;
23
    use LosslessAutoTrait;
24
25
    // To futher improve this converter, I could check out:
26
    // https://github.com/Orbitale/ImageMagickPHP
27
28 2
    public static function imagickInstalled()
29
    {
30 2
        exec('convert -version', $output, $returnCode);
31 2
        return ($returnCode == 0);
32
    }
33
34
    // Check if webp delegate is installed
35 2
    public static function webPDelegateInstalled()
36
    {
37
38 2
        exec('convert -list delegate', $output, $returnCode);
39 2
        foreach ($output as $line) {
40 2
            if (preg_match('#webp\\s*=#i', $line)) {
41 2
                return true;
42
            }
43
        }
44
45
        // try other command
46
        exec('convert -list configure', $output, $returnCode);
47
        foreach ($output as $line) {
48
            if (preg_match('#DELEGATE.*webp#i', $line)) {
49
                return true;
50
            }
51
        }
52
53
        return false;
54
55
        // PS, convert -version does not output delegates on travis, so it is not reliable
56
    }
57
58
    /**
59
     * Check (general) operationality of imagack converter executable
60
     *
61
     * @throws SystemRequirementsNotMetException  if system requirements are not met
62
     */
63 2
    public function checkOperationality()
64
    {
65 2
        $this->checkOperationalityExecTrait();
66
67 2
        if (!self::imagickInstalled()) {
68
            throw new SystemRequirementsNotMetException('imagick is not installed');
69
        }
70 2
        if (!self::webPDelegateInstalled()) {
71
            throw new SystemRequirementsNotMetException('webp delegate missing');
72
        }
73 2
    }
74
75
    /**
76
     * Build command line options
77
     *
78
     * @return string
79
     */
80 2
    private function createCommandLineOptions()
81
    {
82 2
        $commandArguments = [];
83 2
        if ($this->isQualityDetectionRequiredButFailing()) {
84
            // quality:auto was specified, but could not be determined.
85
            // we cannot apply the max-quality logic, but we can provide auto quality
86
            // simply by not specifying the quality option.
87
        } else {
88 2
            $commandArguments[] = '-quality ' . escapeshellarg($this->getCalculatedQuality());
89
        }
90 2
        if ($this->options['lossless']) {
91 1
            $commandArguments[] = '-define webp:lossless=true';
92
        }
93 2
        if ($this->options['low-memory']) {
94
            $commandArguments[] = '-define webp:low-memory=true';
95
        }
96 2
        if ($this->options['autofilter']) {
97
            $commandArguments[] = '-define webp:auto-filter=true';
98
        }
99 2
        if ($this->options['metadata'] == 'none') {
100 2
            $commandArguments[] = '-strip';
101
        }
102 2
        if ($this->options['alpha-quality'] !== 100) {
103 2
            $commandArguments[] = '-define webp:alpha-quality=' . strval($this->options['alpha-quality']);
104
        }
105
106 2
        $commandArguments[] = '-define webp:method=' . $this->options['method'];
107
108 2
        $commandArguments[] = escapeshellarg($this->source);
109 2
        $commandArguments[] = escapeshellarg('webp:' . $this->destination);
110
111 2
        return implode(' ', $commandArguments);
112
    }
113
114 2
    protected function doActualConvert()
115
    {
116
        //$this->logLn('Using quality:' . $this->getCalculatedQuality());
117
118
        // Should we use "magick" or "convert" command?
119
        // It seems they do the same. But which is best supported? Which is mostly available (whitelisted)?
120
        // Should we perhaps try both?
121
        // For now, we just go with "convert"
122
123 2
        $command = 'convert ' . $this->createCommandLineOptions();
124
125
        // also try common system paths?, or perhaps allow path to be set in environment?
126
        //$command = '/home/rosell/opt/bin/magick ' . implode(' ', $commandArguments);
127
128 2
        $useNice = (($this->options['use-nice']) && self::hasNiceSupport()) ? true : false;
129 2
        if ($useNice) {
130 1
            $this->logLn('using nice');
131 1
            $command = 'nice ' . $command;
132
        }
133 2
        $this->logLn('command: ' . $command);
134 2
        exec($command, $output, $returnCode);
135 2
        if ($returnCode == 127) {
136
            throw new SystemRequirementsNotMetException('imagick is not installed');
137
        }
138 2
        if ($returnCode != 0) {
139
            //$this->logLn('command:' . $command);
140 2
            $this->logLn('return code:' . $returnCode);
141 2
            $this->logLn('output:' . print_r(implode("\n", $output), true));
142 2
            throw new SystemRequirementsNotMetException('The exec call failed');
143
        }
144
    }
145
}
146