Passed
Push — master ( a57d9e...3a516f )
by Joschi
02:19
created

LengthFactory::makeInstance()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6.3324

Importance

Changes 0
Metric Value
cc 4
eloc 20
nc 4
nop 3
dl 0
loc 31
ccs 9
cts 19
cp 0.4737
crap 6.3324
rs 8.5806
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\Application\Factory
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\Application\Factory;
38
39
use ChrisKonnertz\StringCalc\Tokenizer\Token;
40
use Jkphl\Respimgcss\Application\Contract\UnitLengthInterface;
41
use Jkphl\Respimgcss\Application\Exceptions\InvalidArgumentException;
42
use Jkphl\Respimgcss\Application\Model\AbsoluteLength;
43
use Jkphl\Respimgcss\Application\Model\PercentageLength;
44
use Jkphl\Respimgcss\Application\Model\StringCalculator;
45
use Jkphl\Respimgcss\Application\Model\ViewportLength;
46
use Jkphl\Respimgcss\Application\Service\LengthNormalizerService;
47
48
/**
49
 * AbstractLength Factory
50
 *
51
 * @package    Jkphl\Respimgcss
52
 * @subpackage Jkphl\Respimgcss\Application\Factory
53
 */
54
class LengthFactory
55
{
56
    /**
57
     * Absolute units
58
     *
59
     * @var array
60
     */
61
    const UNITS_ABSOLUTE = [
62
        UnitLengthInterface::UNIT_PIXEL,
63
        UnitLengthInterface::UNIT_EM,
64
        UnitLengthInterface::UNIT_REM,
65
        UnitLengthInterface::UNIT_CM,
66
        UnitLengthInterface::UNIT_MM,
67
        UnitLengthInterface::UNIT_IN,
68
        UnitLengthInterface::UNIT_PC,
69
        UnitLengthInterface::UNIT_PT,
70
    ];
71
    /**
72
     * Relative units
73
     *
74
     * @var array
75
     */
76
    const UNITS_RELATIVE = [
77
        UnitLengthInterface::UNIT_PERCENT,
78
        UnitLengthInterface::UNIT_VW,
79
    ];
80
81
    /**
82
     * Parse a length string and return a length with unit instance
83
     *
84
     * @param string $length AbstractLength string
85
     * @param int $emPixel   EM to pixel ratio
86
     *
87
     * @return UnitLengthInterface AbstractLength with unit
88
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
89
     * @throws \ChrisKonnertz\StringCalc\Exceptions\InvalidIdentifierException
90
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
91
     */
92 12
    public static function createLengthFromString(string $length, int $emPixel = 16): UnitLengthInterface
93
    {
94 12
        $valueAndUnit = self::matchValueAndUnit($length);
95 11
        return self::makeInstance($valueAndUnit[1], $valueAndUnit[2], $emPixel);
96
    }
97
98
    /**
99
     * Match the value and unit of a length descriptor
100
     *
101
     * @param string $length AbstractLength descriptor
102
     *
103
     * @return array Value and unit (PCRE match)
104
     * @throws InvalidArgumentException If the length string is invalid
105
     */
106 12
    protected static function matchValueAndUnit($length): array
107
    {
108 12
        $length = trim(strtolower($length));
109 12
        if (!strlen($length) || !preg_match('/^(\d+(?:\.\d+)?)([pxremcintvw%]+)$/i', $length, $valueAndUnit)) {
110 1
            throw new InvalidArgumentException(
111 1
                sprintf(InvalidArgumentException::INVALID_LENGTH_STR, $length),
112 1
                InvalidArgumentException::INVALID_LENGTH
113
            );
114
        }
115
116 11
        return $valueAndUnit;
117
    }
118
119
    /**
120
     * Create a value with unit instance
121
     *
122
     * @param string $value Value
123
     * @param string $unit  Unit
124
     * @param int $emPixel  EM to pixel ratio
125
     *
126
     * @return UnitLengthInterface AbstractLength with unit
127
     * @throws InvalidArgumentException If the unit is invalid
128
     * @throws \ChrisKonnertz\StringCalc\Exceptions\ContainerException
129
     * @throws \ChrisKonnertz\StringCalc\Exceptions\InvalidIdentifierException
130
     * @throws \ChrisKonnertz\StringCalc\Exceptions\NotFoundException
131
     */
132 11
    protected static function makeInstance(string $value, string $unit, int $emPixel): UnitLengthInterface
133
    {
134
        // If it's an absolute unit
135 11
        if (in_array($unit, self::UNITS_ABSOLUTE)) {
136 9
            return new AbsoluteLength(floatval($value), $unit, new LengthNormalizerService($emPixel));
137
        }
138
139
        switch ($unit) {
140 2
            case UnitLengthInterface::UNIT_VW: // Viewport unit
141
                $stringCalc = new StringCalculator();
142
                return new ViewportLength(
143
                    $stringCalc->parse(
144
                        [
145
                            new Token(strval($value / 100), Token::TYPE_NUMBER, 0),
146
                            new Token('*', Token::TYPE_CHARACTER, 0),
147
                            new Token('viewport', Token::TYPE_WORD, 0),
148
                            new Token('(', Token::TYPE_CHARACTER, 0),
149
                            new Token(')', Token::TYPE_CHARACTER, 0),
150
                        ]
151
                    ),
152
                    new LengthNormalizerService($emPixel),
153
                    $value
154
                );
155
156 2
            case UnitLengthInterface::UNIT_PERCENT: // Percentages
157 1
                return new PercentageLength(floatval($value));
158
159
            default: // Invalid unit
160 1
                throw new InvalidArgumentException(
161 1
                    sprintf(InvalidArgumentException::INVALID_UNIT_STR, $unit),
162 1
                    InvalidArgumentException::INVALID_UNIT
163
                );
164
        }
165
    }
166
}