CssLength.php
3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
namespace Svg;
class CssLength
{
/**
* Array of valid css length units.
* Should be pre-sorted by unit text length so no earlier length can be
* contained within a latter (eg. 'in' within 'vmin').
*
* @var string[]
*/
protected static $units = [
'vmax',
'vmin',
'rem',
'px',
'pt',
'cm',
'mm',
'in',
'pc',
'em',
'ex',
'ch',
'vw',
'vh',
'%',
'q',
];
/**
* A list of units that are inch-relative, and their unit division within an inch.
*
* @var array<string, float>
*/
protected static $inchDivisions = [
'in' => 1,
'cm' => 2.54,
'mm' => 25.4,
'q' => 101.6,
'pc' => 6,
'pt' => 72,
];
/**
* The CSS length unit indicator.
* Will be lower-case and one of the units listed in the '$units' array or empty.
*
* @var string
*/
protected $unit = '';
/**
* The numeric value of the given length.
*
* @var float
*/
protected $value = 0;
/**
* The original unparsed length provided.
*
* @var string
*/
protected $unparsed;
public function __construct(string $length)
{
$this->unparsed = $length;
$this->parseLengthComponents($length);
}
/**
* Parse out the unit and value components from the given string length.
*/
protected function parseLengthComponents(string $length): void
{
$length = strtolower($length);
foreach (self::$units as $unit) {
$pos = strpos($length, $unit);
if ($pos) {
$this->value = floatval(substr($length, 0, $pos));
$this->unit = $unit;
return;
}
}
$this->unit = '';
$this->value = floatval($length);
}
/**
* Get the unit type of this css length.
* Units are standardised to be lower-cased.
*
* @return string
*/
public function getUnit(): string
{
return $this->unit;
}
/**
* Get this CSS length in the equivalent pixel count size.
*
* @param float $referenceSize
* @param float $dpi
*
* @return float
*/
public function toPixels(float $referenceSize = 11.0, float $dpi = 96.0): float
{
// Standard relative units
if (in_array($this->unit, ['em', 'rem', 'ex', 'ch'])) {
return $this->value * $referenceSize;
}
// Percentage relative units
if (in_array($this->unit, ['%', 'vw', 'vh', 'vmin', 'vmax'])) {
return $this->value * ($referenceSize / 100);
}
// Inch relative units
if (in_array($this->unit, array_keys(static::$inchDivisions))) {
$inchValue = $this->value * $dpi;
$division = static::$inchDivisions[$this->unit];
return $inchValue / $division;
}
return $this->value;
}
}