Passed
Push — master ( 3aebab...165038 )
by Joschi
02:05
created

optimizeCssRulesByImageCandidate()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0058

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 3
nop 1
dl 0
loc 22
ccs 13
cts 14
cp 0.9286
crap 4.0058
rs 8.9197
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * responsive-images-css
5
 *
6
 * @category   Jkphl
7
 * @package    Jkphl\Respimgcss
8
 * @subpackage Jkphl\Respimgcss\Infrastructure
9
 * @author     Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright  Copyright © 2018 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license    http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2018 Joschi Kuphal <[email protected]> / @jkphl
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Jkphl\Respimgcss\Infrastructure;
38
39
use Jkphl\Respimgcss\Domain\Contract\CssMediaConditionInterface as DomainMediaConditionInterface;
40
use Jkphl\Respimgcss\Domain\Contract\CssRuleInterface;
41
use Jkphl\Respimgcss\Infrastructure\CssMediaConditionInterface as RenderableMediaConditionInterface;
42
use Jkphl\Respimgcss\Ports\InvalidArgumentException;
43
use Sabberworm\CSS\CSSList\AtRuleBlockList;
44
use Sabberworm\CSS\CSSList\Document;
45
use Sabberworm\CSS\Renderable;
46
use Sabberworm\CSS\Rule\Rule;
47
use Sabberworm\CSS\RuleSet\DeclarationBlock;
48
use Sabberworm\CSS\Value\CSSString;
49
use Sabberworm\CSS\Value\URL;
50
51
/**
52
 * CSS rules serializer
53
 *
54
 * @package    Jkphl\Respimgcss
55
 * @subpackage Jkphl\Respimgcss\Infrastructure
56
 */
57
class CssRulesSerializer
58
{
59
    /**
60
     * CSS rules
61
     *
62
     * @var CssRuleInterface[]
63
     */
64
    protected $rules;
65
66
    /**
67
     * CSS rules serializer constructor
68
     *
69
     * @param CssRuleInterface[] $rules CSS Rules
70
     */
71 9
    public function __construct(array $rules)
72
    {
73 9
        $this->rules = $rules;
74 9
    }
75
76
    /**
77
     * Return the registered rules as CSS
78
     *
79
     * @param string $selector CSS selector
80
     *
81
     * @return string Serialized CSS rules
82
     * @throws InvalidArgumentException If the CSS selector is invalid
83
     */
84 9
    public function toCss(string $selector): string
85
    {
86
        // If the CSS selector is invalid
87 9
        $selector = trim($selector);
88 9
        if (!strlen($selector)) {
89 1
            throw new InvalidArgumentException(
90 1
                sprintf(InvalidArgumentException::INVALID_CSS_SELECTOR_STR, $selector),
91 1
                InvalidArgumentException::INVALID_CSS_SELECTOR
92
            );
93
        }
94
95 8
        $cssDocument = new Document();
96
97
        // Run through and export all rules
98 8
        foreach ($this->exportCssRules($selector) as $rule) {
99 8
            $cssDocument->append($rule);
100
        }
101
102 8
        return $cssDocument->render();
103
    }
104
105
    /**
106
     * Export all registered CSS rules
107
     *
108
     * @param string $selector CSS selector
109
     *
110
     * @return Renderable[] Exported CSS rules
111
     */
112 8
    protected function exportCssRules(string $selector): array
113
    {
114 8
        $rulesByImageCandidate = [];
115
116
        /** @var CssRuleInterface $rule */
117 8
        foreach ($this->rules as $rule) {
118 8
            $ruleImageCandidate = $rule->getImageCandidate()->getFile();
119 8
            if (!array_key_exists($ruleImageCandidate, $rulesByImageCandidate)) {
120 8
                $rulesByImageCandidate[$ruleImageCandidate] = [];
121
            }
122 8
            $rulesByImageCandidate[$ruleImageCandidate][] = $this->exportCssRule($rule, $selector);
123
        }
124
125
        // Return aggregated rules
126 8
        return array_map([$this, 'optimizeCssRulesByImageCandidate'], $rulesByImageCandidate);
127
    }
128
129
    /**
130
     * Optimize a list of CSS rules by aggregating for @media blocks
131
     *
132
     * @param Renderable[] $rulesByImageCandidate CSS rules
133
     *
134
     * @return Renderable Optimized CSS rules
135
     */
136 8
    protected function optimizeCssRulesByImageCandidate(array $rulesByImageCandidate): Renderable
137
    {
138
        // If there's only one ruleset: Return
139 8
        if (count($rulesByImageCandidate) === 1) {
140 8
            return $rulesByImageCandidate[0];
141
        }
142
143
        // Collect all @media conditions
144 4
        $atRuleConditions = array_map(
145 4
            function (Renderable $renderable) {
146 4
                return ($renderable instanceof AtRuleBlockList) ? $renderable->atRuleArgs() : 'screen';
147 4
            },
148 4
            $rulesByImageCandidate
149
        );
150
151 4
        $renderable      = array_pop($rulesByImageCandidate);
152 4
        $atRuleBlockList = new AtRuleBlockList('media', implode(',', $atRuleConditions));
153 4
        ($renderable instanceof AtRuleBlockList) ?
154 4
            $atRuleBlockList->setContents($renderable->getContents()) :
155
            $atRuleBlockList->append($renderable);
156
157 4
        return $atRuleBlockList;
158
    }
159
160
    /**
161
     * Export a single CSS rule
162
     *
163
     * @param CssRuleInterface $rule CSS rule
164
     * @param string $selector       CSS selector
165
     *
166
     * @return Renderable
167
     */
168 8
    protected function exportCssRule(CssRuleInterface $rule, string $selector): Renderable
169
    {
170
        // If the rule has conditions: Render as an @-rule block
171 8
        if (count($rule)) {
172 8
            return $this->exportCssRuleAtBlock($rule, $selector);
173
        }
174
175 7
        return $this->exportCssRuleDeclarationBlock($rule, $selector);
176
    }
177
178
    /**
179
     * Export a CSS rule as @-media block
180
     *
181
     * @param CssRuleInterface $rule CSS rule
182
     * @param string $selector       CSS selector
183
     *
184
     * @return AtRuleBlockList @-media block
185
     */
186 8
    protected function exportCssRuleAtBlock(CssRuleInterface $rule, string $selector): AtRuleBlockList
187
    {
188 8
        $atRuleMediaConditions = $this->exportCssRuleMediaConditions($rule);
189 8
        $atRuleBlockList       = new AtRuleBlockList('media', $atRuleMediaConditions);
190 8
        $atRuleBlockList->append($this->exportCssRuleDeclarationBlock($rule, $selector));
191
192 8
        return $atRuleBlockList;
193
    }
194
195
    /**
196
     * Export the media conditions associated with a CSS rule
197
     *
198
     * @param CssRuleInterface $rule CSS rule
199
     *
200
     * @return string Media conditions
201
     */
202 8
    protected function exportCssRuleMediaConditions(CssRuleInterface $rule): string
203
    {
204 8
        $alternativeMediaConditions = new CssMediaConditionAlternatives();
205
206
        // Run through all conditions of this rule
207
        /** @var DomainMediaConditionInterface $condition */
208 8
        foreach ($rule as $condition) {
209 8
            $addMediaConditionAlternatives = CssMediaConditionFactory::createFromMediaCondition($condition);
210 8
            $alternativeMediaConditions    = count($alternativeMediaConditions) ?
211 5
                $this->addAndMultiplyCssMediaConditions(
212 5
                    $alternativeMediaConditions,
213 5
                    $addMediaConditionAlternatives
214 8
                ) : $this->initializeCssMediaConditions(
215 8
                    $alternativeMediaConditions,
216 8
                    $addMediaConditionAlternatives
217
                );
218
        }
219
220 8
        return strval($alternativeMediaConditions);
221
    }
222
223
    /**
224
     * Add and multiply media condition alternatives
225
     *
226
     * @param CssMediaConditionAlternatives $alternativeMediaConditions       Base set of alternative media conditions
227
     * @param RenderableMediaConditionInterface[] $mediaConditionAlternatives Media condition alternatives to add
228
     *
229
     * @return CssMediaConditionAlternatives Multiplied set of media condition alternatives
230
     */
231 5
    protected function addAndMultiplyCssMediaConditions(
232
        CssMediaConditionAlternatives $alternativeMediaConditions,
233
        array $mediaConditionAlternatives
234
    ): CssMediaConditionAlternatives {
235 5
        $multipliedAlternativeMediaConditions = new CssMediaConditionAlternatives();
236
237
        // Run through all generated media condition alternatives
238
        /** @var RenderableMediaConditionInterface $mediaConditionAlternative */
239 5
        foreach ($mediaConditionAlternatives as $mediaConditionAlternative) {
240
            // Run through all registered media condition alternatives
241
            /** @var LogicalCssMediaConditionInterface $registeredMediaConditionAlternative */
242 5
            foreach ($alternativeMediaConditions as $registeredMediaConditionAlternative) {
243 5
                $clonedMediaConditionAlternative = clone $registeredMediaConditionAlternative;
244 5
                $clonedMediaConditionAlternative->appendCondition($mediaConditionAlternative);
245 5
                $multipliedAlternativeMediaConditions->appendCondition($clonedMediaConditionAlternative);
246
            }
247
        }
248
249 5
        return $multipliedAlternativeMediaConditions;
250
    }
251
252
    /**
253
     * Initialize media condition alternatives
254
     *
255
     * @param CssMediaConditionAlternatives $alternativeMediaConditions       Base set of alternative media conditions
256
     * @param RenderableMediaConditionInterface[] $mediaConditionAlternatives Media condition alternatives to add
257
     *
258
     * @return CssMediaConditionAlternatives Multiplied set of media condition alternatives
259
     */
260 8
    protected function initializeCssMediaConditions(
261
        CssMediaConditionAlternatives $alternativeMediaConditions,
262
        array $mediaConditionAlternatives
263
    ): CssMediaConditionAlternatives {
264
        // Run through all generated media condition alternatives
265
        /** @var RenderableMediaConditionInterface $mediaConditionAlternative */
266 8
        foreach ($mediaConditionAlternatives as $mediaConditionAlternative) {
267 8
            $alternativeMediaConditions->appendCondition(new LogicalAndCssMediaCondition([$mediaConditionAlternative]));
268
        }
269
270 8
        return $alternativeMediaConditions;
271
    }
272
273
    /**
274
     * Export a CSS rule as declaration block (without media query)
275
     *
276
     * @param CssRuleInterface $rule CSS rule
277
     * @param string $selector       CSS selector
278
     *
279
     * @return DeclarationBlock Declaration block
280
     */
281 8
    protected function exportCssRuleDeclarationBlock(CssRuleInterface $rule, string $selector): DeclarationBlock
282
    {
283 8
        $declarationBlock = new DeclarationBlock();
284 8
        $declarationBlock->setSelectors([$selector]);
285 8
        $declarationBlock->addRule($this->exportCssRuleRule($rule));
286
287 8
        return $declarationBlock;
288
    }
289
290
    /**
291
     * Export the CSS rule property and value
292
     *
293
     * @param CssRuleInterface $rule CSS rule
294
     *
295
     * @return Rule Export CSS rule
296
     */
297 8
    protected function exportCssRuleRule(CssRuleInterface $rule): Rule
298
    {
299 8
        $imageCandidateFile = $rule->getImageCandidate()->getFile();
300 8
        $cssRule            = new Rule('background-image');
301 8
        $cssRule->setValue(new URL(new CSSString($imageCandidateFile)));
302
303 8
        return $cssRule;
304
    }
305
}
306