Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 115 additions & 3 deletions src/Extraction/AbstractHtmlExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace JoliCode\StructuredData\Extraction;

use JoliCode\StructuredData\JsonLd\Parser\Range;

/**
* Base class for extractors that parse structured data from HTML DOM trees.
*
Expand Down Expand Up @@ -41,6 +43,99 @@ protected function loadDocument(string $body): \Dom\HTMLDocument
return $this->documentLoader->load($body);
}

/**
* Locates, in $body, the elements of the document loadDocument() parsed
* from it.
*/
protected function loadLocator(string $body): HtmlSourceLocator
{
return $this->documentLoader->locator($body);
}

/**
* The start tag of the element, or its whole line when the start tag
* cannot be located.
*/
protected static function anchorOf(HtmlSourceLocator $locator, \Dom\Element $element): Range
{
return $locator->startTag($element) ?? $locator->line($element);
}

/**
* Collects the descendants of $root matching $isProperty, in document order,
* as both the microdata and RDFa specifications order property values. The
* descendants of an element for which $stopsAt is true are not visited.
*
* @param callable(\Dom\Element): bool $isProperty
* @param callable(\Dom\Element): bool $stopsAt
*
* @return list<\Dom\Element>
*/
protected static function collectInDocumentOrder(\Dom\Element $root, callable $isProperty, callable $stopsAt): array
{
$propertyNodes = [];
// A stack rather than recursion, for deeply nested pages; children are
// pushed last first, so that the first one is visited first.
$stack = array_reverse(self::childElements($root));

while ($stack) {
$node = array_pop($stack);

if ($isProperty($node)) {
$propertyNodes[] = $node;
}

if ($stopsAt($node)) {
continue;
}

foreach (array_reverse(self::childElements($node)) as $child) {
$stack[] = $child;
}
}

return $propertyNodes;
}

/**
* Groups the values found for each property name into the properties of an
* item, and the source map of those properties.
*
* A name found once holds its value; a name found several times holds the
* list of its values, in document order.
*
* @param array<string, non-empty-list<array{value: mixed, map: SourceMap, key: Range}>> $occurrences the values of each name, in document order
*
* @return array{array<string, mixed>, SourceMap}
*/
protected static function buildProperties(array $occurrences): array
{
$properties = [];
$sourceMap = new SourceMap();

foreach ($occurrences as $name => $values) {
$pointer = SourceMap::pointerSegment($name);
$sourceMap->setKey($pointer, $values[0]['key']);

if (1 === \count($values)) {
$properties[$name] = $values[0]['value'];
$sourceMap->merge($values[0]['map'], $pointer);

continue;
}

$properties[$name] = array_column($values, 'value');
// The list as a whole is anchored on its first value.
$sourceMap->setValue($pointer, $values[0]['map']->getValue(''));

foreach ($values as $index => $value) {
$sourceMap->merge($value['map'], $pointer . SourceMap::pointerSegment($index));
}
}

return [$properties, $sourceMap];
}

/**
* Builds a human-readable location suffix like " at line 42" or
* " at lines 12, 34" from a list of DOM node line numbers.
Expand Down Expand Up @@ -76,11 +171,12 @@ protected static function lineOf(\Dom\Element $node): int
}

/**
* Encodes one extracted item into a JsonLdElement anchored on its DOM node.
* Encodes one extracted item into a JsonLdElement anchored on its DOM node,
* whose $sourceMap tells where each of its keys and values comes from.
*
* @throws ExtractionException when the item cannot be encoded
*/
protected function encodeAsJsonLdElement(\Dom\Element $node, mixed $item, string $encodeFailureMessage): JsonLdElement
protected function encodeAsJsonLdElement(\Dom\Element $node, mixed $item, string $encodeFailureMessage, ?SourceMap $sourceMap = null): JsonLdElement
{
$encoded = json_encode($item, \JSON_UNESCAPED_SLASHES);

Expand All @@ -89,7 +185,7 @@ protected function encodeAsJsonLdElement(\Dom\Element $node, mixed $item, string
}

// JsonLdElement counts lines from 0, as the parser does.
return new JsonLdElement($node->getLineNo(), 0, $encoded, $this->getFormat());
return new JsonLdElement($node->getLineNo(), 0, $encoded, $this->getFormat(), $sourceMap);
}

/**
Expand Down Expand Up @@ -126,4 +222,20 @@ protected function formatRanges(array $lineNumbers): string
),
);
}

/**
* @return list<\Dom\Element>
*/
private static function childElements(\Dom\Element $node): array
{
$children = [];

foreach ($node->childNodes as $childNode) {
if ($childNode instanceof \Dom\Element) {
$children[] = $childNode;
}
}

return $children;
}
}
15 changes: 15 additions & 0 deletions src/Extraction/HtmlDocumentLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ class HtmlDocumentLoader

private ?\Dom\HTMLDocument $lastDocument = null;

private ?HtmlSourceLocator $lastLocator = null;

/**
* Parses $body as HTML5: malformed markup is recovered from, never refused.
*
Expand All @@ -44,13 +46,26 @@ public function load(string $body): \Dom\HTMLDocument

$this->lastBody = $body;
$this->lastDocument = $document;
$this->lastLocator = null;

return $document;
}

/**
* Locates the elements of the document parsed from $body in that body,
* sharing the memoized document and its source scan between extractors.
*/
public function locator(string $body): HtmlSourceLocator
{
$document = $this->load($body);

return $this->lastLocator ??= new HtmlSourceLocator($body, $document);
}

public function reset(): void
{
$this->lastBody = null;
$this->lastDocument = null;
$this->lastLocator = null;
}
}
Loading