Skip to content

Commit 26968b2

Browse files
author
Harrison Ifeanyichukwu
committed
feat: add XML module, instance of this module represents the feed document
The xml module parses the feed content, reporting the parse status and any detected errors.
1 parent 0bcc2ad commit 26968b2

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

src/XML.php

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
<?php
2+
declare(strict_types = 1);
3+
4+
namespace Forensic\FeedParser;
5+
6+
class XML
7+
{
8+
private $_doc = null;
9+
private $_errors = [];
10+
11+
public function __construct(string $xml = null)
12+
{
13+
$this->parse($xml);
14+
}
15+
16+
/**
17+
* parses the xml string into a document.
18+
*
19+
*@return boolean
20+
*/
21+
public function parse(string $xml = null)
22+
{
23+
$this->_doc = null;
24+
$this->_errors = [];
25+
26+
//if no string was provided, bail out
27+
if (is_null($xml))
28+
return false;
29+
30+
libxml_use_internal_errors(true);
31+
$this->_doc = $doc = new \DOMDocument();
32+
33+
//if document was loaded successfully, bail out
34+
if ($doc->loadXML(trim($xml)))
35+
return true;
36+
37+
foreach (libxml_get_errors() as $error)
38+
{
39+
switch ($error->level)
40+
{
41+
//only take error and fatal level errors, ignore warnings
42+
case LIBXML_ERR_ERROR:
43+
case LIBXML_ERR_FATAL:
44+
$this->_errors[] = $error->message . ' on line ' . $error->line;
45+
break;
46+
}
47+
}
48+
libxml_clear_errors();
49+
50+
//reset doc to null if error exists
51+
if (count($this->_errors) > 0)
52+
$this->_doc = null;
53+
54+
return $this->status();
55+
}
56+
57+
/**
58+
* returns the xml document or null if not parsed successful.
59+
*
60+
*@return \DOMDocument|null
61+
*/
62+
public function document()
63+
{
64+
return $this->_doc;
65+
}
66+
67+
/**
68+
* returns the parser detected errors
69+
*
70+
*@return array
71+
*/
72+
public function errors()
73+
{
74+
return $this->_errors;
75+
}
76+
77+
/**
78+
* returns the document parse status
79+
*
80+
*@return boolean
81+
*/
82+
public function status()
83+
{
84+
return !is_null($this->_doc);
85+
}
86+
}

0 commit comments

Comments
 (0)