Completed
Push — master ( 634c3a...7d6b1f )
by smiley
02:28
created

TraversalTrait::match()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Trait TraversalTrait
4
 *
5
 * @filesource   TraversalTrait.php
6
 * @created      06.05.2017
7
 * @package      chillerlan\PrototypeDOM
8
 * @author       Smiley <[email protected]>
9
 * @copyright    2017 Smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\PrototypeDOM;
14
15
use DOMNode;
16
17
/**
18
 * @extends \DOMNode
19
 */
20
trait TraversalTrait{
21
22
	/**
23
	 * @link http://php.net/manual/class.domnode.php#domnode.props.ownerdocument
24
	 *
25
	 * @var \chillerlan\PrototypeDOM\Document
26
	 */
27
	public $ownerDocument;
28
29
	/**
30
	 * @param string $property
31
	 * @param int    $maxLength
32
	 * @param int    $nodeType
33
	 *
34
	 * @return \chillerlan\PrototypeDOM\NodeList
35
	 */
36 2
	public function recursivelyCollect(string $property, int $maxLength = -1, int $nodeType = XML_ELEMENT_NODE):NodeList{
37
		/** @var \DOMNode $this */
38 2
		return $this->ownerDocument->recursivelyCollect($this, $property, $maxLength, $nodeType);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMDocument as the method recursivelyCollect() does only exist in the following sub-classes of DOMDocument: chillerlan\PrototypeDOM\Document. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
39
	}
40
41
	/**
42
	 * @param        $selector
43
	 * @param        $index
44
	 * @param string $property
45
	 * @param int    $nodeType
46
	 *
47
	 * @return \DOMNode|null
48
	 */
49 5
	public function _recursivelyFind($selector, $index, string $property, int $nodeType = XML_ELEMENT_NODE){
50
51 5
		if(is_numeric($selector)){
52 3
			$index    = $selector;
53 3
			$selector = null;
54
		}
55
56
		/** @var \chillerlan\PrototypeDOM\Element $this */
57 5
		return $this->ownerDocument->_recursivelyFind($this, $property, $selector, $index ?? 0, $nodeType);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMDocument as the method _recursivelyFind() does only exist in the following sub-classes of DOMDocument: chillerlan\PrototypeDOM\Document. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
58
	}
59
60
	/**
61
	 * @param bool $xml
62
	 *
63
	 * @return string
64
	 */
65 3
	public function inspect($xml = false):string{
66 3
		return $this->ownerDocument->inspect($this, $xml);
67
	}
68
69
	/**
70
	 * @param string|array $selectors
71
	 *
72
	 * @return \chillerlan\PrototypeDOM\NodeList
73
	 */
74 4
	public function select($selectors = null):NodeList{
75 4
		return $this->ownerDocument->select($selectors, $this, 'descendant::');
76
	}
77
78
	/**
79
	 * @param string $selector
80
	 *
81
	 * @return bool
82
	 */
83 2
	public function match(string $selector):bool{
84
		/** @var \chillerlan\PrototypeDOM\Element $this */
85 2
		return $this->ownerDocument->match($this, $selector);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DOMDocument as the method match() does only exist in the following sub-classes of DOMDocument: chillerlan\PrototypeDOM\Document. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
86
	}
87
88
	/**
89
	 * @param null $expression
90
	 * @param int  $index
91
	 *
92
	 * @return \DOMNode|null
93
	 */
94 2
	public function down($expression = null, int $index = 0){
95
96 2
		if(count(func_get_args()) === 0){
97 2
			return $this->firstDescendant();
98
		}
99
100 1
		if(is_numeric($expression)){
101 1
			$index      = $expression;
102 1
			$expression = '*';
103
		}
104
105 1
		return $this->select(is_string($expression) ? $expression : null)[$index] ?? null;
106
	}
107
108
	/**
109
	 * @param string|null $expression
110
	 * @param int|null    $index
111
	 *
112
	 * @return \DOMNode|null
113
	 */
114 2
	public function up($expression = null, int $index = null){
115 2
		return $this->_recursivelyFind($expression, $index, 'parentNode');
116
	}
117
118
	/**
119
	 * @param string|null $expression
120
	 * @param int|null    $index
121
	 *
122
	 * @return \DOMNode|null
123
	 */
124 1
	public function previous($expression = null, int $index = null){
125 1
		return $this->_recursivelyFind($expression, $index, 'previousSibling');
126
	}
127
128
	/**
129
	 * @param string|null $expression
130
	 * @param int|null    $index
131
	 *
132
	 * @return \DOMNode|null
133
	 */
134 3
	public function next($expression = null, int $index = null){
135 3
		return $this->_recursivelyFind($expression, $index, 'nextSibling');
136
	}
137
138
	/**
139
	 * @param int $nodeType
140
	 *
141
	 * @return \chillerlan\PrototypeDOM\NodeList
142
	 */
143 1
	public function childElements(int $nodeType = XML_ELEMENT_NODE):NodeList{
144 1
		$children = new NodeList;
145
146 1
		if($this->hasChildNodes()){
0 ignored issues
show
Bug introduced by
It seems like hasChildNodes() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
147
148 1
			foreach($this->childNodes as $child){
0 ignored issues
show
Bug introduced by
The property childNodes does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
149
150 1
				if($child->nodeType === $nodeType){
151 1
					$children[] = $child;
152
				}
153
154
			}
155
156
		}
157
158 1
		return $children;
159
	}
160
161
	/**
162
	 * @param \DOMNode $ancestor
163
	 *
164
	 * @return bool
165
	 */
166 1
	public function descendantOf(DOMNode $ancestor):bool{
167 1
		return $this->ancestors()->match($ancestor);
168
	}
169
170
	/**
171
	 * @return \chillerlan\PrototypeDOM\NodeList
172
	 */
173 2
	public function ancestors():NodeList{
174 2
		return $this->recursivelyCollect('parentNode');
175
	}
176
177
	/**
178
	 * @return \chillerlan\PrototypeDOM\NodeList
179
	 */
180 1
	public function siblings():NodeList{
181 1
		return $this->previousSiblings()->reverse()->merge($this->nextSiblings());
182
	}
183
184
	/**
185
	 * @return \chillerlan\PrototypeDOM\NodeList
186
	 */
187 4
	public function descendants():NodeList{
188 4
		return $this->select();
189
	}
190
191
	/**
192
	 * @return \DOMNode|null
193
	 */
194 3
	public function firstDescendant(){
195 3
		return $this->descendants()[0] ?? null;
196
	}
197
198
	/**
199
	 * @return \chillerlan\PrototypeDOM\NodeList
200
	 */
201 1
	public function previousSiblings():NodeList{
202 1
		return $this->recursivelyCollect('previousSibling');
203
	}
204
205
	/**
206
	 * @return \chillerlan\PrototypeDOM\NodeList
207
	 */
208 1
	public function nextSiblings():NodeList{
209 1
		return $this->recursivelyCollect('nextSibling');
210
	}
211
212
}
213