Test Failed
Push — master ( 975525...307699 )
by Bjørn
02:39
created

OptionsTrait::checkEncodingOption()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.2098

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 9
ccs 5
cts 7
cp 0.7143
crap 3.2098
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace WebPConvert\Convert\Converters\BaseTraits;
4
5
use WebPConvert\Convert\Exceptions\ConversionFailed\ConversionSkippedException;
6
use WebPConvert\Options\Exceptions\InvalidOptionValueException;
7
8
use WebPConvert\Options\BooleanOption;
9
use WebPConvert\Options\IntegerOption;
10
use WebPConvert\Options\IntegerOrNullOption;
11
use WebPConvert\Options\MetadataOption;
12
use WebPConvert\Options\Options;
13
use WebPConvert\Options\StringOption;
14
use WebPConvert\Options\QualityOption;
15
16
/**
17
 * Trait for handling options
18
 *
19
 * This trait is currently only used in the AbstractConverter class. It has been extracted into a
20
 * trait in order to bundle the methods concerning options.
21
 *
22
 * @package    WebPConvert
23
 * @author     Bjørn Rosell <[email protected]>
24
 * @since      Class available since Release 2.0.0
25
 */
26
trait OptionsTrait
27
{
28
29
    /** @var array  Provided conversion options */
30
    public $providedOptions;
31
32
    /** @var array  Calculated conversion options (merge of default options and provided options)*/
33
    protected $options;
34
35
    /** @var Options  */
36
    protected $options2;
37
38
    abstract protected function getMimeTypeOfSource();
39
    abstract protected static function getConverterId();
40
41
    /**
42
     *  Create options.
43
     *
44
     *  The options created here will be available to all converters.
45
     *  Individual converters may add options by overriding this method.
46
     *
47
     *  @return void
48
     */
49
    protected function createOptions()
50
    {
51
        $isPng = ($this->getMimeTypeOfSource() == 'image/png');
52
53
        $this->options2 = new Options();
54
        $this->options2->addOptions(
55
            new IntegerOption('alpha-quality', 85, 0, 100),
56
            new BooleanOption('auto-filter', false),
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $defaultValue of WebPConvert\Options\BooleanOption::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

56
            new BooleanOption('auto-filter', /** @scrutinizer ignore-type */ false),
Loading history...
57
            new IntegerOption('default-quality', ($isPng ? 85 : 75), 0, 100),
58
            new StringOption('encoding', 'auto', ['lossy', 'lossless', 'auto']),
59
            new BooleanOption('low-memory', false),
60
            new BooleanOption('log-call-arguments', false),
61 31
            new IntegerOption('max-quality', 85, 0, 100),
62
            new MetadataOption('metadata', 'none'),
63 31
            new IntegerOption('method', 6, 0, 6),
64
            new IntegerOption('near-lossless', 60, 0, 100),
65 31
            new StringOption('preset', 'none', ['none', 'default', 'photo', 'picture', 'drawing', 'icon', 'text']),
66
            new QualityOption('quality', ($isPng ? 85 : 'auto')),
67
            new IntegerOrNullOption('size-in-percentage', null, 0, 100),
68
            new BooleanOption('skip', false),
69
            new BooleanOption('use-nice', false),
70
        );
71
    }
72 31
73
    /**
74
     * Set "provided options" (options provided by the user when calling convert().
75
     *
76
     * This also calculates the protected options array, by merging in the default options, merging
77
     * jpeg and png options and merging prefixed options (such as 'vips-quality').
78
     * The resulting options array are set in the protected property $this->options and can be
79 31
     * retrieved using the public ::getOptions() function.
80 31
     *
81
     * @param   array $providedOptions (optional)
82 31
     * @return  void
83
     */
84
    public function setProvidedOptions($providedOptions = [])
85 17
    {
86
        $this->createOptions();
87
88 17
        $this->providedOptions = $providedOptions;
89
90
        if (isset($this->providedOptions['png'])) {
91
            if ($this->getMimeTypeOfSource() == 'image/png') {
92
                $this->providedOptions = array_merge($this->providedOptions, $this->providedOptions['png']);
93 31
//                $this->logLn(print_r($this->providedOptions, true));
94 31
            }
95
        }
96
97
        if (isset($this->providedOptions['jpeg'])) {
98
            if ($this->getMimeTypeOfSource() == 'image/jpeg') {
99
                $this->providedOptions = array_merge($this->providedOptions, $this->providedOptions['jpeg']);
100
            }
101 2
        }
102
103 2
        // merge down converter-prefixed options
104
        $converterId = self::getConverterId();
105
        $strLen = strlen($converterId);
106
        foreach ($this->providedOptions as $optionKey => $optionValue) {
107
            if (substr($optionKey, 0, $strLen + 1) == ($converterId . '-')) {
108
                $this->providedOptions[substr($optionKey, $strLen + 1)] = $optionValue;
109
            }
110
        }
111
112
        // Create options (Option objects)
113
        foreach ($this->providedOptions as $optionId => $optionValue) {
114
            $this->options2->setOrCreateOption($optionId, $optionValue);
115
        }
116 1
        //$this->logLn(print_r($this->options2->getOptions(), true));
117
//$this->logLn($this->options2->getOption('hello'));
118 1
119 1
        // Create flat associative array of options
120
        $this->options = $this->options2->getOptions();
121
122
        // -  Merge $defaultOptions into provided options
123
        //$this->options = array_merge($this->getDefaultOptions(), $this->providedOptions);
124
125
        //$this->logOptions();
126
    }
127
128
    /**
129
     * Get the resulting options after merging provided options with default options.
130 31
     *
131
     * Note that the defaults depends on the mime type of the source. For example, the default value for quality
132 31
     * is "auto" for jpegs, and 85 for pngs.
133 31
     *
134 31
     * @return array  An associative array of options: ['metadata' => 'none', ...]
135
     */
136 31
    public function getOptions()
137 18
    {
138 18
        return $this->options;
139
    }
140 31
141 17
    /**
142
     * Change an option specifically.
143 31
     *
144
     * This method is probably rarely neeeded. We are using it to change the "encoding" option temporarily
145
     * in the EncodingAutoTrait.
146
     *
147
     * @param  string  $id      Id of option (ie "metadata")
148
     * @param  mixed   $value   The new value.
149
     * @return void
150
     */
151
    protected function setOption($id, $value)
152
    {
153
        $this->options[$id] = $value;
154
        $this->options2->setOrCreateOption($id, $value);
155
    }
156
157
    /**
158
     *  Check options.
159
     *
160
     *  @throws InvalidOptionValueException  if an option value have wrong type or is out of range
161
     *  @throws ConversionSkippedException  if 'skip' option is set to true
162
     *  @return void
163
     */
164
    protected function checkOptions()
165
    {
166
        $this->options2->check();
167 13
168
        if ($this->options['skip']) {
169 13
            if (($this->getMimeTypeOfSource() == 'image/png') && isset($this->options['png']['skip'])) {
170
                throw new ConversionSkippedException(
171
                    'skipped conversion (configured to do so for PNG)'
172
                );
173
            } else {
174
                throw new ConversionSkippedException(
175
                    'skipped conversion (configured to do so)'
176
                );
177
            }
178
        }
179
    }
180
181
/*
182 31
    private function logOption($def) {
183
        list($optionName, $optionType) = $def;
184 31
        $sensitive = (isset($def[3]) && $def[3] === true);
185
        if ($sensitive) {
186
            $printValue = '*****';
187
        } else {
188
            $printValue = $this->options[$optionName];
189
            //switch ($optionType) {
190
            switch (gettype($printValue)) {
191
                case 'boolean':
192
                    $printValue = ($printValue === true ? 'true' : 'false');
193 12
                    break;
194
                case 'string':
195 12
                    $printValue = '"' . $printValue . '"';
196 12
                    break;
197 12
                case 'NULL':
198 10
                    $printValue = 'NULL';
199 10
                    break;
200 1
                case 'array':
201 1
                    //$printValue = print_r($printValue, true);
202
                    if (count($printValue) == 0) {
203
                        $printValue = '(empty array)';
204 12
                    } else {
205
                        $printValue = '(array of ' . count($printValue) . ' items)';
206
                    }
207
                    break;
208
            }
209
        }
210 12
211
        $this->log($optionName . ': ', 'italic');
212
        $this->logLn($printValue);
213
        //$this->logLn($optionName . ': ' . $printValue, 'italic');
214
            //(isset($this->providedOptions[$optionName]) ? '' : ' (using default)')
215
216
        //$this->logLn(gettype($printValue));
217
    }*/
218 12
219
    public function logOptions()
220 12
    {
221 12
    }
222
}
223