Passed
Push — master ( 91a8e4...a6877f )
by Joschi
02:16
created

CssRulesSerializer   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 202
Duplicated Lines 0 %

Test Coverage

Coverage 79.66%

Importance

Changes 0
Metric Value
dl 0
loc 202
ccs 47
cts 59
cp 0.7966
rs 10
c 0
b 0
f 0
wmc 17

9 Methods

Rating   Name   Duplication   Size   Complexity  
A addAndMultiplyCssMediaConditions() 0 19 3
A exportCssRule() 0 8 2
A initializeCssMediaConditions() 0 11 2
A exportCssRuleDeclarationBlock() 0 7 1
B exportCssRuleMediaConditions() 0 26 3
A exportCssRuleAtBlock() 0 7 1
A exportCssRuleRule() 0 7 1
A __construct() 0 3 1
A toCss() 0 22 3
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\OutputFormat;
46
use Sabberworm\CSS\Renderable;
47
use Sabberworm\CSS\Rule\Rule;
48
use Sabberworm\CSS\RuleSet\DeclarationBlock;
49
use Sabberworm\CSS\Value\CSSString;
50
use Sabberworm\CSS\Value\URL;
51
52
/**
53
 * CSS rules serializer
54
 *
55
 * @package    Jkphl\Respimgcss
56
 * @subpackage Jkphl\Respimgcss\Infrastructure
57
 */
58
class CssRulesSerializer
59
{
60
    /**
61
     * CSS rules
62
     *
63
     * @var CssRuleInterface[]
64
     */
65
    protected $rules;
66
67
    /**
68
     * CSS rules serializer constructor
69
     *
70
     * @param CssRuleInterface[] $rules CSS Rules
71
     */
72 4
    public function __construct(array $rules)
73
    {
74 4
        $this->rules = $rules;
75 4
    }
76
77
    /**
78
     * Return the registered rules as CSS
79
     *
80
     * @param string $selector CSS selector
81
     *
82
     * @return string Serialized CSS rules
83
     * @throws InvalidArgumentException If the CSS selector is invalid
84
     */
85 4
    public function toCss(string $selector): string
86
    {
87
        // If the CSS selector is invalid
88 4
        $selector = trim($selector);
89 4
        if (!strlen($selector)) {
90 1
            throw new InvalidArgumentException(
91 1
                sprintf(InvalidArgumentException::INVALID_CSS_SELECTOR_STR, $selector),
92 1
                InvalidArgumentException::INVALID_CSS_SELECTOR
93
            );
94
        }
95
96 3
        $cssDocument = new Document();
97
98
        /** @var CssRuleInterface $rule */
99 3
        foreach ($this->rules as $rule) {
100 3
            $cssDocument->append($this->exportCssRule($rule, $selector));
101
        }
102
103 3
        $outputFormat                      = new OutputFormat();
104 3
        $outputFormat->sSpaceBetweenBlocks = "\r\n";
105
106 3
        return $cssDocument->render($outputFormat);
107
    }
108
109
    /**
110
     * Export a single CSS rule
111
     *
112
     * @param CssRuleInterface $rule CSS rule
113
     * @param string $selector       CSS selector
114
     *
115
     * @return Renderable
116
     */
117 3
    protected function exportCssRule(CssRuleInterface $rule, string $selector): Renderable
118
    {
119
        // If the rule has conditions: Render as an @-rule block
120 3
        if (count($rule)) {
121 3
            return $this->exportCssRuleAtBlock($rule, $selector);
122
        }
123
124 3
        return $this->exportCssRuleDeclarationBlock($rule, $selector);
125
    }
126
127
    /**
128
     * Export a CSS rule as @-media block
129
     *
130
     * @param CssRuleInterface $rule CSS rule
131
     * @param string $selector       CSS selector
132
     *
133
     * @return AtRuleBlockList @-media block
134
     */
135 3
    protected function exportCssRuleAtBlock(CssRuleInterface $rule, string $selector): AtRuleBlockList
136
    {
137 3
        $atRuleMediaConditions = $this->exportCssRuleMediaConditions($rule);
138 3
        $atRuleBlockList       = new AtRuleBlockList('media', $atRuleMediaConditions);
139 3
        $atRuleBlockList->append($this->exportCssRuleDeclarationBlock($rule, $selector));
140
141 3
        return $atRuleBlockList;
142
    }
143
144
    /**
145
     * Export the media conditions associated with a CSS rule
146
     *
147
     * @param CssRuleInterface $rule CSS rule
148
     *
149
     * @return string Media conditions
150
     */
151 3
    protected function exportCssRuleMediaConditions(CssRuleInterface $rule): string
152
    {
153 3
        $alternativeMediaConditions = new CssMediaConditionAlternatives();
154
155
        // Run through all conditions of this rule
156
        /** @var DomainMediaConditionInterface $condition */
157 3
        foreach ($rule as $condition) {
158 3
            $addMediaConditionAlternatives = CssMediaConditionFactory::createFromMediaCondition($condition);
159
160
            // If there are already registered media conditions: Add and multiply
161 3
            if (count($alternativeMediaConditions)) {
162
                $alternativeMediaConditions = $this->addAndMultiplyCssMediaConditions(
163
                    $alternativeMediaConditions,
164
                    $addMediaConditionAlternatives
165
                );
166
                continue;
167
            }
168
169
            // Else: Add and wrap with logical and media conditions
170 3
            $alternativeMediaConditions = $this->initializeCssMediaConditions(
171 3
                $alternativeMediaConditions,
172 3
                $addMediaConditionAlternatives
173
            );
174
        }
175
176 3
        return strval($alternativeMediaConditions);
177
    }
178
179
    /**
180
     * Add and multiply media condition alternatives
181
     *
182
     * @param CssMediaConditionAlternatives $alternativeMediaConditions       Base set of alternative media conditions
183
     * @param RenderableMediaConditionInterface[] $mediaConditionAlternatives Media condition alternatives to add
184
     *
185
     * @return CssMediaConditionAlternatives Multiplied set of media condition alternatives
186
     */
187
    protected function addAndMultiplyCssMediaConditions(
188
        CssMediaConditionAlternatives $alternativeMediaConditions,
189
        array $mediaConditionAlternatives
190
    ): CssMediaConditionAlternatives {
191
        $multipliedAlternativeMediaConditions = new CssMediaConditionAlternatives();
192
193
        // Run through all generated media condition alternatives
194
        /** @var RenderableMediaConditionInterface $mediaConditionAlternative */
195
        foreach ($mediaConditionAlternatives as $mediaConditionAlternative) {
196
            // Run through all registered media condition alternatives
197
            /** @var LogicalCssMediaConditionInterface $registeredMediaConditionAlternative */
198
            foreach ($alternativeMediaConditions as $registeredMediaConditionAlternative) {
199
                $clonedMediaConditionAlternative = clone $registeredMediaConditionAlternative;
200
                $clonedMediaConditionAlternative->appendCondition($mediaConditionAlternative);
201
                $multipliedAlternativeMediaConditions->appendCondition($clonedMediaConditionAlternative);
202
            }
203
        }
204
205
        return $multipliedAlternativeMediaConditions;
206
    }
207
208
    /**
209
     * Initialize media condition alternatives
210
     *
211
     * @param CssMediaConditionAlternatives $alternativeMediaConditions       Base set of alternative media conditions
212
     * @param RenderableMediaConditionInterface[] $mediaConditionAlternatives Media condition alternatives to add
213
     *
214
     * @return CssMediaConditionAlternatives Multiplied set of media condition alternatives
215
     */
216 3
    protected function initializeCssMediaConditions(
217
        CssMediaConditionAlternatives $alternativeMediaConditions,
218
        array $mediaConditionAlternatives
219
    ): CssMediaConditionAlternatives {
220
        // Run through all generated media condition alternatives
221
        /** @var RenderableMediaConditionInterface $mediaConditionAlternative */
222 3
        foreach ($mediaConditionAlternatives as $mediaConditionAlternative) {
223 3
            $alternativeMediaConditions->appendCondition(new LogicalAndCssMediaCondition([$mediaConditionAlternative]));
224
        }
225
226 3
        return $alternativeMediaConditions;
227
    }
228
229
    /**
230
     * Export a CSS rule as declaration block (without media query)
231
     *
232
     * @param CssRuleInterface $rule CSS rule
233
     * @param string $selector       CSS selector
234
     *
235
     * @return DeclarationBlock Declaration block
236
     */
237 3
    protected function exportCssRuleDeclarationBlock(CssRuleInterface $rule, string $selector): DeclarationBlock
238
    {
239 3
        $declarationBlock = new DeclarationBlock();
240 3
        $declarationBlock->setSelectors([$selector]);
241 3
        $declarationBlock->addRule($this->exportCssRuleRule($rule));
242
243 3
        return $declarationBlock;
244
    }
245
246
    /**
247
     * Export the CSS rule property and value
248
     *
249
     * @param CssRuleInterface $rule CSS rule
250
     *
251
     * @return Rule Export CSS rule
252
     */
253 3
    protected function exportCssRuleRule(CssRuleInterface $rule): Rule
254
    {
255 3
        $imageCandidateFile = $rule->getImageCandidate()->getFile();
256 3
        $cssRule            = new Rule('background-image');
257 3
        $cssRule->setValue(new URL(new CSSString($imageCandidateFile)));
258
259 3
        return $cssRule;
260
    }
261
}