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

OptionsTrait   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 270
Duplicated Lines 0 %

Test Coverage

Coverage 76.25%

Importance

Changes 0
Metric Value
eloc 69
dl 0
loc 270
ccs 61
cts 80
cp 0.7625
rs 9.6
c 0
b 0
f 0
wmc 35

12 Methods

Rating   Name   Duplication   Size   Complexity  
A checkOptions() 0 12 4
A checkOptionTypesGenerally() 0 12 5
A getOptionDefinitions() 0 3 1
A getDefaultOptions() 0 12 3
A getOptions() 0 3 1
A getOptionDefinitionsExtra() 0 3 1
A checkQualityOption() 0 18 6
A getGeneralOptionDefinitions() 0 3 1
A checkLosslessOption() 0 9 4
A setOption() 0 3 1
A checkOptionTypes() 0 5 1
B setProvidedOptions() 0 33 7
1
<?php
2
3
namespace WebPConvert\Convert\Converters\BaseTraits;
4
5
use WebPConvert\Convert\Exceptions\ConversionFailed\ConversionSkippedException;
6
use WebPConvert\Convert\Exceptions\ConversionFailed\InvalidInput\InvalidOptionTypeException;
7
8
/**
9
 * Trait for handling options
10
 *
11
 * This trait is currently only used in the AbstractConverter class. It has been extracted into a
12
 * trait in order to bundle the methods concerning options.
13
 *
14
 * @package    WebPConvert
15
 * @author     Bjørn Rosell <[email protected]>
16
 * @since      Class available since Release 2.0.0
17
 */
18
trait OptionsTrait
19
{
20
21
    /** @var array  Provided conversion options */
22
    public $providedOptions;
23
24
    /** @var array  Calculated conversion options (merge of default options and provided options)*/
25
    protected $options;
26
27
    abstract protected function getMimeTypeOfSource();
28
    abstract protected static function getConverterId();
29
30
    /** @var array  Definitions of general options (the options that are available on all converters) */
31
    protected static $optionDefinitionsBasic = [
32
        ['alpha-quality', 'integer', 80],
33
        ['autofilter', 'boolean', false],
34
        ['default-quality', 'number', 75],       // PS: Default is altered to 85 for PNG in ::getDefaultOptions()
35
        ['lossless', 'boolean|string', false],  // PS: Default is altered to "auto" for PNG in ::getDefaultOptions()
36
        ['low-memory', 'boolean', false],
37
        ['max-quality', 'number', 85],
38
        ['metadata', 'string', 'none'],
39
        ['method', 'number', 6],
40
        ['near-lossless', 'integer', 60],
41
        ['preset', 'string', null],              // ('default' | 'photo' | 'picture' | 'drawing' | 'icon' | 'text')
42
        ['quality', 'number|string', 'auto'],    // PS: Default is altered to 85 for PNG in ::getDefaultOptions()
43
        ['size-in-percentage', 'number', null],
44
        ['skip', 'boolean', false],
45
        ['use-nice', 'boolean', false],
46
    ];
47
48
    /**
49
     * Set "provided options" (options provided by the user when calling convert().
50
     *
51
     * This also calculates the protected options array, by merging in the default options, merging
52
     * jpeg and png options and merging prefixed options (such as 'vips-quality').
53
     * The resulting options array are set in the protected property $this->options and can be
54
     * retrieved using the public ::getOptions() function.
55
     *
56
     * @param   array $providedOptions (optional)
57
     * @return  void
58
     */
59 31
    public function setProvidedOptions($providedOptions = [])
60
    {
61 31
        $this->providedOptions = $providedOptions;
62
63 31
        if (isset($this->providedOptions['png'])) {
64
            if ($this->getMimeTypeOfSource() == 'image/png') {
65
                $this->providedOptions = array_merge($this->providedOptions, $this->providedOptions['png']);
66
//                $this->logLn(print_r($this->providedOptions, true));
67
            }
68
        }
69
70 31
        if (isset($this->providedOptions['jpeg'])) {
71
            if ($this->getMimeTypeOfSource() == 'image/jpeg') {
72
                $this->providedOptions = array_merge($this->providedOptions, $this->providedOptions['jpeg']);
73
            }
74
        }
75
76
        // merge down converter-prefixed options
77 31
        $converterId = self::getConverterId();
78 31
        $strLen = strlen($converterId);
79
        //$this->logLn('id:' . $converterId);
80 31
        foreach ($this->providedOptions as $optionKey => $optionValue) {
81
            //$this->logLn($optionKey . ':' . $optionValue);
82
            //$this->logLn(substr($optionKey, 0, strlen($converterId)));
83 17
            if (substr($optionKey, 0, $strLen + 1) == ($converterId . '-')) {
84
                //$this->logLn($optionKey . ':' . $optionValue);
85
                //$this->logLn(substr($optionKey, $strLen + 1));
86 17
                $this->providedOptions[substr($optionKey, $strLen + 1)] = $optionValue;
87
            }
88
        }
89
90
        // -  Merge $defaultOptions into provided options
91 31
        $this->options = array_merge($this->getDefaultOptions(), $this->providedOptions);
92 31
    }
93
94
    /**
95
     * Get the resulting options after merging provided options with default options.
96
     *
97
     * @return array  An associative array of options: ['metadata' => 'none', ...]
98
     */
99 2
    public function getOptions()
100
    {
101 2
        return $this->options;
102
    }
103
104
    /**
105
     * Change an option specifically.
106
     *
107
     * This method is probably rarely neeeded. We are using it to change the "lossless" option temporarily
108
     * in the LosslessAutoTrait.
109
     *
110
     * @param  string  $optionName   Name id of option (ie "metadata")
111
     * @param  mixed   $optionValue  The new value.
112
     * @return void
113
     */
114 1
    protected function setOption($optionName, $optionValue)
115
    {
116 1
        $this->options[$optionName] = $optionValue;
117 1
    }
118
119
120
    /**
121
     * Get default options for the converter.
122
     *
123
     * Note that the defaults depends on the mime type of the source. For example, the default value for quality
124
     * is "auto" for jpegs, and 85 for pngs.
125
     *
126
     * @return array  An associative array of option defaults: ['metadata' => 'none', ...]
127
     */
128 31
    public function getDefaultOptions()
129
    {
130 31
        $defaults = [];
131 31
        foreach ($this->getOptionDefinitions() as list($name, $type, $default)) {
132 31
            $defaults[$name] = $default;
133
        }
134 31
        if ($this->getMimeTypeOfSource() == 'image/png') {
135 18
            $defaults['lossless'] = 'auto';
136 18
            $defaults['quality'] = 85;
137 18
            $defaults['default-quality'] = 85;
138
        }
139 31
        return $defaults;
140
    }
141
142
143
    /**
144
     * Get definitions of general options (those available for all converters)
145
     *
146
     * To get only the extra definitions for a specific converter, call
147
     * ::getOptionDefinitionsExtra(). To get both general and extra, merged together, call ::getOptionDefinitions().
148
     *
149
     * @return array  A numeric array of definitions of general options for the converter.
150
     *                Each definition is a numeric array with three items: [option id, type, default value]
151
     */
152
    public function getGeneralOptionDefinitions()
153
    {
154
        return self::$optionDefinitionsBasic;
155
    }
156
157
    /**
158
     * Get definitions of extra options unique for the actual converter.
159
     *
160
     * @return array  A numeric array of definitions of extra options for the converter.
161
     *                Each definition is a numeric array with three items: [option id, type, default value]
162
     */
163 13
    protected function getOptionDefinitionsExtra()
164
    {
165 13
        return [];
166
    }
167
168
    /**
169
     * Get option definitions for the converter (includes both general options and the extra options for the converter)
170
     *
171
     * To get only the general options definitions (those available for all converters), call
172
     * ::getGeneralOptionDefinitions(). To get only the extra definitions for a specific converter, call
173
     * ::getOptionDefinitionsExtra().
174
     *
175
     * @return array  A numeric array of definitions of all options for the converter.
176
     *                Each definition is a numeric array with three items: [option id, type, default value]
177
     */
178 31
    public function getOptionDefinitions()
179
    {
180 31
        return array_merge(self::$optionDefinitionsBasic, $this->getOptionDefinitionsExtra());
181
    }
182
183
    /**
184
     *  Check option types generally (against their definitions).
185
     *
186
     *  @throws InvalidOptionTypeException  if type is invalid
187
     *  @return void
188
     */
189 12
    private function checkOptionTypesGenerally()
190
    {
191 12
        foreach ($this->getOptionDefinitions() as $def) {
192 12
            list($optionName, $optionType) = $def;
193 12
            if (isset($this->providedOptions[$optionName])) {
194 10
                $actualType = gettype($this->providedOptions[$optionName]);
195 10
                if ($actualType != $optionType) {
196 6
                    $optionType = str_replace('number', 'integer|double', $optionType);
197 6
                    if (!in_array($actualType, explode('|', $optionType))) {
198
                        throw new InvalidOptionTypeException(
199
                            'The provided ' . $optionName . ' option is not a ' . $optionType .
200 12
                                ' (it is a ' . $actualType . ')'
201
                        );
202
                    }
203
                }
204
            }
205
        }
206 12
    }
207
208
    /**
209
     *  Check quality option
210
     *
211
     *  @throws InvalidOptionTypeException  if value is out of range
212
     *  @return void
213
     */
214 12
    private function checkQualityOption()
215
    {
216 12
        if (!isset($this->providedOptions['quality'])) {
217 12
            return;
218
        }
219 1
        $optionValue = $this->providedOptions['quality'];
220 1
        if (gettype($optionValue) == 'string') {
221 1
            if ($optionValue != 'auto') {
222
                throw new InvalidOptionTypeException(
223
                    'Quality option must be either "auto" or a number between 0-100. ' .
224 1
                    'A string, "' . $optionValue . '" was given'
225
                );
226
            }
227
        } else {
228
            if (($optionValue < 0) || ($optionValue > 100)) {
229
                throw new InvalidOptionTypeException(
230
                    'Quality option must be either "auto" or a number between 0-100. ' .
231
                        'The number you provided (' . strval($optionValue) . ') is out of range.'
232
                );
233
            }
234
        }
235 1
    }
236
237
    /**
238
     *  Check lossless option
239
     *
240
     *  @throws InvalidOptionTypeException  if value is out of range
241
     *  @return void
242
     */
243 12
    private function checkLosslessOption()
244
    {
245 12
        if (!isset($this->providedOptions['lossless'])) {
246 7
            return;
247
        }
248 6
        $optionValue = $this->providedOptions['lossless'];
249 6
        if ((gettype($optionValue) == 'string') && ($optionValue != 'auto')) {
250
            throw new InvalidOptionTypeException(
251
                'Lossless option must be true, false or "auto". It was set to: "' . $optionValue . '"'
252
            );
253
        }
254 6
    }
255
256
    /**
257
     *  Check option types.
258
     *
259
     *  @throws InvalidOptionTypeException  if an option value have wrong type or is out of range
260
     *  @return void
261
     */
262 12
    private function checkOptionTypes()
263
    {
264 12
        $this->checkOptionTypesGenerally();
265 12
        $this->checkQualityOption();
266 12
        $this->checkLosslessOption();
267 12
    }
268
269
    /**
270
     *  Check options.
271
     *
272
     *  @throws InvalidOptionTypeException  if an option value have wrong type or is out of range
273
     *  @throws ConversionSkippedException  if 'skip' option is set to true
274
     *  @return void
275
     */
276 12
    protected function checkOptions()
277
    {
278 12
        $this->checkOptionTypes();
279
280 12
        if ($this->options['skip']) {
281
            if (($this->getMimeTypeOfSource() == 'image/png') && isset($this->options['png']['skip'])) {
282
                throw new ConversionSkippedException(
283
                    'skipped conversion (configured to do so for PNG)'
284
                );
285
            } else {
286
                throw new ConversionSkippedException(
287
                    'skipped conversion (configured to do so)'
288
                );
289
            }
290
        }
291 12
    }
292
}
293