Passed
Push — master ( f80879...93467d )
by Bjørn
03:47
created

Stack::converterIdToClassname()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.1576

Importance

Changes 0
Metric Value
cc 4
eloc 14
nc 6
nop 1
dl 0
loc 17
ccs 7
cts 12
cp 0.5833
crap 5.1576
rs 9.7998
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A Stack::getAvailableConverters() 0 3 1
1
<?php
2
3
// TODO: Quality option
4
5
namespace WebPConvert\Convert\Converters;
6
7
use WebPConvert\Convert\ConverterFactory;
8
use WebPConvert\Convert\Converters\AbstractConverter;
9
use WebPConvert\Convert\Exceptions\ConversionFailedException;
10
use WebPConvert\Convert\Exceptions\ConversionFailed\ConverterNotOperationalException;
11
use WebPConvert\Convert\Exceptions\ConversionFailed\ConverterNotOperational\SystemRequirementsNotMetException;
12
use WebPConvert\Convert\Exceptions\ConversionFailed\ConversionSkippedException;
13
14
//use WebPConvert\Convert\Exceptions\ConversionFailed\InvalidInput\TargetNotFoundException;
15
16
/**
17
 * Convert images to webp by trying a stack of converters until success.
18
 *
19
 * @package    WebPConvert
20
 * @author     Bjørn Rosell <[email protected]>
21
 * @since      Class available since Release 2.0.0
22
 */
23
class Stack extends AbstractConverter
24
{
25
26 5
    protected function getOptionDefinitionsExtra()
27
    {
28
        return [
29
            [
30 5
                'converters',
31
                'array', [
32
                    'cwebp', 'vips', 'wpc', 'imagickbinary', 'ewww', 'imagick', 'gmagick', 'gmagickbinary', 'gd'
33
                ],
34
                true
35
            ],
36
            ['shuffle', 'boolean', false],
37
            ['preferred-converters', 'array', []],
38
            ['extra-converters', 'array', []]
39
        ];
40
    }
41
42
    /**
43
     * Get available converters (ids).
44
     *
45
     * @return  array  An array of ids of converters that comes with this library
46
     */
47
    public static function getAvailableConverters()
48
    {
49
        return ['cwebp', 'vips', 'wpc', 'imagickbinary', 'ewww', 'imagick', 'gmagick', 'gmagickbinary', 'gd'];
50
    }
51
    
52
    /**
53
     * Check (general) operationality of imagack converter executable
54
     *
55
     * @throws SystemRequirementsNotMetException  if system requirements are not met
56
     */
57 3
    public function checkOperationality()
58
    {
59 3
        if (count($this->options['converters']) == 0) {
60 1
            throw new ConverterNotOperationalException(
61 1
                'Converter stack is empty! - no converters to try, no conversion can be made!'
62
            );
63
        }
64
65
        // TODO: We should test if all converters are found in order to detect problems early
66
67 2
        $this->logLn('Stack converter ignited');
68 2
    }
69
70 2
    protected function doActualConvert()
71
    {
72 2
        $options = $this->options;
73
74 2
        $beginTimeStack = microtime(true);
75
76 2
        $anyRuntimeErrors = false;
77
78 2
        $converters = $options['converters'];
79 2
        if (count($options['extra-converters']) > 0) {
80
            $converters = array_merge($converters, $options['extra-converters']);
81
            /*foreach ($options['extra-converters'] as $extra) {
82
                $converters[] = $extra;
83
            }*/
84
        }
85
86
        // preferred-converters
87 2
        if (count($options['preferred-converters']) > 0) {
88
            foreach (array_reverse($options['preferred-converters']) as $prioritizedConverter) {
89
                foreach ($converters as $i => $converter) {
90
                    if (is_array($converter)) {
91
                        $converterId = $converter['converter'];
92
                    } else {
93
                        $converterId = $converter;
94
                    }
95
                    if ($converterId == $prioritizedConverter) {
96
                        unset($converters[$i]);
97
                        array_unshift($converters, $converter);
98
                        break;
99
                    }
100
                }
101
            }
102
            // perhaps write the order to the log? (without options) - but this requires some effort
103
        }
104
105
        // shuffle
106 2
        if ($options['shuffle']) {
107
            shuffle($converters);
108
        }
109
110
        //$this->logLn(print_r($converters));
111
        //$options['converters'] = $converters;
112 2
        $defaultConverterOptions = $options;
113
114
        //unset($defaultConverterOptions['converters']);
115
        //unset($defaultConverterOptions['converter-options']);
116 2
        $defaultConverterOptions['_skip_input_check'] = true;
117 2
        $defaultConverterOptions['_suppress_success_message'] = true;
118 2
        unset($defaultConverterOptions['converters']);
119 2
        unset($defaultConverterOptions['extra-converters']);
120 2
        unset($defaultConverterOptions['converter-options']);
121 2
        unset($defaultConverterOptions['preferred-converters']);
122
123
//        $this->logLn('converters: ' . print_r($converters, true));
124
125
        //return;
126 2
        foreach ($converters as $converter) {
127 2
            if (is_array($converter)) {
128
                $converterId = $converter['converter'];
129
                $converterOptions = $converter['options'];
130
            } else {
131 2
                $converterId = $converter;
132 2
                $converterOptions = [];
133 2
                if (isset($options['converter-options'][$converterId])) {
134
                    // Note: right now, converter-options are not meant to be used,
135
                    //       when you have several converters of the same type
136
                    $converterOptions = $options['converter-options'][$converterId];
137
                }
138
            }
139 2
            $converterOptions = array_merge($defaultConverterOptions, $converterOptions);
140
            /*
141
            if ($converterId != 'stack') {
142
                //unset($converterOptions['converters']);
143
                //unset($converterOptions['converter-options']);
144
            } else {
145
                //$converterOptions['converter-options'] =
146
                $this->logLn('STACK');
147
                $this->logLn('converterOptions: ' . print_r($converterOptions, true));
148
            }*/
149
150 2
            $beginTime = microtime(true);
151
152 2
            $converter = ConverterFactory::makeConverter(
153 2
                $converterId,
154 2
                $this->source,
155 2
                $this->destination,
156 2
                $converterOptions,
157 2
                $this->logger
158
            );
159
160
            try {
161 1
                $this->ln();
162 1
                $this->logLn('Trying: ' . $converterId, 'italic');
163
164 1
                $converter->doConvert();
165
166
                //self::runConverterWithTiming($converterId, $source, $destination, $converterOptions, false, $logger);
167
168 1
                $this->logLn($converterId . ' succeeded :)');
169
                //throw new ConverterNotOperationalException('...');
170 1
                return;
171
            } catch (ConverterNotOperationalException $e) {
172
                $this->logLn($e->getMessage());
173
            } catch (ConversionFailedException $e) {
174
                $this->logLn($e->getMessage(), 'italic');
175
                $prev = $e->getPrevious();
176
                if (!is_null($prev)) {
177
                    $this->logLn($prev->getMessage(), 'italic');
178
                    $this->logLn(' in ' . $prev->getFile() . ', line ' . $prev->getLine(), 'italic');
179
                    $this->ln();
180
                }
181
                //$this->logLn($e->getTraceAsString());
182
                $anyRuntimeErrors = true;
183
            } catch (ConversionSkippedException $e) {
184
                $this->logLn($e->getMessage());
185
            }
186
187
            $this->logLn($converterId . ' failed in ' . round((microtime(true) - $beginTime) * 1000) . ' ms');
188
        }
189
190
        $this->ln();
191
        $this->logLn('Stack failed in ' . round((microtime(true) - $beginTimeStack) * 1000) . ' ms');
192
193
        if ($anyRuntimeErrors) {
0 ignored issues
show
introduced by
The condition $anyRuntimeErrors is always false.
Loading history...
194
            // At least one converter failed
195
            throw new ConversionFailedException(
196
                'None of the converters in the stack could convert the image. ' .
197
                'At least one failed, even though its requirements seemed to be met.'
198
            );
199
        } else {
200
            // All converters threw a SystemRequirementsNotMetException
201
            throw new ConverterNotOperationalException('None of the converters in the stack are operational');
202
        }
203
    }
204
}
205