From 726d8dc9c1b21b60018cad3d599373cfcffcd63c Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Mon, 23 Nov 2026 20:01:27 +0100 Subject: [PATCH 1/3] Count columns in UTF-16 code units, as the editor does --- src/Extraction/JsonLdNodeExtractor.php | 9 +++-- src/JsonLd/Parser/PointerListener.php | 7 ++-- src/JsonLd/Parser/PositionAwareJsonParser.php | 13 +++---- src/JsonLd/Parser/Utf16.php | 36 +++++++++++++++++++ tests/Validation/JsonLdParserTest.php | 13 +++++++ 5 files changed, 66 insertions(+), 12 deletions(-) create mode 100644 src/JsonLd/Parser/Utf16.php diff --git a/src/Extraction/JsonLdNodeExtractor.php b/src/Extraction/JsonLdNodeExtractor.php index cab85c86c..dce327d7d 100644 --- a/src/Extraction/JsonLdNodeExtractor.php +++ b/src/Extraction/JsonLdNodeExtractor.php @@ -11,6 +11,8 @@ namespace JoliCode\StructuredData\Extraction; +use JoliCode\StructuredData\JsonLd\Parser\Utf16; + class JsonLdNodeExtractor extends AbstractHtmlExtractor { // The quotes are optional in HTML, and minifiers remove them. Whitespace may surround @@ -86,13 +88,14 @@ private function extractJsonLdNodes(string $body): array $startLine = substr_count($bodyPrefix, "\n"); + // Columns count UTF-16 code units, as the editors displaying them do. if (0 === $startLine) { - $startColumn = mb_strlen($bodyPrefix); + $startColumn = Utf16::length($bodyPrefix); } else { $lastLineReturnPosition = strrpos($bodyPrefix, "\n"); $startColumn = false === $lastLineReturnPosition - ? mb_strlen($bodyPrefix) - : mb_strlen(substr($bodyPrefix, $lastLineReturnPosition + 1)); + ? Utf16::length($bodyPrefix) + : Utf16::length(substr($bodyPrefix, $lastLineReturnPosition + 1)); } $jsonLdElement = new JsonLdElement($startLine, $startColumn, $match[0], $this->getFormat()); diff --git a/src/JsonLd/Parser/PointerListener.php b/src/JsonLd/Parser/PointerListener.php index ad21b7b3e..26ea6ce8e 100644 --- a/src/JsonLd/Parser/PointerListener.php +++ b/src/JsonLd/Parser/PointerListener.php @@ -104,11 +104,12 @@ public function value($value): void private function adjustFilePosition(string $string): int { $byteLength = \strlen($string); - $characterLength = mb_strlen($string); + // Columns count UTF-16 code units, as the editors displaying them do. + $width = Utf16::length($string); - $this->currentColumnAdjustment += $characterLength - $byteLength; + $this->currentColumnAdjustment += $width - $byteLength; - return $characterLength; + return $width; } private function startStructure(string $structureClass): void diff --git a/src/JsonLd/Parser/PositionAwareJsonParser.php b/src/JsonLd/Parser/PositionAwareJsonParser.php index 23c267b18..14ed77c9f 100644 --- a/src/JsonLd/Parser/PositionAwareJsonParser.php +++ b/src/JsonLd/Parser/PositionAwareJsonParser.php @@ -42,8 +42,8 @@ final class PositionAwareJsonParser private int $lineStart = 0; /** - * Cumulated difference between character and byte lengths of the string - * tokens processed on the current line, so that columns count characters. + * Cumulated difference between UTF-16 and byte lengths of the string tokens + * processed on the current line, so that columns count UTF-16 code units. */ private int $columnAdjustment = 0; @@ -261,13 +261,14 @@ private function parseString(int $offset): array $decoded = \is_string($decodedRaw) ? $decodedRaw : ''; } - // Columns count characters, not bytes: the difference for this token - // applies to it and to everything that follows on the same line. - $this->columnAdjustment += mb_strlen($decoded) - \strlen($decoded); + // Columns count UTF-16 code units, not bytes: the difference for this + // token applies to it and to everything that follows on the same line. + $width = Utf16::length($decoded); + $this->columnAdjustment += $width - \strlen($decoded); $end = $this->position($closingQuote); $start = clone $end; - $start->column -= mb_strlen($decoded); + $start->column -= $width; return [$closingQuote + 1, $decoded, new Range($start, $end)]; } diff --git a/src/JsonLd/Parser/Utf16.php b/src/JsonLd/Parser/Utf16.php new file mode 100644 index 000000000..c518b4f42 --- /dev/null +++ b/src/JsonLd/Parser/Utf16.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Parser; + +/** + * Columns are counted in UTF-16 code units, as editors running in a browser + * (CodeMirror, Monaco) and JavaScript strings count them: a character outside + * the Basic Multilingual Plane, such as most emoji, takes two columns. + */ +final class Utf16 +{ + /** + * The length of a UTF-8 string in UTF-16 code units. + */ + public static function length(string $string): int + { + $length = mb_strlen($string, 'UTF-8'); + + if ($length === \strlen($string)) { + return $length; + } + + // Each character outside the BMP is encoded on four bytes in UTF-8, led + // by a byte from 0xF0 to 0xF4, and takes a surrogate pair in UTF-16. + return $length + (int) preg_match_all('/[\xF0-\xF4]/', $string); + } +} diff --git a/tests/Validation/JsonLdParserTest.php b/tests/Validation/JsonLdParserTest.php index eb699668a..5d0d0b44a 100644 --- a/tests/Validation/JsonLdParserTest.php +++ b/tests/Validation/JsonLdParserTest.php @@ -65,6 +65,19 @@ public function testADocumentWithATrailingCommaIsStillRead(): void $this->assertSame($this->range($wellFormed->getProperty('c')->value?->content), $this->range($list)); } + public function testColumnsCountUtf16CodeUnits(): void + { + // The emoji takes two columns, as in a browser editor; both parsers agree. + foreach (['{"a":"🙂","b":"x"}', '{"a":"🙂","b":"x",}'] as $content) { + $structure = $this->parse($content); + $this->assertInstanceOf(ObjectStructure::class, $structure); + + $property = $structure->getProperty('b'); + $this->assertSame('11:16 to 11:17', $property->key->range->start . ' to ' . $property->key->range->end, $content); + $this->assertSame('11:20 to 11:21', $property->value?->range->start . ' to ' . $property->value?->range->end, $content); + } + } + private function range(mixed $structure): string { $this->assertInstanceOf(AbstractStructure::class, $structure); From ef320dd6dad379d8936cab56a061f965be9034ce Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Mon, 23 Nov 2026 20:03:03 +0100 Subject: [PATCH 2/3] Read microdata and RDFa properties in document order --- src/Extraction/AbstractHtmlExtractor.php | 52 ++++++++++++++++++++++++ src/Extraction/MicrodataExtractor.php | 37 ++++------------- src/Extraction/RdfaExtractor.php | 38 ++++------------- tests/Validation/ExtractorTest.php | 42 +++++++++++++++++++ 4 files changed, 110 insertions(+), 59 deletions(-) diff --git a/src/Extraction/AbstractHtmlExtractor.php b/src/Extraction/AbstractHtmlExtractor.php index 9c5bed00f..1e219bdb8 100644 --- a/src/Extraction/AbstractHtmlExtractor.php +++ b/src/Extraction/AbstractHtmlExtractor.php @@ -41,6 +41,42 @@ protected function loadDocument(string $body): \Dom\HTMLDocument return $this->documentLoader->load($body); } + /** + * 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; + } + /** * Builds a human-readable location suffix like " at line 42" or * " at lines 12, 34" from a list of DOM node line numbers. @@ -126,4 +162,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; + } } diff --git a/src/Extraction/MicrodataExtractor.php b/src/Extraction/MicrodataExtractor.php index 87999d271..8d1d1f671 100644 --- a/src/Extraction/MicrodataExtractor.php +++ b/src/Extraction/MicrodataExtractor.php @@ -243,35 +243,14 @@ private function extractProperties(\Dom\Element $itemElement, \Dom\XPath $xpath) */ private function collectPropertyNodesForItem(\Dom\Element $itemElement): array { - $propertyNodes = []; - $stack = []; - - foreach ($itemElement->childNodes as $childNode) { - if ($childNode instanceof \Dom\Element) { - $stack[] = $childNode; - } - } - - while ($stack) { - $node = array_pop($stack); - - if ($node->hasAttribute('itemprop')) { - $propertyNodes[] = $node; - } - - // Skip descending into nested itemscopes (they will be extracted as nested items) - if ($node->hasAttribute('itemscope')) { - continue; - } - - foreach ($node->childNodes as $childNode) { - if ($childNode instanceof \Dom\Element) { - $stack[] = $childNode; - } - } - } - - return $propertyNodes; + // Properties are read in document order, as the specification orders + // the values of a repeated property. A nested item is not descended + // into: its properties are its own. + return self::collectInDocumentOrder( + $itemElement, + static fn (\Dom\Element $node): bool => $node->hasAttribute('itemprop'), + static fn (\Dom\Element $node): bool => $node->hasAttribute('itemscope'), + ); } private function extractPropertyValue(\Dom\Element $propertyNode): ?string diff --git a/src/Extraction/RdfaExtractor.php b/src/Extraction/RdfaExtractor.php index e4c5c8b4a..219b1e9b8 100644 --- a/src/Extraction/RdfaExtractor.php +++ b/src/Extraction/RdfaExtractor.php @@ -266,36 +266,14 @@ private function extractProperties(\Dom\Element $subjectNode): array */ private function collectPropertyNodesForSubject(\Dom\Element $subjectNode): array { - $propertyNodes = []; - $stack = []; - - foreach ($subjectNode->childNodes as $childNode) { - if ($childNode instanceof \Dom\Element) { - $stack[] = $childNode; - } - } - - while ($stack) { - $node = array_pop($stack); - - if ($node->hasAttribute('property')) { - $propertyNodes[] = $node; - } - - // Skip descending into schema.org subjects that don't have property attributes - // (property+typeof nodes are handled above and their nested subjects are extracted in extractProperties) - if ($this->isSchemaOrgSubject($node) && !$node->hasAttribute('property')) { - continue; - } - - foreach ($node->childNodes as $childNode) { - if ($childNode instanceof \Dom\Element) { - $stack[] = $childNode; - } - } - } - - return $propertyNodes; + // Properties are read in document order. Schema.org subjects that don't + // have a property attribute are not descended into (property+typeof + // nodes are, their nested subjects being extracted in extractProperties). + return self::collectInDocumentOrder( + $subjectNode, + static fn (\Dom\Element $node): bool => $node->hasAttribute('property'), + fn (\Dom\Element $node): bool => $this->isSchemaOrgSubject($node) && !$node->hasAttribute('property'), + ); } private function extractSubjectIdentifier(\Dom\Element $subjectNode): ?string diff --git a/tests/Validation/ExtractorTest.php b/tests/Validation/ExtractorTest.php index d93e7cba1..dda0e4ae7 100644 --- a/tests/Validation/ExtractorTest.php +++ b/tests/Validation/ExtractorTest.php @@ -411,4 +411,46 @@ class="name" (new Extractor())->setExtractors(ExtractorsContainer::MICRODATA)->extract($document); } + + public function testMicrodataPropertiesAreReadInDocumentOrder(): void + { + $document = <<<'HTML' +
+ +
    +
  1. Step 1k1
  2. +
  3. Step 2
  4. +
+ k2 +
+HTML; + + $elements = (new Extractor())->setExtractors(ExtractorsContainer::MICRODATA)->extract($document); + $item = json_decode($elements[0]->content, true); + + $this->assertIsArray($item); + $this->assertSame(['@context', '@type', 'image', 'recipeInstructions', 'keywords'], array_keys($item)); + $this->assertSame(['1.jpg', '2.jpg', '3.jpg'], $item['image']); + $this->assertSame(['Step 1k1', 'Step 2'], $item['recipeInstructions']); + $this->assertSame(['k1', 'k2'], $item['keywords']); + } + + public function testRdfaPropertiesAreReadInDocumentOrder(): void + { + $document = <<<'HTML' +
+ Cake + Step 1 + Step 2 + Step 3 +
+HTML; + + $elements = (new Extractor())->setExtractors(ExtractorsContainer::RDFA)->extract($document); + $item = json_decode($elements[0]->content, true); + + $this->assertIsArray($item); + $this->assertSame(['@context', '@type', 'name', 'recipeInstructions'], array_keys($item)); + $this->assertSame(['Step 1', 'Step 2', 'Step 3'], $item['recipeInstructions']); + } } From 4c967d139087632cb91f182cc42b72de4c5eb055 Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Mon, 23 Nov 2026 20:03:57 +0100 Subject: [PATCH 3/3] Point microdata and RDFa positions at the HTML source instead of the generated JSON --- src/Extraction/AbstractHtmlExtractor.php | 66 ++- src/Extraction/HtmlDocumentLoader.php | 15 + src/Extraction/HtmlSourceLocator.php | 619 ++++++++++++++++++++ src/Extraction/JsonLdElement.php | 6 + src/Extraction/MicrodataExtractor.php | 163 +++--- src/Extraction/RdfaExtractor.php | 148 +++-- src/Extraction/SourceMap.php | 94 +++ src/JsonLd/Parser/JsonLdParser.php | 7 +- src/JsonLd/Parser/SourceMapApplier.php | 90 +++ tests/Validation/HtmlSourcePositionTest.php | 278 +++++++++ 10 files changed, 1369 insertions(+), 117 deletions(-) create mode 100644 src/Extraction/HtmlSourceLocator.php create mode 100644 src/Extraction/SourceMap.php create mode 100644 src/JsonLd/Parser/SourceMapApplier.php create mode 100644 tests/Validation/HtmlSourcePositionTest.php diff --git a/src/Extraction/AbstractHtmlExtractor.php b/src/Extraction/AbstractHtmlExtractor.php index 1e219bdb8..2121371c6 100644 --- a/src/Extraction/AbstractHtmlExtractor.php +++ b/src/Extraction/AbstractHtmlExtractor.php @@ -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. * @@ -41,6 +43,24 @@ 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 @@ -77,6 +97,45 @@ protected static function collectInDocumentOrder(\Dom\Element $root, callable $i 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> $occurrences the values of each name, in document order + * + * @return array{array, 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. @@ -112,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); @@ -125,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); } /** diff --git a/src/Extraction/HtmlDocumentLoader.php b/src/Extraction/HtmlDocumentLoader.php index c885de8b5..6ca6fe847 100644 --- a/src/Extraction/HtmlDocumentLoader.php +++ b/src/Extraction/HtmlDocumentLoader.php @@ -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. * @@ -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; } } diff --git a/src/Extraction/HtmlSourceLocator.php b/src/Extraction/HtmlSourceLocator.php new file mode 100644 index 000000000..4cb0f9080 --- /dev/null +++ b/src/Extraction/HtmlSourceLocator.php @@ -0,0 +1,619 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Extraction; + +use JoliCode\StructuredData\JsonLd\Parser\Position; +use JoliCode\StructuredData\JsonLd\Parser\Range; +use JoliCode\StructuredData\JsonLd\Parser\Utf16; + +/** + * Finds where the elements of a parsed HTML document are written in its source. + * + * Dom\HTMLDocument only tells the line an element starts on, never its column, + * and nothing about its attributes or text. This class scans the source once + * with a small tolerant tokenizer, recording every start tag with the offsets + * of its attributes and of its matching end tag, then pairs each element of + * the DOM with its tag. + * + * An element is paired by its line, its name and its structured data + * attributes, then by its rank among the elements sharing all three: the HTML5 + * parser adds elements of its own (html, body, tbody, clones of misnested + * formatting elements) and moves some (foster parenting), so a plain count of + * the tags would drift. Only elements carrying a structured data attribute are + * paired, the only ones the extractors ask about. An element that cannot be + * paired is not located: callers fall back to its line. + * + * Lines are counted from 1 and columns from 1, in UTF-16 code units, as the + * editors displaying them count them. Ranges end on the column just after + * their last character. + */ +final class HtmlSourceLocator +{ + private const SIGNATURE_ATTRIBUTES = ['itemprop', 'itemscope', 'itemtype', 'itemid', 'property', 'typeof', 'about', 'resource', 'vocab', 'prefix']; + + private const VOID_ELEMENTS = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']; + + /** + * Elements whose content is text up to their end tag, never markup. + */ + private const RAW_TEXT_ELEMENTS = ['script', 'style', 'xmp', 'iframe', 'noembed', 'noframes', 'textarea', 'title']; + + private const WHITESPACE = " \t\n\f\r"; + + private const TRIMMED_CHARACTERS = " \t\n\r\0\x0B"; + + /** + * Bytes between two column checkpoints of a line. + */ + private const COLUMN_CHECKPOINT_SPACING = 1024; + + /** + * @var list}>|null + */ + private ?array $tags = null; + + /** + * The offset of the end tag of each start tag that has one, by tag index. + * + * @var array + */ + private array $closeStarts = []; + + /** + * @var list + */ + private array $lineStarts = []; + + /** + * The line found by the last lookup, where the next one starts. + */ + private int $lineCursor = 0; + + /** + * Known columns of each line, as [offset, column] pairs in increasing order. + * + * @var array> + */ + private array $columnCheckpoints = []; + + /** + * Strong references: the DOM extension hands out the same object for a node + * only while one is alive, so the paired elements are kept alive with the + * locator. + * + * @var \SplObjectStorage<\Dom\Element, int>|null + */ + private ?\SplObjectStorage $elementTags = null; + + public function __construct( + private readonly string $body, + private readonly \Dom\HTMLDocument $document, + ) { + } + + /** + * The start tag of the element, from its "<" to its ">". + */ + public function startTag(\Dom\Element $element): ?Range + { + $tag = $this->tagOf($element); + + return null === $tag ? null : $this->range($tag['start'], $tag['end']); + } + + /** + * The whole line the element starts on, for an element that cannot be + * located more precisely. + */ + public function line(\Dom\Element $element): Range + { + $this->tokenize(); + + $lineIndex = min(max(0, $element->getLineNo()), \count($this->lineStarts) - 1); + $lineStart = $this->lineStarts[$lineIndex]; + $lineEnd = $this->lineStarts[$lineIndex + 1] ?? \strlen($this->body); + + // The next line starts after the line break, which is not part of the + // line; a line holds no other "\r" or "\n". + while ($lineEnd > $lineStart && \in_array($this->body[$lineEnd - 1], ["\r", "\n"], true)) { + --$lineEnd; + } + + return $this->range($lineStart, $lineEnd); + } + + /** + * The name of an attribute of the element, "itemtype" in itemtype="…". + */ + public function attributeName(\Dom\Element $element, string $attribute): ?Range + { + $location = $this->tagOf($element)['attributes'][$attribute] ?? null; + + return null === $location ? null : $this->range($location['nameStart'], $location['nameEnd']); + } + + /** + * The value of an attribute of the element, without its quotes and without + * the whitespace around it, as the extractors trim it. + */ + public function attributeValue(\Dom\Element $element, string $attribute): ?Range + { + $location = $this->tagOf($element)['attributes'][$attribute] ?? null; + + if (null === $location || null === $location['valueStart'] || null === $location['valueEnd']) { + return null; + } + + return $this->trimmedRange($location['valueStart'], $location['valueEnd']); + } + + /** + * The $index-th whitespace-separated token of an attribute value, counted + * from 0: one name of itemprop="name alternateName", one type of typeof. + */ + public function attributeToken(\Dom\Element $element, string $attribute, int $index): ?Range + { + $location = $this->tagOf($element)['attributes'][$attribute] ?? null; + + if (null === $location || null === $location['valueStart'] || null === $location['valueEnd']) { + return null; + } + + $rawValue = substr($this->body, $location['valueStart'], $location['valueEnd'] - $location['valueStart']); + + if (!preg_match_all('/[^' . preg_quote(self::WHITESPACE, '/') . ']+/', $rawValue, $matches, \PREG_OFFSET_CAPTURE) || !isset($matches[0][$index])) { + return null; + } + + [$token, $offset] = $matches[0][$index]; + $start = $location['valueStart'] + $offset; + + return $this->range($start, $start + \strlen($token)); + } + + /** + * The text the element holds, from its first to its last non-whitespace + * character: "2010" in 2010 . + * + * The element must have an end tag, and what lies between its tags must + * read as its text content: when the HTML5 parser closed it somewhere else + * (a

without

), its text is not located. + */ + public function text(\Dom\Element $element): ?Range + { + $tagIndex = $this->tagIndexOf($element); + $closeStart = null === $tagIndex ? null : $this->closeStarts[$tagIndex] ?? null; + + if (null === $tagIndex || null === $closeStart || null === $this->tags) { + return null; + } + + $contentStart = $this->tags[$tagIndex]['end']; + $innerSource = substr($this->body, $contentStart, $closeStart - $contentStart); + + if (self::normalizeText(html_entity_decode(strip_tags($innerSource), \ENT_QUOTES | \ENT_HTML5, 'UTF-8')) !== self::normalizeText($element->textContent ?? '')) { + return null; + } + + return $this->trimmedRange($contentStart, $closeStart); + } + + private static function normalizeText(string $text): string + { + return trim((string) preg_replace('/\s+/u', ' ', $text)); + } + + /** + * @return array{name: string, start: int, end: int, attributes: array}|null + */ + private function tagOf(\Dom\Element $element): ?array + { + $tagIndex = $this->tagIndexOf($element); + + return null === $tagIndex ? null : $this->tags[$tagIndex] ?? null; + } + + private function tagIndexOf(\Dom\Element $element): ?int + { + $this->pairElements(); + + if (null === $this->elementTags || !$this->elementTags->offsetExists($element)) { + return null; + } + + return $this->elementTags[$element]; + } + + private function trimmedRange(int $start, int $end): ?Range + { + $value = substr($this->body, $start, $end - $start); + $leading = \strlen($value) - \strlen(ltrim($value, self::TRIMMED_CHARACTERS)); + $trimmedLength = \strlen(trim($value, self::TRIMMED_CHARACTERS)); + + if (0 === $trimmedLength) { + return null; + } + + return $this->range($start + $leading, $start + $leading + $trimmedLength); + } + + private function range(int $startOffset, int $endOffset): Range + { + return new Range($this->position($startOffset), $this->position($endOffset)); + } + + private function position(int $offset): Position + { + $lineIndex = $this->lineIndexOf($offset); + + return new Position($lineIndex + 1, $this->columnOf($lineIndex, $offset)); + } + + /** + * The column of an offset, counted from a checkpoint of its line rather + * than from the line start: on a minified page, the whole document is one + * line, and counting from its start for every position would be quadratic. + */ + private function columnOf(int $lineIndex, int $offset): int + { + $checkpoints = $this->columnCheckpoints[$lineIndex] ?? [[$this->lineStarts[$lineIndex], 1]]; + $last = \count($checkpoints) - 1; + + // The last checkpoint at or before the offset. + $index = $last; + + if ($checkpoints[$last][0] > $offset) { + $low = 0; + $high = $last; + + while ($low < $high) { + $middle = intdiv($low + $high + 1, 2); + + if ($checkpoints[$middle][0] <= $offset) { + $low = $middle; + } else { + $high = $middle - 1; + } + } + + $index = $low; + } + + [$from, $column] = $checkpoints[$index]; + + // Past the last checkpoint, new ones are laid every so often, on the + // first byte of a character so that no character is split in two. + while ($index === $last && $offset - $from > self::COLUMN_CHECKPOINT_SPACING) { + $next = $from + self::COLUMN_CHECKPOINT_SPACING; + + while ($next < $offset && 0x80 === (\ord($this->body[$next]) & 0xC0)) { + ++$next; + } + + $column += Utf16::length(substr($this->body, $from, $next - $from)); + $from = $next; + $checkpoints[] = [$from, $column]; + $index = ++$last; + } + + $this->columnCheckpoints[$lineIndex] = $checkpoints; + + return $column + Utf16::length(substr($this->body, $from, $offset - $from)); + } + + /** + * The line holding the offset, counted from 0. + */ + private function lineIndexOf(int $offset): int + { + // Offsets are mostly asked for in document order: walking forward from + // the line found last is cheaper than a search over the whole page. + $line = $this->lineCursor; + + if ($this->lineStarts[$line] <= $offset) { + $steps = 0; + + while (isset($this->lineStarts[$line + 1]) && $this->lineStarts[$line + 1] <= $offset && ++$steps < 64) { + ++$line; + } + + if (!isset($this->lineStarts[$line + 1]) || $this->lineStarts[$line + 1] > $offset) { + return $this->lineCursor = $line; + } + } + + // The last line starting at or before the offset. + $low = 0; + $high = \count($this->lineStarts) - 1; + + while ($low < $high) { + $middle = intdiv($low + $high + 1, 2); + + if ($this->lineStarts[$middle] <= $offset) { + $low = $middle; + } else { + $high = $middle - 1; + } + } + + return $this->lineCursor = $low; + } + + private function pairElements(): void + { + if (null !== $this->elementTags) { + return; + } + + $this->tokenize(); + $this->elementTags = new \SplObjectStorage(); + + $tagsBySignature = []; + + foreach ($this->tags ?? [] as $index => $tag) { + $signature = $this->sourceSignature($tag); + + if (null !== $signature) { + $tagsBySignature[$signature][] = $index; + } + } + + $ranks = []; + + // In document order; walking the elements is an order of magnitude + // faster than an XPath query testing each attribute. + foreach ($this->document->getElementsByTagName('*') as $element) { + $signature = $element->hasAttributes() ? $this->domSignature($element) : null; + + if (null === $signature) { + continue; + } + + $rank = $ranks[$signature] = ($ranks[$signature] ?? -1) + 1; + + if (isset($tagsBySignature[$signature][$rank])) { + $this->elementTags[$element] = $tagsBySignature[$signature][$rank]; + } + } + } + + /** + * @param array{name: string, start: int, end: int, attributes: array} $tag + */ + private function sourceSignature(array $tag): ?string + { + $attributes = []; + + foreach (self::SIGNATURE_ATTRIBUTES as $attribute) { + $location = $tag['attributes'][$attribute] ?? null; + + if (null === $location) { + continue; + } + + $value = null === $location['valueStart'] || null === $location['valueEnd'] + ? '' + : html_entity_decode(substr($this->body, $location['valueStart'], $location['valueEnd'] - $location['valueStart']), \ENT_QUOTES | \ENT_HTML5, 'UTF-8'); + + $attributes[] = $attribute . '=' . preg_replace('/\r\n?/', "\n", $value); + } + + if ([] === $attributes) { + return null; + } + + return $this->lineIndexOf($tag['start']) . "\0" . $tag['name'] . "\0" . implode("\0", $attributes); + } + + /** + * Null for an element without any structured data attribute, which is + * never paired. + */ + private function domSignature(\Dom\Element $element): ?string + { + $attributes = []; + + foreach (self::SIGNATURE_ATTRIBUTES as $attribute) { + if ($element->hasAttribute($attribute)) { + $attributes[] = $attribute . '=' . $element->getAttribute($attribute); + } + } + + if ([] === $attributes) { + return null; + } + + return $element->getLineNo() . "\0" . strtolower($element->localName) . "\0" . implode("\0", $attributes); + } + + private function tokenize(): void + { + if (null !== $this->tags) { + return; + } + + $body = $this->body; + $length = \strlen($body); + + // Line breaks are "\r\n", "\r" or "\n", as the HTML parser and the + // editors read them. + $this->lineStarts = [0]; + + if (preg_match_all('/\r\n|\r|\n/', $body, $matches, \PREG_OFFSET_CAPTURE)) { + foreach ($matches[0] as [$lineBreak, $offset]) { + $this->lineStarts[] = $offset + \strlen($lineBreak); + } + } + + $tags = []; + // Indexes of the start tags still waiting for their end tag, by name. + $openTags = []; + // The content of a