Passed
Push — master ( 165038...ea3f04 )
by Joschi
02:14
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
        /** @var CssRuleInterface $rule */
98 8
        foreach ($this->rules as $rule) {
99 8
            $cssDocument->append($this->exportCssRule($rule, $selector));
100
        }
101
102 8
        return $cssDocument->render();
103
    }
104
105
    /**
106
     * Export a single CSS rule
107
     *
108
     * @param CssRuleInterface $rule CSS rule
109
     * @param string $selector       CSS selector
110
     *
111
     * @return Renderable
112
     */
113 8
    protected function exportCssRule(CssRuleInterface $rule, string $selector): Renderable
114
    {
115
        // If the rule has conditions: Render as an @-rule block
116 8
        if (count($rule)) {
117 8
            return $this->exportCssRuleAtBlock($rule, $selector);
118
        }
119
120 7
        return $this->exportCssRuleDeclarationBlock($rule, $selector);
121
    }
122
123
    /**
124
     * Export a CSS rule as @-media block
125
     *
126
     * @param CssRuleInterface $rule CSS rule
127
     * @param string $selector       CSS selector
128
     *
129
     * @return AtRuleBlockList @-media block
130
     */
131 8
    protected function exportCssRuleAtBlock(CssRuleInterface $rule, string $selector): AtRuleBlockList
132
    {
133 8
        $atRuleMediaConditions = $this->exportCssRuleMediaConditions($rule);
134 8
        $atRuleBlockList       = new AtRuleBlockList('media', $atRuleMediaConditions);
135 8
        $atRuleBlockList->append($this->exportCssRuleDeclarationBlock($rule, $selector));
136
137 8
        return $atRuleBlockList;
138
    }
139
140
    /**
141
     * Export the media conditions associated with a CSS rule
142
     *
143
     * @param CssRuleInterface $rule CSS rule
144
     *
145
     * @return string Media conditions
146
     */
147 8
    protected function exportCssRuleMediaConditions(CssRuleInterface $rule): string
148
    {
149 8
        $alternativeMediaConditions = new CssMediaConditionAlternatives();
150
151
        // Run through all conditions of this rule
152
        /** @var DomainMediaConditionInterface $condition */
153 8
        foreach ($rule as $condition) {
154 8
            $addMediaConditionAlternatives = CssMediaConditionFactory::createFromMediaCondition($condition);
155 8
            $alternativeMediaConditions    = count($alternativeMediaConditions) ?
156 5
                $this->addAndMultiplyCssMediaConditions(
157 5
                    $alternativeMediaConditions,
158 5
                    $addMediaConditionAlternatives
159 8
                ) : $this->initializeCssMediaConditions(
160 8
                    $alternativeMediaConditions,
161 8
                    $addMediaConditionAlternatives
162
                );
163
        }
164
165 8
        return strval($alternativeMediaConditions);
166
    }
167
168
    /**
169
     * Add and multiply media condition alternatives
170
     *
171
     * @param CssMediaConditionAlternatives $alternativeMediaConditions       Base set of alternative media conditions
172
     * @param RenderableMediaConditionInterface[] $mediaConditionAlternatives Media condition alternatives to add
173
     *
174
     * @return CssMediaConditionAlternatives Multiplied set of media condition alternatives
175
     */
176 5
    protected function addAndMultiplyCssMediaConditions(
177
        CssMediaConditionAlternatives $alternativeMediaConditions,
178
        array $mediaConditionAlternatives
179
    ): CssMediaConditionAlternatives {
180 5
        $multipliedAlternativeMediaConditions = new CssMediaConditionAlternatives();
181
182
        // Run through all generated media condition alternatives
183
        /** @var RenderableMediaConditionInterface $mediaConditionAlternative */
184 5
        foreach ($mediaConditionAlternatives as $mediaConditionAlternative) {
185
            // Run through all registered media condition alternatives
186
            /** @var LogicalCssMediaConditionInterface $registeredMediaConditionAlternative */
187 5
            foreach ($alternativeMediaConditions as $registeredMediaConditionAlternative) {
188 5
                $clonedMediaConditionAlternative = clone $registeredMediaConditionAlternative;
189 5
                $clonedMediaConditionAlternative->appendCondition($mediaConditionAlternative);
190 5
                $multipliedAlternativeMediaConditions->appendCondition($clonedMediaConditionAlternative);
191
            }
192
        }
193
194 5
        return $multipliedAlternativeMediaConditions;
195
    }
196
197
    /**
198
     * Initialize media condition alternatives
199
     *
200
     * @param CssMediaConditionAlternatives $alternativeMediaConditions       Base set of alternative media conditions
201
     * @param RenderableMediaConditionInterface[] $mediaConditionAlternatives Media condition alternatives to add
202
     *
203
     * @return CssMediaConditionAlternatives Multiplied set of media condition alternatives
204
     */
205 8
    protected function initializeCssMediaConditions(
206
        CssMediaConditionAlternatives $alternativeMediaConditions,
207
        array $mediaConditionAlternatives
208
    ): CssMediaConditionAlternatives {
209
        // Run through all generated media condition alternatives
210
        /** @var RenderableMediaConditionInterface $mediaConditionAlternative */
211 8
        foreach ($mediaConditionAlternatives as $mediaConditionAlternative) {
212 8
            $alternativeMediaConditions->appendCondition(new LogicalAndCssMediaCondition([$mediaConditionAlternative]));
213
        }
214
215 8
        return $alternativeMediaConditions;
216
    }
217
218
    /**
219
     * Export a CSS rule as declaration block (without media query)
220
     *
221
     * @param CssRuleInterface $rule CSS rule
222
     * @param string $selector       CSS selector
223
     *
224
     * @return DeclarationBlock Declaration block
225
     */
226 8
    protected function exportCssRuleDeclarationBlock(CssRuleInterface $rule, string $selector): DeclarationBlock
227
    {
228 8
        $declarationBlock = new DeclarationBlock();
229 8
        $declarationBlock->setSelectors([$selector]);
230 8
        $declarationBlock->addRule($this->exportCssRuleRule($rule));
231
232 8
        return $declarationBlock;
233
    }
234
235
    /**
236
     * Export the CSS rule property and value
237
     *
238
     * @param CssRuleInterface $rule CSS rule
239
     *
240
     * @return Rule Export CSS rule
241
     */
242 8
    protected function exportCssRuleRule(CssRuleInterface $rule): Rule
243
    {
244 8
        $imageCandidateFile = $rule->getImageCandidate()->getFile();
245 8
        $cssRule            = new Rule('background-image');
246 8
        $cssRule->setValue(new URL(new CSSString($imageCandidateFile)));
247
248 8
        return $cssRule;
249
    }
250
}
251