Passed
Push — master ( f13612...5c9f14 )
by Josh
02:53
created

AddAttributeValueToElements::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 3
crap 1
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_split('(\\s+)', $attrValue, -1, PREG_SPLIT_NO_EMPTY);
0 ignored issues
show
Bug Best Practice introduced by
The expression return preg_split('(\s+)...ns\PREG_SPLIT_NO_EMPTY) could return the type false which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
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
}