Completed
Push — master ( a509ec...f043ba )
by Dan Michael O.
01:03
created

HelperMethods::xpath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Danmichaelo\QuiteSimpleXMLElement;
4
5
use SimpleXMLElement;
6
7
trait HelperMethods
8
{
9
    /**
10
     * @var SimpleXMLElement
11
     */
12
    public $el;
13
14
    /**
15
     * Get a node attribute value.
16
     *
17
     * @param string $attribute
18
     * @return string
19
     */
20
    public function attr($attribute)
21
    {
22
        return trim((string) $this->el->attributes()->{$attribute});
23
    }
24
25
    /**
26
     * Get the first node matching an XPath query, or null if no match.
27
     *
28
     * @param string $path
29
     * @return QuiteSimpleXMLElement
30
     */
31
    public function first($path)
32
    {
33
        // Convenience method
34
        $x = $this->xpath($path);
35
36
        return count($x) ? $x[0] : null;
37
    }
38
39
    /**
40
     * Check if the document has at least one node matching an XPath query.
41
     *
42
     * @param string $path
43
     * @return bool
44
     */
45
    public function has($path)
46
    {
47
        $x = $this->xpath($path);
48
49
        return count($x) ? true : false;
50
    }
51
52
    /**
53
     * Get all nodes matching an XPath query.
54
     *
55
     * @param string $path
56
     * @return QuiteSimpleXMLElement[]
57
     */
58
    public function xpath($path)
59
    {
60
        return array_map(function ($el) {
61
            return new QuiteSimpleXMLElement($el, $this);
62
        }, $this->el->xpath($path));
63
    }
64
65
    /**
66
     * Alias for `xpath()`.
67
     *
68
     * @param $path
69
     * @return QuiteSimpleXMLElement[]
70
     */
71
    public function all($path)
72
    {
73
        return $this->xpath($path);
74
    }
75
76
77
}