|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* @package s9e\TextFormatter |
|
5
|
|
|
* @copyright Copyright (c) 2010-2020 The s9e authors |
|
6
|
|
|
* @license http://www.opensource.org/licenses/mit-license.php The MIT License |
|
7
|
|
|
*/ |
|
8
|
|
|
namespace s9e\TextFormatter\Configurator\TemplateNormalizations; |
|
9
|
|
|
|
|
10
|
|
|
use DOMElement; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Add a value to a list of space-separated value |
|
14
|
|
|
*/ |
|
15
|
|
|
class AddAttributeValueToElements extends AbstractNormalization |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var string Name of the attribute to modify |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $attrName; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var string Value to be added to the attribute |
|
24
|
|
|
*/ |
|
25
|
|
|
protected $value; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @param string $query XPath query used to locate elements |
|
29
|
|
|
* @param string $attrName Name of the attribute to modify |
|
30
|
|
|
* @param string $value Value to be added to the attribute |
|
31
|
|
|
*/ |
|
32
|
5 |
|
public function __construct(string $query, string $attrName, string $value) |
|
33
|
|
|
{ |
|
34
|
5 |
|
$this->attrName = $attrName; |
|
35
|
5 |
|
$this->queries = [$query]; |
|
36
|
5 |
|
$this->value = $value; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Explode a string of space-separated values into an array |
|
41
|
|
|
* |
|
42
|
|
|
* @param string $attrValue Attribute's value |
|
43
|
|
|
* @return string[] |
|
44
|
|
|
*/ |
|
45
|
4 |
|
protected function getValues(string $attrValue): array |
|
46
|
|
|
{ |
|
47
|
4 |
|
return preg_match_all('(\\S++)', $attrValue, $m) ? $m[0] : []; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* {@inheritdoc} |
|
52
|
|
|
*/ |
|
53
|
4 |
|
protected function normalizeElement(DOMElement $element): void |
|
54
|
|
|
{ |
|
55
|
4 |
|
$currentValues = $this->getValues($element->getAttribute($this->attrName)); |
|
56
|
4 |
|
if (!in_array($this->value, $currentValues, true)) |
|
57
|
|
|
{ |
|
58
|
3 |
|
$currentValues[] = $this->value; |
|
59
|
|
|
|
|
60
|
3 |
|
$element->setAttribute($this->attrName, implode(' ', $currentValues)); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
} |