Skip to content

Commit e31afbd

Browse files
author
Harrison Ifeanyichukwu
committed
feat: add XPath module, to be used in querying and processing the feed
1 parent 6b04553 commit e31afbd

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

src/XPath.php

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php
2+
declare(strict_types = 1);
3+
4+
namespace Forensic\FeedParser;
5+
6+
use DOMDocument;
7+
use DOMXPath;
8+
use DOMNode;
9+
10+
class XPath
11+
{
12+
private $_dom_xpath = null;
13+
14+
public function __construct(DOMDocument $doc)
15+
{
16+
$this->_dom_xpath = new DOMXPath($doc);
17+
}
18+
19+
/**
20+
* registers namespace
21+
*
22+
*@return boolean
23+
*/
24+
public function registerNamespace(string $prefix, string $namespacePrefix)
25+
{
26+
return $this->_dom_xpath->registerNamespace($prefix, $namespacePrefix);
27+
}
28+
29+
/**
30+
* registers namespaces
31+
*/
32+
public function registerNamespaces(array $namespaces)
33+
{
34+
foreach($namespaces as $prefix => $namespacePrefix)
35+
if (is_string($prefix) && is_string($namespacePrefix))
36+
$this->registerNamespace($prefix, $namespacePrefix);
37+
}
38+
39+
/**
40+
* queries the document and returns a single result item or null
41+
*
42+
*@return DOMNode|null
43+
*/
44+
public function selectNode(string $expression, DOMNode $context_node = null)
45+
{
46+
$result = $this->_dom_xpath->query($expression, $context_node);
47+
if ($result === false || $result->length === 0)
48+
return null;
49+
50+
return $result->item(0);
51+
}
52+
53+
/**
54+
* queries the document and returns a a DOMNodeList or null
55+
*
56+
*@return DOMNodeList|null
57+
*/
58+
public function selectNodes(string $expression, DOMNode $context_node = null)
59+
{
60+
$result = $this->_dom_xpath->query($expression, $context_node);
61+
if ($result === false)
62+
return null;
63+
64+
return $result;
65+
}
66+
67+
/**
68+
* returns the dom xpath
69+
*
70+
*@return DOMXPath
71+
*/
72+
public function get()
73+
{
74+
return $this->_dom_xpath;
75+
}
76+
}

0 commit comments

Comments
 (0)