Processor.php
3.1 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
<?php
namespace TijsVerkoyen\CssToInlineStyles\Css\Property;
use Symfony\Component\CssSelector\Node\Specificity;
class Processor
{
/**
* Split a string into separate properties
*
* @param string $propertiesString
*
* @return string[]
*/
public function splitIntoSeparateProperties($propertiesString)
{
$propertiesString = $this->cleanup($propertiesString);
$properties = (array) explode(';', $propertiesString);
$keysToRemove = array();
$numberOfProperties = count($properties);
for ($i = 0; $i < $numberOfProperties; $i++) {
$properties[$i] = trim($properties[$i]);
// if the new property begins with base64 it is part of the current property
if (isset($properties[$i + 1]) && strpos(trim($properties[$i + 1]), 'base64,') === 0) {
$properties[$i] .= ';' . trim($properties[$i + 1]);
$keysToRemove[] = $i + 1;
}
}
if (!empty($keysToRemove)) {
foreach ($keysToRemove as $key) {
unset($properties[$key]);
}
}
return array_values($properties);
}
/**
* @param string $string
*
* @return string
*/
private function cleanup($string)
{
$string = str_replace(array("\r", "\n"), '', $string);
$string = str_replace(array("\t"), ' ', $string);
$string = str_replace('"', '\'', $string);
$string = preg_replace('|/\*.*?\*/|', '', $string);
$string = preg_replace('/\s\s+/', ' ', $string);
$string = trim($string);
$string = rtrim($string, ';');
return $string;
}
/**
* Converts a property-string into an object
*
* @param string $property
*
* @return Property|null
*/
public function convertToObject($property, Specificity $specificity = null)
{
if (strpos($property, ':') === false) {
return null;
}
list($name, $value) = explode(':', $property, 2);
$name = trim($name);
$value = trim($value);
if ($value === '') {
return null;
}
return new Property($name, $value, $specificity);
}
/**
* Converts an array of property-strings into objects
*
* @param string[] $properties
*
* @return Property[]
*/
public function convertArrayToObjects(array $properties, Specificity $specificity = null)
{
$objects = array();
foreach ($properties as $property) {
$object = $this->convertToObject($property, $specificity);
if ($object === null) {
continue;
}
$objects[] = $object;
}
return $objects;
}
/**
* Build the property-string for multiple properties
*
* @param Property[] $properties
*
* @return string
*/
public function buildPropertiesString(array $properties)
{
$chunks = array();
foreach ($properties as $property) {
$chunks[] = $property->toString();
}
return implode(' ', $chunks);
}
}