This repository has been archived by the owner on Jan 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFvd.php
133 lines (103 loc) · 3.07 KB
/
Fvd.php
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
<?php
/*
* This file is part of the KtwFvd package.
*
* (c) Kevin T. Weber <https://github.com/kevintweber/KtwFvd/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace kevintweber\KtwFvd;
class Fvd
{
static public function Compact($descriptors)
{
// Format input correctly by removing whitespace.
$descriptors = preg_replace('/\s+/', '', (string)$descriptors);
$resultArray = array('font-style' => 'n', 'font-weight' => 4);
$descriptorArray = explode(';', $descriptors);
foreach ($descriptorArray as $descriptor) {
if ($descriptor == '') {
continue;
}
list($property, $value) = explode(':', $descriptor);
switch ($property) {
case 'font-style':
$result = self::parseFontStyle($value);
break;
case 'font-weight':
$result = self::parseFontWeight($value);
break;
default:
throw new \LogicException('Invalid property: ' . $property);
}
$resultArray[$property] = $result;
}
return implode($resultArray);
}
static public function Expand($fvd)
{
$parsedFvd = self::Parse($fvd);
$response = '';
foreach ($parsedFvd as $attribute => $value) {
$response .= $attribute . ':' . $value . ';';
}
return $response;
}
/**
* @param string $fvd The FVD
*
* @return array
*/
static public function Parse($fvd)
{
// Validate FVD.
if (preg_match('/^[i|n|o][1-9]$/', $fvd) !== 1) {
throw new \InvalidArgumentException('Invalid FVD format.');
}
$result = array('font-style' => null, 'font-weight' => null);
// Parse font-style.
switch ($fvd[0]) {
case 'n':
$result['font-style'] = 'normal';
break;
case 'i':
$result['font-style'] = 'italic';
break;
case 'o':
$result['font-style'] = 'oblique';
break;
default:
throw new \LogicException('Invalid font-style: ' . $fvd[0]);
}
// Parse font-weight
$result['font-weight'] = intval($fvd[1]) * 100;
return $result;
}
static protected function parseFontStyle($value)
{
switch ($value) {
case 'normal':
return 'n';
case 'italic':
return 'i';
case 'oblique':
return 'o';
}
throw new \InvalidArgumentException('Invalid font style: ' . $value);
}
static protected function parseFontWeight($value)
{
if ($value == 'normal') {
return 4;
}
else if ($value == 'bold') {
return 7;
}
$result = intval($value[0]);
if ($result < 1) {
throw new \InvalidArgumentException('Invalid font weight: ' . $value);
}
return $result;
}
}