Passed
Push — master ( 6fb159...2324c3 )
by Joschi
01:58
created

Generator::compileCssRuleset()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 2
nop 3
dl 0
loc 25
ccs 13
cts 13
cp 1
crap 3
rs 8.8571
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\Application\Contract\UnitLengthInterface;
40
use Jkphl\Respimgcss\Application\Factory\ImageCandidateFactory;
41
use Jkphl\Respimgcss\Application\Factory\LengthFactory;
42
use Jkphl\Respimgcss\Application\Factory\SourceSizeFactory;
43
use Jkphl\Respimgcss\Application\Model\ImageCandidateSet;
44
use Jkphl\Respimgcss\Application\Service\CssRulesetCompilerService;
45
use Jkphl\Respimgcss\Domain\Contract\ImageCandidateInterface;
46
use Jkphl\Respimgcss\Ports\CssRuleset;
47
use Jkphl\Respimgcss\Ports\CssRulesetInterface;
48
use Jkphl\Respimgcss\Ports\GeneratorInterface;
49
use Jkphl\Respimgcss\Ports\InvalidArgumentException;
50
51
/**
52
 * Responsive image CSS generator (internal)
53
 *
54
 * @package    Jkphl\Respimgcss
55
 * @subpackage Jkphl\Respimgcss\Ports
56
 */
57
abstract class Generator implements GeneratorInterface
58
{
59
    /**
60
     * Breakpoints
61
     *
62
     * @var UnitLengthInterface[]
63
     */
64
    protected $breakpoints;
65
    /**
66
     * EM to pixel ratio
67
     *
68
     * @var int
69
     */
70
    protected $emPixel;
71
    /**
72
     * Image candidates
73
     *
74
     * @var ImageCandidateSet
75
     */
76
    protected $imageCandidates = null;
77
78
    /**
79
     * Generator constructor
80
     *
81
     * @param string[] $breakpoints List of breakpoint length strings
82
     * @param int $emPixel          EM to pixel ratio
83
     */
84 6
    public function __construct(array $breakpoints, int $emPixel)
85
    {
86 6
        $this->emPixel     = $emPixel;
87 6
        $lengthFactory     = new LengthFactory(new ViewportCalculatorServiceFactory(), $this->emPixel);
88 6
        $this->breakpoints = array_map(
89 6
            [$lengthFactory, 'createLengthFromString'],
90 6
            $breakpoints,
91 6
            array_fill(0, count($breakpoints), $this->emPixel)
92
        );
93 6
    }
94
95
    /**
96
     * Register an image candidate
97
     *
98
     * @param string $file            Image candidate file path and name
99
     * @param string|null $descriptor Image candidate descriptor
100
     *
101
     * @return GeneratorInterface Self reference
102
     * @api
103
     */
104 6
    public function registerImageCandidate(string $file, string $descriptor = null): GeneratorInterface
105
    {
106 6
        $imageCandidate = ($descriptor === null) ?
107 6
            ImageCandidateFactory::createImageCandidateFromString($file) :
108 6
            ImageCandidateFactory::createImageCandidateFromFileAndDescriptor($file, $descriptor);
109
110
        // If the image candidate set doesn't exist yet
111 6
        if ($this->imageCandidates === null) {
112 6
            $this->imageCandidates = new ImageCandidateSet($imageCandidate);
113
114 6
            return $this;
115
        }
116
117
        // Register the image candidate
118 6
        $this->imageCandidates[] = $imageCandidate;
119
120 6
        return $this;
121
    }
122
123
    /**
124
     * Return the registered image candidates
125
     *
126
     * @return ImageCandidateInterface[] Image candidates
127
     */
128 6
    public function getImageCandidates(): array
129
    {
130 6
        return ($this->imageCandidates === null) ? [] : $this->imageCandidates->toArray();
131
    }
132
133
    /**
134
     * Create a CSS ruleset for the registered image candidates
135
     *
136
     * @param float[] $densities Device display densities
137
     * @param string $sizes      Source sizes
138
     *
139
     * @return CssRulesetInterface CSS Ruleset
140
     */
141 6
    public function make(array $densities = [1], string $sizes = ''): CssRulesetInterface
142
    {
143 6
        $cssRuleset = new CssRuleset();
144
145
        // If all necessary properties are given
146 6
        if (count($this->breakpoints) && count($this->getImageCandidates()) && count($densities)) {
147 6
            $cssRuleset = $this->compileCssRuleset($cssRuleset, $densities, $sizes);
148
        }
149
150 4
        return $cssRuleset;
151
    }
152
153
    /**
154
     * Compile a CSS ruleset
155
     *
156
     * @param CssRuleset $baseCssRuleset                 Base CSS ruleset
157
     * @param ImageCandidateInterface[] $imageCandidates Image candidates
158
     * @param int[] $densities                           Densities
159
     * @param string $sizes                              Source sizes
160
     *
161
     * @return CssRulesetInterface Compile CSS ruleset
162
     * @throws InvalidArgumentException If source sizes are used with resolution based image candidates
163
     */
164 6
    protected function compileCssRuleset(
165
        CssRuleset $baseCssRuleset,
166
        array $densities,
167
        string $sizes
168
    ): CssRulesetInterface {
169 6
        $sourceSizeList = $this->makeSourceSizeList($sizes);
170
171
        // If source sizes are used with resolution based image candidates
172 6
        if ($sourceSizeList && ($this->imageCandidates->getType() == ImageCandidateInterface::TYPE_DENSITY)) {
173 2
            throw new InvalidArgumentException(
174 2
                InvalidArgumentException::SIZES_NOT_ALLOWED_STR,
175 2
                InvalidArgumentException::SIZES_NOT_ALLOWED
176
            );
177
        }
178
179
        // Instantiate a CSS ruleset compiler service and compile for all densities
180 4
        $cssRulesetCompilerService = new CssRulesetCompilerService(
181 4
            $baseCssRuleset,
182 4
            $this->breakpoints,
183 4
            $this->imageCandidates,
184 4
            new ViewportCalculatorServiceFactory(),
185 4
            $this->emPixel
186
        );
187
188 4
        return new CssRuleset($cssRulesetCompilerService->compile($densities));
189
    }
190
191
    /**
192
     * Create a size list from a source size list
193
     *
194
     * @param string $sourceSizeListStr SourceSizeList size list
195
     *
196
     * @return SourceSizeList Size list
197
     */
198 6
    protected function makeSourceSizeList(string $sourceSizeListStr): ?SourceSizeList
199
    {
200 6
        $sourceSizeFactory   = new SourceSizeFactory(new ViewportCalculatorServiceFactory(), $this->emPixel);
201 6
        $unparsedSourceSizes = array_filter(array_map('trim', explode(',', $sourceSizeListStr)));
202 6
        $sourceSizes         = array_map(
203 6
            function($unparsedSourceSize) use ($sourceSizeFactory) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
204 2
                return $sourceSizeFactory->createFromSourceSizeStr($unparsedSourceSize);
205 6
            },
206 6
            $unparsedSourceSizes
207
        );
208
209 6
        return count($sourceSizes) ? new SourceSizeList($sourceSizes) : null;
210
    }
211
}