Added MicrodataDOMDocument

This is for both gaining flexibility and made code cleaner.
This commit is contained in:
Yusuf Kandemir 2018-11-12 18:05:31 +03:00
parent daa8efa0fa
commit e17ceac9ea
4 changed files with 46 additions and 10 deletions

View File

@ -6,7 +6,7 @@ abstract class Microdata
{
public static function fromHTML($html, $documentURI = '')
{
$dom = new \DOMDocument;
$dom = new MicrodataDOMDocument;
$dom->loadHTML($html, LIBXML_NOERROR);
$dom->documentURI = $documentURI;
@ -15,15 +15,19 @@ abstract class Microdata
public static function fromHTMLFile($filename, $documentURI = '')
{
$dom = new \DOMDocument;
$dom = new MicrodataDOMDocument;
$dom->loadHTMLFile($filename);
$dom->documentURI = $documentURI;
return new MicrodataParser($dom);
}
public static function fromDOMDocument(\DOMDocument $dom)
public static function fromDOMDocument(\DOMDocument $domDocument)
{
$dom = new MicrodataDOMDocument;
$importedNode = $dom->importNode($domDocument->documentElement, true);
$dom->appendChild($importedNode);
return new MicrodataParser($dom);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace YusufKandemir\MicrodataParser;
class MicrodataDOMDocument extends \DOMDocument
{
public $xpath;
public function getItems()
{
return $this->xpath->query('//*[@itemscope and not(@itemprop)]');
}
public function loadHTML($source, $options = 0)
{
$return = parent::loadHTML($source, $options);
$this->xpath = new \DOMXPath($this);
return $return;
}
public function loadHTMLFile($filename, $options = 0)
{
$return = parent::loadHTMLFile($filename, $options);
$this->xpath = new \DOMXPath($this);
return $return;
}
}

View File

@ -4,14 +4,14 @@ namespace YusufKandemir\MicrodataParser;
class MicrodataParser
{
protected $topLevelItems;
protected $dom;
public function __construct(\DOMDocument $dom)
public function __construct(MicrodataDOMDocument $dom)
{
$dom->registerNodeClass(\DOMDocument::class, MicrodataDOMDocument::class);
$dom->registerNodeClass(\DOMElement::class, MicrodataDOMElement::class);
$xpath = new \DOMXPath($dom);
$this->topLevelItems = $xpath->query('//*[@itemscope and not(@itemprop)]');
$this->dom = $dom;
}
public function toArray()
@ -36,8 +36,8 @@ class MicrodataParser
$result->items = [];
foreach ($this->topLevelItems as $topLevelItem) {
$result->items[] = $this->getObject($topLevelItem);
foreach ($this->dom->getItems() as $item) {
$result->items[] = $this->getObject($item);
}
return $result;

View File

@ -2,6 +2,7 @@
namespace YusufKandemir\MicrodataParser\Tests;
use YusufKandemir\MicrodataParser\MicrodataDOMDocument;
use YusufKandemir\MicrodataParser\MicrodataParser;
class MicrodataParserTest extends \PHPUnit\Framework\TestCase
@ -13,7 +14,7 @@ class MicrodataParserTest extends \PHPUnit\Framework\TestCase
protected function getParser($data)
{
$dom = new \DOMDocument;
$dom = new MicrodataDOMDocument;
$dom->loadHTML($data['source']);
$dom->documentURI = $data['uri'];