From 05e8b8a8d87d5d3b3b0825da9aab44196aa3d645 Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sat, 21 Nov 2026 11:38:05 +0100 Subject: [PATCH 01/10] Resolve relative IRIs as RFC 3986 section 5.2 says, through league/uri-interfaces --- CHANGELOG.md | 11 ++ composer.json | 2 +- src/JsonLd/Algorithms/Http/IriResolver.php | 25 ++++- tests/Algorithms/Http/IriResolverTest.php | 121 +++++++++++++++++++++ 4 files changed, 155 insertions(+), 4 deletions(-) create mode 100644 tests/Algorithms/Http/IriResolverTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 963a805fb..d3802debd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [Unreleased] + +### Changed + +- Relative IRIs are resolved as RFC 3986 section 5.2 describes it and nothing more, as + JSON-LD asks: non-ASCII characters are no longer percent-encoded, the host keeps its + case, and a reference without a path keeps the dot segments of the base (`?y` against + `http://a/b/./c` is `http://a/b/./c?y`). The resolution is the one of + `League\Uri\UriString`, so the library now requires `league/uri-interfaces ^7.10` + instead of `league/uri`. + ## [0.3.0] - 2026-11-13 ### Added diff --git a/composer.json b/composer.json index 710640e2d..58cf2883e 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,7 @@ "ext-dom": "*", "ext-json": "*", "ext-libxml": "*", - "league/uri": "^7.8", + "league/uri-interfaces": "^7.10", "psr/log": "^1|^2|^3", "salsify/json-streaming-parser": "^8.3", "symfony/http-client-contracts": "^3.0" diff --git a/src/JsonLd/Algorithms/Http/IriResolver.php b/src/JsonLd/Algorithms/Http/IriResolver.php index afffe9a01..1dccd88a1 100644 --- a/src/JsonLd/Algorithms/Http/IriResolver.php +++ b/src/JsonLd/Algorithms/Http/IriResolver.php @@ -14,7 +14,8 @@ use JoliCode\StructuredData\JsonLd\Algorithms\ContextProcessing\Context; use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\Keyword; use JoliCode\StructuredData\JsonLd\Algorithms\TermDefinition\TermDefinitionCreator; -use League\Uri\Uri; +use League\Uri\Contracts\UriException; +use League\Uri\UriString; class IriResolver { @@ -169,7 +170,7 @@ public static function isRelativeIri(mixed $iri): bool /** * Permissive absolute IRI/URI shape check. * This is because JSON-LD uses absolute identifiers (URN scheme) that are not fetchable over HTTP. - * Use League\Uri when strict web URL validation is required. + * Use league/uri when strict web URL validation is required. */ public static function isAbsoluteIri(mixed $iri): bool { @@ -213,7 +214,25 @@ public static function resolveIri(?string $base, string $iri): string return $iri; } - return (string) Uri::parse($iri, $base); + // A reference without a path keeps the path of the base as it is, dot + // segments included (RFC 3986 section 5.2.2), where league/uri removes + // them: this one case is resolved here. + if ('' === $iri || '#' === $iri[0]) { + return explode('#', $base, 2)[0] . $iri; + } + + if ('?' === $iri[0]) { + return explode('?', explode('#', $base, 2)[0], 2)[0] . $iri; + } + + // The resolution of RFC 3986 section 5.2 and nothing more, as JSON-LD + // asks: no normalization, no percent-encoding. A reference that cannot + // be parsed is handed back as it is, so that it stays not well-formed. + try { + return UriString::resolve($iri, $base); + } catch (UriException) { + return $iri; + } } public static function isKeywordLikeString(string $value): bool diff --git a/tests/Algorithms/Http/IriResolverTest.php b/tests/Algorithms/Http/IriResolverTest.php new file mode 100644 index 000000000..d2e007616 --- /dev/null +++ b/tests/Algorithms/Http/IriResolverTest.php @@ -0,0 +1,121 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Http; + +use JoliCode\StructuredData\JsonLd\Algorithms\Http\IriResolver; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * JSON-LD resolves a relative IRI with the algorithm of RFC 3986 section 5.2 + * and nothing more: no normalization, no percent-encoding. + */ +#[Group('algorithms')] +class IriResolverTest extends TestCase +{ + private const BASE = 'http://a/b/c/d;p?q'; + + #[DataProvider('provideRfc3986Examples')] + public function testTheExamplesOfRfc3986(string $reference, string $expected): void + { + $this->assertSame($expected, IriResolver::resolveIri(self::BASE, $reference)); + } + + /** + * RFC 3986 sections 5.4.1 (normal examples) and 5.4.2 (abnormal examples). + * + * @return iterable + */ + public static function provideRfc3986Examples(): iterable + { + $examples = [ + 'g:h' => 'g:h', + 'g' => 'http://a/b/c/g', + './g' => 'http://a/b/c/g', + 'g/' => 'http://a/b/c/g/', + '/g' => 'http://a/g', + '//g' => 'http://g', + '?y' => 'http://a/b/c/d;p?y', + 'g?y' => 'http://a/b/c/g?y', + '#s' => 'http://a/b/c/d;p?q#s', + 'g#s' => 'http://a/b/c/g#s', + 'g?y#s' => 'http://a/b/c/g?y#s', + ';x' => 'http://a/b/c/;x', + 'g;x' => 'http://a/b/c/g;x', + 'g;x?y#s' => 'http://a/b/c/g;x?y#s', + '' => 'http://a/b/c/d;p?q', + '.' => 'http://a/b/c/', + './' => 'http://a/b/c/', + '..' => 'http://a/b/', + '../' => 'http://a/b/', + '../g' => 'http://a/b/g', + '../..' => 'http://a/', + '../../' => 'http://a/', + '../../g' => 'http://a/g', + '../../../g' => 'http://a/g', + '../../../../g' => 'http://a/g', + '/./g' => 'http://a/g', + '/../g' => 'http://a/g', + 'g.' => 'http://a/b/c/g.', + '.g' => 'http://a/b/c/.g', + 'g..' => 'http://a/b/c/g..', + '..g' => 'http://a/b/c/..g', + './../g' => 'http://a/b/g', + './g/.' => 'http://a/b/c/g/', + 'g/./h' => 'http://a/b/c/g/h', + 'g/../h' => 'http://a/b/c/h', + 'g;x=1/./y' => 'http://a/b/c/g;x=1/y', + 'g;x=1/../y' => 'http://a/b/c/y', + 'g?y/./x' => 'http://a/b/c/g?y/./x', + 'g?y/../x' => 'http://a/b/c/g?y/../x', + 'g#s/./x' => 'http://a/b/c/g#s/./x', + 'g#s/../x' => 'http://a/b/c/g#s/../x', + 'http:g' => 'http:g', + ]; + + foreach ($examples as $reference => $expected) { + yield \sprintf('"%s"', $reference) => [(string) $reference, $expected]; + } + } + + #[DataProvider('provideReferences')] + public function testNothingIsNormalized(?string $base, string $reference, string $expected): void + { + $this->assertSame($expected, IriResolver::resolveIri($base, $reference)); + } + + /** + * @return iterable + */ + public static function provideReferences(): iterable + { + yield 'a query keeps the dot segments of the base' => ['http://a/bb/ccc/./d;p?q', '?y', 'http://a/bb/ccc/./d;p?y']; + yield 'a fragment keeps the dot segments of the base' => ['http://a/bb/ccc/../d;p?q', '#s', 'http://a/bb/ccc/../d;p?q#s']; + yield 'an empty reference keeps the dot segments of the base' => ['http://a/bb/ccc/../d;p?q#f', '', 'http://a/bb/ccc/../d;p?q']; + yield 'a fragment replaces the fragment of the base' => ['http://a/b?q#old', '#new', 'http://a/b?q#new']; + yield 'a query replaces the query and the fragment of the base' => ['http://a/b?old#f', '?new', 'http://a/b?new']; + yield 'a path merges with a base holding dot segments' => ['http://a/bb/ccc/../d;p?q', '../../', 'http://a/']; + yield 'the root keeps its slash' => ['http://a/b', '..', 'http://a/']; + yield 'a base without a path' => ['http://a', 'g', 'http://a/g']; + yield 'a file base' => ['file:///a/bb/ccc/d;p?q', 'g?y', 'file:///a/bb/ccc/g?y']; + yield 'characters of an IRI are not percent-encoded' => ['http://example.com/', 'é/ü?ñ#ø', 'http://example.com/é/ü?ñ#ø']; + yield 'the host keeps its case' => ['http://EXAMPLE.com/A/%7euser', 'x', 'http://EXAMPLE.com/A/x']; + yield 'percent-encoded characters are left alone' => ['http://example.com/', '%7Euser/%c3%a9', 'http://example.com/%7Euser/%c3%a9']; + yield 'an absolute IRI is not touched' => ['http://example.com/', 'http://other.example/a/../b', 'http://other.example/a/../b']; + yield 'a blank node identifier is not touched' => ['http://example.com/', '_:b0', '_:b0']; + yield 'no base' => [null, 'relative', 'relative']; + yield 'an empty base' => ['', 'relative', 'relative']; + yield 'a reference that is not an IRI stays as it is' => ['http://example.com/', 'a b', 'a b']; + yield 'characters an IRI may not hold are not percent-encoded either' => ['http://example.com/', 'a/', 'http://example.com/a/']; + } +} From 07e7adb9e63c224c020db320a25762045f6565fd Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sat, 21 Nov 2026 11:38:06 +0100 Subject: [PATCH 02/10] Keep a plain string next to a language-tagged string of the same text in node maps --- CHANGELOG.md | 5 +++++ src/JsonLd/Algorithms/Services/DataStructureComparator.php | 6 ++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3802debd..de46b9e7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,11 @@ `League\Uri\UriString`, so the library now requires `league/uri-interfaces ^7.10` instead of `league/uri`. +### Fixed + +- Flattening and framing merged a plain string into a language-tagged string holding the + same text when both were values of the same property: only one of the two was kept. + ## [0.3.0] - 2026-11-13 ### Added diff --git a/src/JsonLd/Algorithms/Services/DataStructureComparator.php b/src/JsonLd/Algorithms/Services/DataStructureComparator.php index c536d552e..9245b1fc6 100644 --- a/src/JsonLd/Algorithms/Services/DataStructureComparator.php +++ b/src/JsonLd/Algorithms/Services/DataStructureComparator.php @@ -25,7 +25,9 @@ class DataStructureComparator public static function objectAlreadyInArray(\stdClass $object, array $array): bool { foreach ($array as $arrayObject) { - if ($arrayObject instanceof \stdClass && self::objectsHaveSameProperties($object, $arrayObject)) { + // Both ways: a value object is not the language-tagged one that + // merely holds the same "@value". + if ($arrayObject instanceof \stdClass && self::objectsHaveSameProperties($object, $arrayObject) && self::objectsHaveSameProperties($arrayObject, $object)) { return true; } } @@ -49,7 +51,7 @@ public static function objectsHaveSameProperties(object $object1, object $object } if (\is_object($value)) { - if (!self::objectsHaveSameProperties($value, $object2->$property)) { + if (!\is_object($object2->$property) || !self::objectsHaveSameProperties($value, $object2->$property)) { return false; } From a2ce467414c372ee752db94b228b42b58f74ad8d Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sat, 21 Nov 2026 11:38:06 +0100 Subject: [PATCH 03/10] Name the invalid reverse property value error as the specification does --- CHANGELOG.md | 2 ++ src/JsonLd/Algorithms/Expand/Expander.php | 2 +- tests/Algorithms/ExpanderTest.php | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index de46b9e7c..dc3af4ce7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ ### Fixed +- Expansion reported `invalid @reverse property value` where the specification names the + error `invalid reverse property value` (W3C test `expand#ter34`). - Flattening and framing merged a plain string into a language-tagged string holding the same text when both were values of the same property: only one of the two was kept. diff --git a/src/JsonLd/Algorithms/Expand/Expander.php b/src/JsonLd/Algorithms/Expand/Expander.php index 7954eff71..7db602f8a 100644 --- a/src/JsonLd/Algorithms/Expand/Expander.php +++ b/src/JsonLd/Algorithms/Expand/Expander.php @@ -811,7 +811,7 @@ private function processReverseKeyword( foreach ((array) $items as $item) { // 13.4.13.4.2.1.1 if (ExpandedObjectShape::isValueObject($item) || ExpandedObjectShape::isListObject($item)) { - throw new ExpansionException('invalid @reverse property value'); + throw new ExpansionException('invalid reverse property value'); } // 13.4.13.4.2.1.2 diff --git a/tests/Algorithms/ExpanderTest.php b/tests/Algorithms/ExpanderTest.php index 7b62b402a..6664cbf0d 100644 --- a/tests/Algorithms/ExpanderTest.php +++ b/tests/Algorithms/ExpanderTest.php @@ -98,7 +98,7 @@ protected static function getExpectedErrorMessage(string $filename): string 'er31-in.jsonld' => 'invalid @index value', 'er32-in.jsonld' => 'list of lists', 'er33-in.jsonld' => 'invalid @reverse value', - 'er34-in.jsonld' => 'invalid @reverse property value', + 'er34-in.jsonld' => 'invalid reverse property value', 'er35-in.jsonld' => 'invalid language map value', 'er36-in.jsonld' => 'invalid reverse property value', 'er37-in.jsonld' => 'invalid value object', From 49a176d54f5537fe6e3341d9cb2b80723075cee7 Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sat, 21 Nov 2026 11:38:07 +0100 Subject: [PATCH 04/10] Add the JSON-LD 1.1 toRdf and fromRdf algorithms, passing the official W3C test suites --- .castor/earl.php | 30 +- .castor/json-ld.php | 53 ++ .castor/qa.php | 16 + CHANGELOG.md | 12 + CONTRIBUTING.md | 5 + README.md | 3 +- docs/json-ld.md | 69 ++- docs/remote-contexts.md | 2 +- src/JsonLd/Algorithms.php | 16 + .../Algorithms/JsonLd/ProcessorOptions.php | 11 +- src/JsonLd/Algorithms/Rdf/BlankNode.php | 23 + .../Algorithms/Rdf/CanonicalLexicalForm.php | 86 ++++ .../Algorithms/Rdf/FromRdfConverter.php | 464 ++++++++++++++++++ src/JsonLd/Algorithms/Rdf/Iri.php | 23 + .../Algorithms/Rdf/JsonCanonicalizer.php | 140 ++++++ src/JsonLd/Algorithms/Rdf/Literal.php | 26 + src/JsonLd/Algorithms/Rdf/NQuadsParser.php | 121 +++++ .../Algorithms/Rdf/NQuadsSerializer.php | 68 +++ src/JsonLd/Algorithms/Rdf/Quad.php | 27 + src/JsonLd/Algorithms/Rdf/RdfDataset.php | 63 +++ src/JsonLd/Algorithms/Rdf/RdfVocabulary.php | 41 ++ src/JsonLd/Algorithms/Rdf/ToRdfConverter.php | 353 +++++++++++++ src/JsonLd/Algorithms/Rdf/WellFormedness.php | 38 ++ tests/Algorithms/FromRdfTest.php | 63 +++ tests/Algorithms/Rdf/ComparatorTest.php | 132 +++++ tests/Algorithms/Rdf/ConvertersTest.php | 171 +++++++ tests/Algorithms/Rdf/JsonLdComparator.php | 79 +++ tests/Algorithms/Rdf/LexicalFormTest.php | 131 +++++ tests/Algorithms/Rdf/ManifestTestProvider.php | 126 +++++ tests/Algorithms/Rdf/NQuadsTest.php | 133 +++++ .../Algorithms/Rdf/RdfDatasetIsomorphism.php | 235 +++++++++ .../Rdf/W3cFixtureDocumentLoader.php | 51 ++ tests/Algorithms/ToRdfTest.php | 73 +++ 33 files changed, 2870 insertions(+), 14 deletions(-) create mode 100644 src/JsonLd/Algorithms/Rdf/BlankNode.php create mode 100644 src/JsonLd/Algorithms/Rdf/CanonicalLexicalForm.php create mode 100644 src/JsonLd/Algorithms/Rdf/FromRdfConverter.php create mode 100644 src/JsonLd/Algorithms/Rdf/Iri.php create mode 100644 src/JsonLd/Algorithms/Rdf/JsonCanonicalizer.php create mode 100644 src/JsonLd/Algorithms/Rdf/Literal.php create mode 100644 src/JsonLd/Algorithms/Rdf/NQuadsParser.php create mode 100644 src/JsonLd/Algorithms/Rdf/NQuadsSerializer.php create mode 100644 src/JsonLd/Algorithms/Rdf/Quad.php create mode 100644 src/JsonLd/Algorithms/Rdf/RdfDataset.php create mode 100644 src/JsonLd/Algorithms/Rdf/RdfVocabulary.php create mode 100644 src/JsonLd/Algorithms/Rdf/ToRdfConverter.php create mode 100644 src/JsonLd/Algorithms/Rdf/WellFormedness.php create mode 100644 tests/Algorithms/FromRdfTest.php create mode 100644 tests/Algorithms/Rdf/ComparatorTest.php create mode 100644 tests/Algorithms/Rdf/ConvertersTest.php create mode 100644 tests/Algorithms/Rdf/JsonLdComparator.php create mode 100644 tests/Algorithms/Rdf/LexicalFormTest.php create mode 100644 tests/Algorithms/Rdf/ManifestTestProvider.php create mode 100644 tests/Algorithms/Rdf/NQuadsTest.php create mode 100644 tests/Algorithms/Rdf/RdfDatasetIsomorphism.php create mode 100644 tests/Algorithms/Rdf/W3cFixtureDocumentLoader.php create mode 100644 tests/Algorithms/ToRdfTest.php diff --git a/.castor/earl.php b/.castor/earl.php index 35b6be83b..93a3184fd 100644 --- a/.castor/earl.php +++ b/.castor/earl.php @@ -38,7 +38,10 @@ * order, so the cache directory constants of qa.php are not defined yet when this * file is parsed. * - * @return array + * The RDF suites are driven by their manifest: their data sets are named after + * the fragment of the test IRI rather than after a fixture file ("byId"). + * + * @return array */ function earlSuites(): array { @@ -63,6 +66,18 @@ function earlSuites(): array 'manifest' => CACHE_DIR_W3C_FRAMING_TEST_SUITE . '/tests/frame-manifest.jsonld', 'iri' => 'https://w3c.github.io/json-ld-framing/tests/frame-manifest', ], + 'ToRdfTest' => [ + 'name' => 'toRdf', + 'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/toRdf-manifest.jsonld', + 'iri' => 'https://w3c.github.io/json-ld-api/tests/toRdf-manifest', + 'byId' => true, + ], + 'FromRdfTest' => [ + 'name' => 'fromRdf', + 'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/fromRdf-manifest.jsonld', + 'iri' => 'https://w3c.github.io/json-ld-api/tests/fromRdf-manifest', + 'byId' => true, + ], ]; } @@ -126,7 +141,7 @@ function earl( $results = $outcomes[$testClass] ?? []; $summary[$suite['name']] = ['passed' => 0, 'failed' => 0, 'inapplicable' => 0, 'untested' => 0]; - foreach (earlManifestEntries($suite['manifest']) as $entry) { + foreach (earlManifestEntries($suite['manifest'], $suite['byId'] ?? false) as $entry) { // A test that was not run is either out of scope (it only applies to // JSON-LD 1.0 processors) or genuinely untested: the distinction matters // in the consolidated report. @@ -201,10 +216,11 @@ function earlOutcomesFromJunit(string $junitFile): array * The data set name follows the convention of AbstractJsonLdTestCase: the expected * output file with "-out" replaced by "-in" (several manifest entries share an * input file but not an expected output), or the input file for a negative test. + * The suites driven by their manifest name it after the test fragment instead. * * @return list */ -function earlManifestEntries(string $manifestFile): array +function earlManifestEntries(string $manifestFile, bool $byId = false): array { $content = file_get_contents($manifestFile); @@ -229,9 +245,11 @@ function earlManifestEntries(string $manifestFile): array $entries[] = [ 'id' => $test['@id'], - 'test' => \is_string($test['expect'] ?? null) - ? str_replace('-out', '-in', basename($test['expect'])) - : basename($test['input']), + 'test' => match (true) { + $byId => $test['@id'], + \is_string($test['expect'] ?? null) => str_replace('-out', '-in', basename($test['expect'])), + default => basename($test['input']), + }, 'jsonLd10Only' => 'json-ld-1.0' === ($option['specVersion'] ?? null), ]; } diff --git a/.castor/json-ld.php b/.castor/json-ld.php index f5c705a6d..0fda7c10a 100644 --- a/.castor/json-ld.php +++ b/.castor/json-ld.php @@ -12,6 +12,7 @@ namespace json_ld; use Castor\Attribute\AsArgument; +use Castor\Attribute\AsOption; use Castor\Attribute\AsTask; use function Castor\io; @@ -20,6 +21,11 @@ use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; use JoliCode\StructuredData\JsonLd\Algorithms\Flatten\Flattener; use JoliCode\StructuredData\JsonLd\Algorithms\Frame\Framer; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use Symfony\Component\Console\Input\InputOption; #[AsTask(description: 'Applies the expansion algorithm to a JSON-LD document')] function expand( @@ -118,3 +124,50 @@ function frameJsonLd( io()->writeln($result); } + +#[AsTask(name: 'to-rdf', description: 'Deserializes a JSON-LD document to RDF, written as N-Quads')] +function toRdf( + #[AsArgument(name: 'file', description: 'The JSON-LD file to deserialize')] + string $fileName, + #[AsOption(name: 'rdf-direction', mode: InputOption::VALUE_REQUIRED, description: 'How the base direction of a string is written: "i18n-datatype" or "compound-literal" (dropped by default)')] + ?string $rdfDirection = null, + #[AsOption(name: 'generalized', description: 'Keep the triples whose predicate is a blank node')] + bool $generalized = false, +): void { + $file = file_get_contents($fileName); + + if (false === $file) { + io()->error(\sprintf('The file "%s" could not be read.', $fileName)); + + return; + } + + $converter = new ToRdfConverter(); + $dataset = $converter->toRdf($file, new ProcessorOptions(produceGeneralizedRdf: $generalized, rdfDirection: $rdfDirection)); + + io()->write(NQuadsSerializer::serialize($dataset)); +} + +#[AsTask(name: 'from-rdf', description: 'Serializes an RDF dataset, read as N-Quads, as a JSON-LD document')] +function fromRdf( + #[AsArgument(name: 'file', description: 'The N-Quads file to serialize')] + string $fileName, + #[AsOption(name: 'rdf-direction', mode: InputOption::VALUE_REQUIRED, description: 'How the base direction of a string is read back: "i18n-datatype" or "compound-literal"')] + ?string $rdfDirection = null, + #[AsOption(name: 'native-types', description: 'Turn xsd:boolean, xsd:integer and xsd:double literals into JSON booleans and numbers')] + bool $nativeTypes = false, + #[AsOption(name: 'rdf-type', description: 'Keep rdf:type as an ordinary property instead of "@type"')] + bool $rdfType = false, +): void { + $file = file_get_contents($fileName); + + if (false === $file) { + io()->error(\sprintf('The file "%s" could not be read.', $fileName)); + + return; + } + + $converter = new FromRdfConverter(); + + io()->writeln($converter->fromRdf($file, new ProcessorOptions(rdfDirection: $rdfDirection, useNativeTypes: $nativeTypes, useRdfType: $rdfType, ordered: true))); +} diff --git a/.castor/qa.php b/.castor/qa.php index 04a60575d..061c4db0b 100644 --- a/.castor/qa.php +++ b/.castor/qa.php @@ -80,6 +80,8 @@ function suiteFixturesAreMissing(): bool return !fs()->exists(\sprintf('%s/tests/flatten/output', CACHE_DIR_W3C_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/frame/output', CACHE_DIR_W3C_FRAMING_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/expand-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) + || !fs()->exists(\sprintf('%s/tests/toRdf-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) + || !fs()->exists(\sprintf('%s/tests/fromRdf-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/frame-manifest.jsonld', CACHE_DIR_W3C_FRAMING_TEST_SUITE)); } @@ -237,6 +239,20 @@ function phpunitPrepare( } } + // The RDF suites are driven by their manifest, which names every file of a + // test: their fixtures are copied as they are upstream, N-Quads included. + foreach (Algorithms::rdfAlgorithmNames() as $algorithm) { + fs()->copy( + \sprintf('%s/json-ld-api-%s/tests/%s-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE, $ref, $algorithm), + \sprintf('%s/tests/%s-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE, $algorithm), + true, + ); + fs()->mirror( + \sprintf('%s/json-ld-api-%s/tests/%s', CACHE_DIR_W3C_TEST_SUITE, $ref, $algorithm), + \sprintf('%s/tests/%s', CACHE_DIR_W3C_TEST_SUITE, $algorithm), + ); + } + // remove the zip archive and all the files fs()->remove($zipFileName); fs()->remove(\sprintf('%s/json-ld-api-%s', CACHE_DIR_W3C_TEST_SUITE, $ref)); diff --git a/CHANGELOG.md b/CHANGELOG.md index dc3af4ce7..9cfa5eb9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,20 @@ ## [Unreleased] +### Added + +- The RDF serialization and deserialization algorithms of JSON-LD 1.1: `ToRdfConverter` + turns a JSON-LD document into an `RdfDataset`, `FromRdfConverter` turns a dataset or + N-Quads into an expanded document, and `NQuadsParser` / `NQuadsSerializer` read and + write N-Quads. Generalized RDF, both `rdfDirection` forms, native types and JSON + literals (canonicalized with RFC 8785) are supported. The official `toRdf` and `fromRdf` + test suites pass, and are part of `castor qa:earl`. From the command line: + `castor json-ld:to-rdf` and `castor json-ld:from-rdf`. See [docs/json-ld.md](docs/json-ld.md#rdf). + ### Changed +- `ProcessorOptions::$produceGeneralizedRdf` now defaults to `false`, as the specification + says. Nothing read the option before. - Relative IRIs are resolved as RFC 3986 section 5.2 describes it and nothing more, as JSON-LD asks: non-ASCII characters are no longer percent-encoded, the host keeps its case, and a reference without a path keeps the dot segments of the base (`?y` against diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d0267c10a..7fbc64c6c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -127,6 +127,11 @@ Command | Description `castor qa:phpunit:coverage` | Runs PHPUnit with code coverage (requires the pcov or xdebug extension) `castor qa:infection` | Runs Infection mutation testing on the validator and mapper layers (requires the pcov or xdebug extension) +The W3C suites each have their PHPUnit group: `expand`, `compact`, `flatten`, `frame`, `toRdf` and `fromRdf` +(`castor qa:phpunit:run --group toRdf`). The first four list their fixture files and set the options of each +test in PHP; the two RDF suites are driven by their manifest (`tests/Algorithms/Rdf/ManifestTestProvider.php`) +and read the remote contexts from the downloaded copy, so they run offline. + The W3C test suite is pinned to a known-good upstream commit (see `W3C_TEST_SUITE_REF` in `.castor/qa.php`). To re-download it, or to test against the upstream main branch: diff --git a/README.md b/README.md index 9d0766422..13e808729 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,8 @@ nodes, the parsed tree, and the CLI. ### Use the JSON-LD algorithms Expansion, compaction, flattening and framing are available as `Expander`, `Compactor`, -`Flattener` and `Framer`: +`Flattener` and `Framer`, and the conversion to and from RDF as `ToRdfConverter` and +`FromRdfConverter`: ```php use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; diff --git a/docs/json-ld.md b/docs/json-ld.md index 64569ec3d..85f339e42 100644 --- a/docs/json-ld.md +++ b/docs/json-ld.md @@ -8,8 +8,8 @@ The library implements the W3C - [Expansion](https://www.w3.org/TR/json-ld11-api/#expansion-algorithm): `JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander` - [Flattening](https://www.w3.org/TR/json-ld11-api/#flattening-algorithm): `JoliCode\StructuredData\JsonLd\Algorithms\Flatten\Flattener` - [Framing](https://www.w3.org/TR/json-ld11-framing/#framing-algorithm): `JoliCode\StructuredData\JsonLd\Algorithms\Frame\Framer` - -Serialization to and from RDF (`toRdf` / `fromRdf`) is out of scope and not implemented. +- [Deserialization to RDF](https://www.w3.org/TR/json-ld11-api/#deserialize-json-ld-to-rdf-algorithm) (`toRdf`): `JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter` +- [Serialization from RDF](https://www.w3.org/TR/json-ld11-api/#serialize-rdf-as-json-ld-algorithm) (`fromRdf`): `JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter` ## Usage @@ -67,6 +67,56 @@ $result = $expander->expand($jsonString, options: $options, encodeResult: false) Remote `@context` URLs other than schema.org are refused by default: see [Loading remote contexts](remote-contexts.md). +## RDF + +`ToRdfConverter` turns a JSON-LD document into an `RdfDataset`, a set of `Quad` objects +whose terms are `Iri`, `BlankNode` and `Literal` values. `NQuadsSerializer` writes a dataset +as [N-Quads](https://www.w3.org/TR/n-quads/): + +```php +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; + +$dataset = (new ToRdfConverter())->toRdf('{ + "@context": "https://schema.org", + "@id": "https://example.com/john", + "@type": "Person", + "name": "John Doe" +}'); + +echo NQuadsSerializer::serialize($dataset); +``` + +```nquads + . + "John Doe" . +``` + +`FromRdfConverter` goes the other way. It takes an `RdfDataset` or an N-Quads string +(`NQuadsParser` reads one into a dataset) and returns the expanded JSON-LD document, as a +JSON string unless `encodeResult` is `false`: + +```php +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; + +$document = (new FromRdfConverter())->fromRdf($nQuads, new ProcessorOptions(useNativeTypes: true)); +``` + +Four options of `ProcessorOptions` only concern these two algorithms: + +| Option | Default | Effect | +| --- | --- | --- | +| `produceGeneralizedRdf` | `false` | `toRdf` keeps the triples whose predicate is a blank node, which RDF does not allow. | +| `rdfDirection` | `null` | How the base direction of a string (`@direction`) travels through RDF, which has no room for it: dropped when `null`, written in the datatype with `i18n-datatype`, in a blank node with `compound-literal`. Use the same value both ways. | +| `useNativeTypes` | `false` | `fromRdf` turns `xsd:boolean`, `xsd:integer` and `xsd:double` literals into JSON booleans and numbers. A literal JSON cannot hold (an integer larger than a PHP integer, an infinity, an invalid lexical form) keeps its string and its `@type`. | +| `useRdfType` | `false` | `fromRdf` keeps `rdf:type` as an ordinary property instead of `@type`. | + +A triple that would hold an IRI or a language tag that is not well-formed is left out of +the dataset, as the specification asks: `toRdf` does not report it. Numbers take their +canonical `xsd:integer` or `xsd:double` lexical form, and a JSON literal (`"@type": "@json"`) +is written with the [JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785). + ## Conformance Each algorithm is validated against the official W3C test suites @@ -78,15 +128,22 @@ The full suites pass. The only skipped fixtures are a handful that target JSON-L 1.0-specific behavior (declared `specVersion: json-ld-1.0` in the upstream manifest), which this library does not implement; each skip is documented in the corresponding test. -As of the pinned upstream commits, the manifests list 781 tests, and every test that +As of the pinned upstream commits, the manifests list 1307 tests, and every test that applies to a JSON-LD 1.1 processor passes: | Suite | Passed | JSON-LD 1.0 only | | --- | --- | --- | -| expand | 385 | 0 | -| compact | 244 | 2 | +| expand | 388 | 0 | +| compact | 245 | 2 | | flatten | 58 | 0 | | frame | 91 | 1 | +| toRdf | 457 | 11 | +| fromRdf | 53 | 1 | + +The `toRdf` and `fromRdf` figures include the optional features of the specification: +generalized RDF, and both `rdfDirection` forms. The `html` and `remote-doc` suites are not +run: extracting JSON-LD from HTML is the job of the [validator](validator.md), not of +these algorithms. `castor qa:earl` runs these suites and writes an [EARL](https://www.w3.org/TR/EARL10-Schema/) report in Turtle, one assertion per manifest entry, in the format the @@ -103,4 +160,6 @@ castor json-ld:expand castor json-ld:flatten castor json-ld:compact castor json-ld:frame +castor json-ld:to-rdf [--rdf-direction=i18n-datatype|compound-literal] [--generalized] +castor json-ld:from-rdf [--rdf-direction=...] [--native-types] [--rdf-type] ``` diff --git a/docs/remote-contexts.md b/docs/remote-contexts.md index 3ddd9e08a..527e00a51 100644 --- a/docs/remote-contexts.md +++ b/docs/remote-contexts.md @@ -8,7 +8,7 @@ that URL to be resolved before the document can be expanded. This library resolv files it ships with, so the most common case by far is covered without a single outbound request. -Every other remote context is **refused**. `Validator::audit()` and the four algorithms +Every other remote context is **refused**. `Validator::audit()`, the four algorithms and the deserialization to RDF issue no network request and read no file unless you say otherwise, and a refused context raises the error the specification mandates: diff --git a/src/JsonLd/Algorithms.php b/src/JsonLd/Algorithms.php index 01d70e61f..7edc79667 100644 --- a/src/JsonLd/Algorithms.php +++ b/src/JsonLd/Algorithms.php @@ -18,6 +18,8 @@ enum Algorithms: string case COMPACT = 'compact'; case EXPAND = 'expand'; case FRAME = 'frame'; + case TO_RDF = 'toRdf'; + case FROM_RDF = 'fromRdf'; /** * The list of algorithms that are part of the official test suite. @@ -34,4 +36,18 @@ public static function algorithmNames(): array self::EXPAND->value, ]; } + + /** + * The RDF algorithms of the official test suite. Their tests are driven by + * the manifests, so their fixtures keep the upstream layout. + * + * @return list + */ + public static function rdfAlgorithmNames(): array + { + return [ + self::TO_RDF->value, + self::FROM_RDF->value, + ]; + } } diff --git a/src/JsonLd/Algorithms/JsonLd/ProcessorOptions.php b/src/JsonLd/Algorithms/JsonLd/ProcessorOptions.php index df940177c..4e4ee42f5 100644 --- a/src/JsonLd/Algorithms/JsonLd/ProcessorOptions.php +++ b/src/JsonLd/Algorithms/JsonLd/ProcessorOptions.php @@ -30,7 +30,16 @@ public function __construct( public ?bool $omitGraph = null, public bool $ordered = false, public string $processingMode = Context::PROCESSING_MODE_11, - public bool $produceGeneralizedRdf = true, + /** + * Deserialization to RDF only: whether a triple whose predicate is a blank + * node is kept. Such a triple is not RDF, so it is dropped by default. + */ + public bool $produceGeneralizedRdf = false, + /** + * RDF algorithms only: how the base direction of a string travels through + * RDF, which has no room for it. Null drops it, "i18n-datatype" writes it + * in the datatype, "compound-literal" in a blank node. + */ public ?string $rdfDirection = null, public bool $useNativeTypes = false, public bool $useRdfType = false, diff --git a/src/JsonLd/Algorithms/Rdf/BlankNode.php b/src/JsonLd/Algorithms/Rdf/BlankNode.php new file mode 100644 index 000000000..cb185db16 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/BlankNode.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * A blank node, as a term of an RDF quad. The label keeps its "_:" prefix. + */ +final readonly class BlankNode +{ + public function __construct( + public string $label, + ) { + } +} diff --git a/src/JsonLd/Algorithms/Rdf/CanonicalLexicalForm.php b/src/JsonLd/Algorithms/Rdf/CanonicalLexicalForm.php new file mode 100644 index 000000000..e91cd6649 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/CanonicalLexicalForm.php @@ -0,0 +1,86 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * The canonical lexical forms a native JSON value takes once it becomes an RDF + * literal. + * + * see https://www.w3.org/TR/json-ld11-api/#data-round-tripping + */ +final class CanonicalLexicalForm +{ + public static function boolean(bool $value): string + { + return $value ? 'true' : 'false'; + } + + /** + * The canonical lexical form of an xsd:integer: no fraction, no exponent. + */ + public static function integer(int|float $value): string + { + if (\is_int($value)) { + return (string) $value; + } + + $integer = \sprintf('%.0F', $value); + + return '-0' === $integer ? '0' : $integer; + } + + /** + * The canonical lexical form of an xsd:double: one digit before the point, + * at least one after, and an exponent without sign nor leading zero. + */ + public static function double(int|float $value): string + { + $value = (float) $value; + + if (is_nan($value)) { + return 'NaN'; + } + + if (is_infinite($value)) { + return $value > 0 ? 'INF' : '-INF'; + } + + if (1 !== preg_match('/^(-?\d)\.(\d+)E([+-])(\d+)$/', \sprintf('%1.15E', $value), $matches)) { + return (string) $value; + } + + $fraction = rtrim($matches[2], '0'); + $exponent = ltrim($matches[4], '0'); + + return \sprintf( + '%s.%sE%s%s', + $matches[1], + '' === $fraction ? '0' : $fraction, + '-' === $matches[3] && '' !== $exponent ? '-' : '', + '' === $exponent ? '0' : $exponent, + ); + } + + /** + * Whether a number is written as an xsd:double rather than an xsd:integer + * when nothing says which: it has a fraction, or is too large to be read + * back as an integer. + */ + public static function isDouble(int|float $value): bool + { + if (\is_int($value)) { + return false; + } + + return !is_finite($value) || 0.0 !== fmod($value, 1.0) || abs($value) >= 1.0E21; + } +} diff --git a/src/JsonLd/Algorithms/Rdf/FromRdfConverter.php b/src/JsonLd/Algorithms/Rdf/FromRdfConverter.php new file mode 100644 index 000000000..6b3ae7397 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/FromRdfConverter.php @@ -0,0 +1,464 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\ContextProcessing\Context; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\FramingKeyword; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\Keyword; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; + +/** + * Serializes an RDF dataset as an expanded JSON-LD document. + * + * This is a PHP implementation of the Serialize RDF as JSON-LD algorithm based + * on the JSON-LD 1.1 Processing Algorithms and API W3C Recommendation published + * on July 16th, 2020. + * + * see https://www.w3.org/TR/json-ld11-api/#serialize-rdf-as-json-ld-algorithm + * + * @phpstan-type Usage array{node: \stdClass, property: string, value: \stdClass} + */ +class FromRdfConverter +{ + private readonly NQuadsParser $parser; + + public function __construct(?NQuadsParser $parser = null) + { + $this->parser = $parser ?? new NQuadsParser(); + } + + /** + * @param RdfDataset|string $dataset The dataset to serialize. A string is read as N-Quads. + * @param bool $encodeResult Whether to encode the result as a JSON string or not + * + * @return ($encodeResult is true ? string : list<\stdClass>) + */ + public function fromRdf( + RdfDataset|string $dataset, + ProcessorOptions $options = new ProcessorOptions(), + bool $encodeResult = true, + ): array|string { + ToRdfConverter::assertRdfDirection($options->rdfDirection); + + if (\is_string($dataset)) { + $dataset = $this->parser->parse($dataset); + } + + // 1 and 2 + /** @var array> $graphMap */ + $graphMap = [FramingKeyword::DEFAULT->value => []]; + // 3 + /** @var array $referencedOnce */ + $referencedOnce = []; + // 4 + /** @var array> $compoundLiteralSubjects */ + $compoundLiteralSubjects = []; + // The usages of rdf:nil, per graph: the tail of every list. + /** @var array> $nilUsages */ + $nilUsages = []; + + // 5 + foreach ($dataset->quads() as $quad) { + // 5.1 + $name = null === $quad->graph ? FramingKeyword::DEFAULT->value : self::identifier($quad->graph); + // 5.2 + $graphMap[$name] ??= []; + + // 5.4 + if (FramingKeyword::DEFAULT->value !== $name) { + $graphMap[FramingKeyword::DEFAULT->value][$name] ??= self::createNode($name); + } + + $subject = self::identifier($quad->subject); + $predicate = self::identifier($quad->predicate); + $object = $quad->object; + + // 5.7.1 and 5.7.2 + $node = $graphMap[$name][$subject] ??= self::createNode($subject); + + // 5.7.3 + if (RdfVocabulary::RDF_DIRECTION_COMPOUND_LITERAL === $options->rdfDirection && RdfVocabulary::RDF_DIRECTION === $predicate) { + $compoundLiteralSubjects[$name][$subject] = true; + } + + $objectIdentifier = null; + + if (!$object instanceof Literal) { + $objectIdentifier = self::identifier($object); + // 5.7.4 + $graphMap[$name][$objectIdentifier] ??= self::createNode($objectIdentifier); + + // 5.7.5 + if (RdfVocabulary::RDF_TYPE === $predicate && !$options->useRdfType) { + $types = $node->{Keyword::TYPE->value} ?? []; + + if (!\in_array($objectIdentifier, $types, true)) { + $types[] = $objectIdentifier; + } + + $node->{Keyword::TYPE->value} = $types; + + continue; + } + } + + // 5.7.6 + $value = $this->rdfToObject($object, $options); + + // 5.7.7 and 5.7.8 + $values = $node->{$predicate} ?? []; + $known = false; + + foreach ($values as $existingValue) { + if (serialize($existingValue) === serialize($value)) { + $value = $existingValue; + $known = true; + + break; + } + } + + if (!$known) { + $values[] = $value; + $node->{$predicate} = $values; + } + + if (null === $objectIdentifier) { + continue; + } + + $usage = ['node' => $node, 'property' => $predicate, 'value' => $value]; + + if (RdfVocabulary::RDF_NIL === $objectIdentifier) { + // 5.7.9 + $nilUsages[$name][] = $usage; + } elseif (\array_key_exists($objectIdentifier, $referencedOnce)) { + // 5.7.10 + $referencedOnce[$objectIdentifier] = false; + } elseif ($object instanceof BlankNode) { + // 5.7.11 + $referencedOnce[$objectIdentifier] = $usage; + } + } + + // 6 + foreach (array_keys($graphMap) as $name) { + $name = (string) $name; + + // 6.1 + foreach (array_keys($compoundLiteralSubjects[$name] ?? []) as $compoundLiteral) { + $compoundLiteral = (string) $compoundLiteral; + // 6.1.1 + $usage = $referencedOnce[$compoundLiteral] ?? false; + + if (false === $usage) { + continue; + } + + // 6.1.5 + $compoundLiteralNode = $graphMap[$name][$compoundLiteral] ?? null; + unset($graphMap[$name][$compoundLiteral]); + + if (null === $compoundLiteralNode) { + continue; + } + + // 6.1.6 + foreach ($usage['node']->{$usage['property']} ?? [] as $reference) { + if (!$reference instanceof \stdClass || ($reference->{Keyword::ID->value} ?? null) !== $compoundLiteral) { + continue; + } + + // 6.1.6.1 + unset($reference->{Keyword::ID->value}); + // 6.1.6.2 + $reference->{Keyword::VALUE->value} = self::firstValue($compoundLiteralNode, RdfVocabulary::RDF_VALUE); + + // 6.1.6.3 + if (property_exists($compoundLiteralNode, RdfVocabulary::RDF_LANGUAGE)) { + $language = self::firstValue($compoundLiteralNode, RdfVocabulary::RDF_LANGUAGE); + + if (!WellFormedness::isLanguageTag($language)) { + throw new JsonLdException('invalid language-tagged string'); + } + + $reference->{Keyword::LANGUAGE->value} = $language; + } + + // 6.1.6.4 + if (property_exists($compoundLiteralNode, RdfVocabulary::RDF_DIRECTION)) { + $direction = self::firstValue($compoundLiteralNode, RdfVocabulary::RDF_DIRECTION); + + if ('ltr' !== $direction && 'rtl' !== $direction) { + throw new JsonLdException('invalid base direction'); + } + + $reference->{Keyword::DIRECTION->value} = $direction; + } + } + } + + // 6.2 to 6.4 + foreach ($nilUsages[$name] ?? [] as $usage) { + // 6.4.1 + $node = $usage['node']; + $property = $usage['property']; + $head = $usage['value']; + // 6.4.2 + $list = []; + $listNodes = []; + + // 6.4.3 + while (RdfVocabulary::RDF_REST === $property && self::isWellFormedListNode($node, $referencedOnce)) { + $nodeIdentifier = (string) $node->{Keyword::ID->value}; + /** @var Usage $nodeUsage */ + $nodeUsage = $referencedOnce[$nodeIdentifier]; + + // 6.4.3.1 + $list[] = $node->{RdfVocabulary::RDF_FIRST}[0]; + // 6.4.3.2 + $listNodes[] = $nodeIdentifier; + // 6.4.3.3 to 6.4.3.5 + $node = $nodeUsage['node']; + $property = $nodeUsage['property']; + $head = $nodeUsage['value']; + + // 6.4.3.6 + if (!WellFormedness::isBlankNode($node->{Keyword::ID->value})) { + break; + } + } + + // 6.4.4 + unset($head->{Keyword::ID->value}); + // 6.4.5 and 6.4.6 + $head->{Keyword::LIST->value} = array_reverse($list); + + // 6.4.7 + foreach ($listNodes as $listNode) { + unset($graphMap[$name][$listNode]); + } + } + } + + // 7 + $result = []; + $defaultGraph = $graphMap[FramingKeyword::DEFAULT->value]; + + if ($options->ordered) { + ksort($defaultGraph, \SORT_STRING); + } + + // 8 + foreach ($defaultGraph as $subject => $node) { + $subject = (string) $subject; + + // 8.1 + if (FramingKeyword::DEFAULT->value !== $subject && \array_key_exists($subject, $graphMap)) { + $namedGraph = $graphMap[$subject]; + + if ($options->ordered) { + ksort($namedGraph, \SORT_STRING); + } + + // 8.1.1 and 8.1.2 + $node->{Keyword::GRAPH->value} = array_values(array_filter($namedGraph, self::isNotOnlyAReference(...))); + } + + // 8.2 + if (self::isNotOnlyAReference($node)) { + $result[] = $node; + } + } + + if (!$encodeResult) { + return $result; + } + + $encoded = json_encode($result, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION); + + if (false === $encoded) { + throw new JsonLdException('The JSON-LD document could not be encoded.'); + } + + return $encoded; + } + + /** + * The RDF to Object Conversion algorithm. + * + * see https://www.w3.org/TR/json-ld11-api/#rdf-to-object-conversion + */ + private function rdfToObject(Iri|BlankNode|Literal $value, ProcessorOptions $options): \stdClass + { + // 1 + if (!$value instanceof Literal) { + return (object) [Keyword::ID->value => self::identifier($value)]; + } + + // 2 + $result = new \stdClass(); + $converted = $value->value; + $type = null; + + if (null !== $value->language) { + // 2.7 + $result->{Keyword::LANGUAGE->value} = $value->language; + } elseif (Context::PROCESSING_MODE_10 !== $options->processingMode && RdfVocabulary::RDF_JSON === $value->datatype) { + // 2.5 + try { + $converted = json_decode($value->value, flags: \JSON_THROW_ON_ERROR); + } catch (\JsonException) { + throw new JsonLdException('invalid JSON literal'); + } + + $type = Keyword::JSON->value; + } elseif (RdfVocabulary::RDF_DIRECTION_I18N_DATATYPE === $options->rdfDirection && str_starts_with($value->datatype, RdfVocabulary::I18N)) { + // 2.6 + [$language, $direction] = explode('_', substr($value->datatype, \strlen(RdfVocabulary::I18N)), 2) + [1 => '']; + + if ('' !== $language) { + $result->{Keyword::LANGUAGE->value} = $language; + } + + if ('' !== $direction) { + $result->{Keyword::DIRECTION->value} = $direction; + } + } elseif ($options->useNativeTypes) { + // 2.4 + [$converted, $type] = self::nativeValue($value); + } elseif (RdfVocabulary::XSD_STRING !== $value->datatype) { + // 2.8 + $type = $value->datatype; + } + + // 2.9 + $result->{Keyword::VALUE->value} = $converted; + + // 2.10 + if (null !== $type) { + $result->{Keyword::TYPE->value} = $type; + } + + return $result; + } + + /** + * A literal as a native JSON value, when its lexical form allows it. The + * datatype is kept whenever the native value alone would not say it. + * + * @return array{bool|int|float|string, string|null} + */ + private static function nativeValue(Literal $literal): array + { + $lexicalForm = $literal->value; + + switch ($literal->datatype) { + case RdfVocabulary::XSD_STRING: + return [$lexicalForm, null]; + case RdfVocabulary::XSD_BOOLEAN: + if (\in_array($lexicalForm, ['true', 'false', '1', '0'], true)) { + return ['true' === $lexicalForm || '1' === $lexicalForm, null]; + } + + break; + case RdfVocabulary::XSD_INTEGER: + // An integer PHP cannot hold keeps its lexical form: a float + // would silently lose its last digits. + if (1 === preg_match('/^[+-]?\d+$/', $lexicalForm) && (string) (int) $lexicalForm === self::normalizeInteger($lexicalForm)) { + return [(int) $lexicalForm, null]; + } + + break; + case RdfVocabulary::XSD_DOUBLE: + // JSON has no infinity: a double it cannot write stays a string. + if (1 === preg_match('/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/', $lexicalForm) && is_finite((float) $lexicalForm)) { + return [(float) $lexicalForm, null]; + } + + break; + } + + return [$lexicalForm, $literal->datatype]; + } + + /** + * An integer lexical form without its optional plus sign and leading zeros. + */ + private static function normalizeInteger(string $lexicalForm): string + { + $negative = str_starts_with($lexicalForm, '-'); + $digits = ltrim(ltrim($lexicalForm, '+-'), '0'); + + if ('' === $digits) { + return '0'; + } + + return ($negative ? '-' : '') . $digits; + } + + /** + * Whether a node is one link of a well-formed RDF collection: a blank node + * referenced once, holding one rdf:first, one rdf:rest and nothing else but + * an optional rdf:List type. + * + * @param array $referencedOnce + */ + private static function isWellFormedListNode(\stdClass $node, array $referencedOnce): bool + { + $identifier = $node->{Keyword::ID->value} ?? null; + + if (!WellFormedness::isBlankNode($identifier) || false === ($referencedOnce[$identifier] ?? false)) { + return false; + } + + $first = $node->{RdfVocabulary::RDF_FIRST} ?? null; + $rest = $node->{RdfVocabulary::RDF_REST} ?? null; + + if (!\is_array($first) || 1 !== \count($first) || !\is_array($rest) || 1 !== \count($rest)) { + return false; + } + + $entryCount = \count(get_object_vars($node)); + + if (3 === $entryCount) { + return true; + } + + return 4 === $entryCount && [RdfVocabulary::RDF_LIST] === ($node->{Keyword::TYPE->value} ?? null); + } + + private static function isNotOnlyAReference(\stdClass $node): bool + { + $entries = get_object_vars($node); + + return 1 !== \count($entries) || !\array_key_exists(Keyword::ID->value, $entries); + } + + private static function firstValue(\stdClass $node, string $property): mixed + { + $first = ($node->{$property} ?? [])[0] ?? null; + + return $first instanceof \stdClass ? ($first->{Keyword::VALUE->value} ?? null) : null; + } + + private static function createNode(string $identifier): \stdClass + { + return (object) [Keyword::ID->value => $identifier]; + } + + private static function identifier(Iri|BlankNode $term): string + { + return $term instanceof Iri ? $term->value : $term->label; + } +} diff --git a/src/JsonLd/Algorithms/Rdf/Iri.php b/src/JsonLd/Algorithms/Rdf/Iri.php new file mode 100644 index 000000000..8e1fe81ad --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/Iri.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * An IRI, as a term of an RDF quad. + */ +final readonly class Iri +{ + public function __construct( + public string $value, + ) { + } +} diff --git a/src/JsonLd/Algorithms/Rdf/JsonCanonicalizer.php b/src/JsonLd/Algorithms/Rdf/JsonCanonicalizer.php new file mode 100644 index 000000000..f7e18f172 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/JsonCanonicalizer.php @@ -0,0 +1,140 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; + +/** + * The JSON Canonicalization Scheme (RFC 8785), which gives a JSON literal its + * lexical form. + * + * It expects a value decoded by json_decode() without the "assoc" flag: a JSON + * object is a \stdClass, which is what tells an empty object from an empty + * array. + * + * see https://www.rfc-editor.org/rfc/rfc8785 + */ +final class JsonCanonicalizer +{ + public static function canonicalize(mixed $value): string + { + if (null === $value) { + return 'null'; + } + + if (\is_bool($value)) { + return $value ? 'true' : 'false'; + } + + if (\is_int($value)) { + return (string) $value; + } + + if (\is_float($value)) { + return self::number($value); + } + + if (\is_string($value)) { + return self::string($value); + } + + if (\is_array($value)) { + return '[' . implode(',', array_map(self::canonicalize(...), $value)) . ']'; + } + + if ($value instanceof \stdClass) { + $members = []; + + foreach (get_object_vars($value) as $key => $member) { + $members[(string) $key] = $member; + } + + uksort($members, static fn (int|string $a, int|string $b): int => strcmp( + mb_convert_encoding((string) $a, 'UTF-16BE', 'UTF-8'), + mb_convert_encoding((string) $b, 'UTF-16BE', 'UTF-8'), + )); + + $serialized = []; + + foreach ($members as $key => $member) { + $serialized[] = self::string((string) $key) . ':' . self::canonicalize($member); + } + + return '{' . implode(',', $serialized) . '}'; + } + + throw new JsonLdException('invalid JSON literal'); + } + + private static function string(string $value): string + { + $encoded = json_encode($value, \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_LINE_TERMINATORS); + + if (false === $encoded) { + throw new JsonLdException('invalid JSON literal'); + } + + return $encoded; + } + + /** + * Number serialization as ECMAScript does it: the shortest digits that read + * back as the same double, in decimal notation between 1e-6 and 1e21. + */ + private static function number(float $value): string + { + if (!is_finite($value)) { + throw new JsonLdException('invalid JSON literal'); + } + + if (0.0 === $value) { + return '0'; + } + + $sign = $value < 0 ? '-' : ''; + $absolute = abs($value); + $representation = \sprintf('%.16e', $absolute); + + for ($precision = 0; $precision < 16; ++$precision) { + $candidate = \sprintf('%.' . $precision . 'e', $absolute); + + if ((float) $candidate === $absolute) { + $representation = $candidate; + + break; + } + } + + [$mantissa, $exponent] = explode('e', $representation); + $digits = rtrim(str_replace('.', '', $mantissa), '0'); + $digits = '' === $digits ? '0' : $digits; + $digitCount = \strlen($digits); + $pointPosition = (int) $exponent + 1; + + if ($digitCount <= $pointPosition && $pointPosition <= 21) { + return $sign . $digits . str_repeat('0', $pointPosition - $digitCount); + } + + if (0 < $pointPosition && $pointPosition <= 21) { + return $sign . substr($digits, 0, $pointPosition) . '.' . substr($digits, $pointPosition); + } + + if (-6 < $pointPosition && $pointPosition <= 0) { + return $sign . '0.' . str_repeat('0', -$pointPosition) . $digits; + } + + $power = $pointPosition - 1; + + return $sign . $digits[0] . ($digitCount > 1 ? '.' . substr($digits, 1) : '') + . 'e' . ($power < 0 ? '-' : '+') . abs($power); + } +} diff --git a/src/JsonLd/Algorithms/Rdf/Literal.php b/src/JsonLd/Algorithms/Rdf/Literal.php new file mode 100644 index 000000000..85246e541 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/Literal.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * An RDF literal: a lexical form, a datatype IRI and, for a language-tagged + * string, a language tag. + */ +final readonly class Literal +{ + public function __construct( + public string $value, + public string $datatype = RdfVocabulary::XSD_STRING, + public ?string $language = null, + ) { + } +} diff --git a/src/JsonLd/Algorithms/Rdf/NQuadsParser.php b/src/JsonLd/Algorithms/Rdf/NQuadsParser.php new file mode 100644 index 000000000..829a9bffc --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/NQuadsParser.php @@ -0,0 +1,121 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; + +/** + * Reads N-Quads into an RDF dataset. Blank nodes are accepted as predicates, so + * that generalized RDF can be read back. + * + * see https://www.w3.org/TR/n-quads/ + */ +final class NQuadsParser +{ + private const IRI = '<((?:[^\x00-\x20<>"{}|^`\\\\]|\\\\u[0-9A-Fa-f]{4}|\\\\U[0-9A-Fa-f]{8})*)>'; + private const BLANK_NODE = '(_:(?:[^\s.<"]|\.(?=[^\s.<"]))+)'; + private const LITERAL = '"((?:[^"\\\\\n\r]|\\\\.)*)"(?:\^\^' . self::IRI . '|@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*))?'; + private const STATEMENT = '/^[ \t]*(?:' . self::IRI . '|' . self::BLANK_NODE . ')[ \t]*' + . '(?:' . self::IRI . '|' . self::BLANK_NODE . ')[ \t]*' + . '(?:' . self::IRI . '|' . self::BLANK_NODE . '|' . self::LITERAL . ')[ \t]*' + . '(?:(?:' . self::IRI . '|' . self::BLANK_NODE . ')[ \t]*)?\.[ \t]*(?:#.*)?$/u'; + + private const ESCAPES = [ + 't' => "\t", + 'b' => "\x08", + 'n' => "\n", + 'r' => "\r", + 'f' => "\f", + '"' => '"', + "'" => "'", + '\\' => '\\', + ]; + + public function parse(string $nQuads): RdfDataset + { + $dataset = new RdfDataset(); + $lines = preg_split('/\r\n|\n|\r/', $nQuads); + + foreach (false === $lines ? [] : $lines as $index => $line) { + if (1 === preg_match('/^[ \t]*(?:#.*)?$/', $line)) { + continue; + } + + if (1 !== preg_match(self::STATEMENT, $line, $matches, \PREG_UNMATCHED_AS_NULL)) { + throw new JsonLdException(\sprintf('The N-Quads statement at line %d could not be parsed.', $index + 1)); + } + + $matches += array_fill(0, 12, null); + + $object = null !== $matches[7] + ? $this->literal($matches[7], $matches[8], $matches[9]) + : $this->node($matches[5], $matches[6]); + + $dataset->add(new Quad( + $this->node($matches[1], $matches[2]), + $this->node($matches[3], $matches[4]), + $object, + null === $matches[10] && null === $matches[11] ? null : $this->node($matches[10], $matches[11]), + )); + } + + return $dataset; + } + + private function node(?string $iri, ?string $blankNode): Iri|BlankNode + { + if (null !== $blankNode) { + return new BlankNode($blankNode); + } + + return new Iri($this->unescape((string) $iri)); + } + + private function literal(string $value, ?string $datatype, ?string $language): Literal + { + if (null !== $language) { + return new Literal($this->unescape($value), RdfVocabulary::RDF_LANG_STRING, $language); + } + + return new Literal( + $this->unescape($value), + null === $datatype ? RdfVocabulary::XSD_STRING : $this->unescape($datatype), + ); + } + + private function unescape(string $value): string + { + if (!str_contains($value, '\\')) { + return $value; + } + + return (string) preg_replace_callback( + '/\\\\(u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8}|.)/su', + static function (array $match): string { + $escape = $match[1]; + + if (\strlen($escape) > 1 && ('u' === $escape[0] || 'U' === $escape[0])) { + $codePoint = (int) hexdec(substr($escape, 1)); + + if ($codePoint > 0x10FFFF || ($codePoint >= 0xD800 && $codePoint <= 0xDFFF)) { + throw new JsonLdException('An N-Quads escape sequence does not name a character.'); + } + + return mb_chr($codePoint, 'UTF-8'); + } + + return self::ESCAPES[$escape] ?? throw new JsonLdException(\sprintf('"\%s" is not an N-Quads escape sequence.', $escape)); + }, + $value, + ); + } +} diff --git a/src/JsonLd/Algorithms/Rdf/NQuadsSerializer.php b/src/JsonLd/Algorithms/Rdf/NQuadsSerializer.php new file mode 100644 index 000000000..ef53d1f99 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/NQuadsSerializer.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * Writes an RDF dataset as N-Quads. + * + * see https://www.w3.org/TR/n-quads/ + */ +final class NQuadsSerializer +{ + public static function serialize(RdfDataset $dataset): string + { + $lines = []; + + foreach ($dataset->quads() as $quad) { + $lines[] = self::quad($quad) . "\n"; + } + + return implode('', $lines); + } + + /** + * One statement, without its line ending. + */ + public static function quad(Quad $quad): string + { + $terms = [self::term($quad->subject), self::term($quad->predicate), self::term($quad->object)]; + + if (null !== $quad->graph) { + $terms[] = self::term($quad->graph); + } + + return implode(' ', $terms) . ' .'; + } + + public static function term(Iri|BlankNode|Literal $term): string + { + if ($term instanceof Iri) { + return '<' . $term->value . '>'; + } + + if ($term instanceof BlankNode) { + return $term->label; + } + + $literal = '"' . strtr($term->value, ['\\' => '\\\\', '"' => '\"', "\n" => '\n', "\r" => '\r']) . '"'; + + if (null !== $term->language) { + return $literal . '@' . $term->language; + } + + if (RdfVocabulary::XSD_STRING === $term->datatype) { + return $literal; + } + + return $literal . '^^<' . $term->datatype . '>'; + } +} diff --git a/src/JsonLd/Algorithms/Rdf/Quad.php b/src/JsonLd/Algorithms/Rdf/Quad.php new file mode 100644 index 000000000..8a6e0ba5d --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/Quad.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * An RDF quad. A null graph stands for the default graph. A blank node may be + * a predicate: this is generalized RDF, see the "produceGeneralizedRdf" option. + */ +final readonly class Quad +{ + public function __construct( + public Iri|BlankNode $subject, + public Iri|BlankNode $predicate, + public Iri|BlankNode|Literal $object, + public Iri|BlankNode|null $graph = null, + ) { + } +} diff --git a/src/JsonLd/Algorithms/Rdf/RdfDataset.php b/src/JsonLd/Algorithms/Rdf/RdfDataset.php new file mode 100644 index 000000000..fbeb04e7d --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/RdfDataset.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * An RDF dataset: a set of quads, the default graph being the quads without a + * graph name. + * + * @implements \IteratorAggregate + */ +final class RdfDataset implements \IteratorAggregate, \Countable +{ + /** @var array */ + private array $quads = []; + + /** + * @param iterable $quads + */ + public function __construct(iterable $quads = []) + { + foreach ($quads as $quad) { + $this->add($quad); + } + } + + /** + * A dataset is a set: adding a quad it already holds changes nothing. + */ + public function add(Quad $quad): void + { + $this->quads[NQuadsSerializer::quad($quad)] ??= $quad; + } + + /** + * @return list + */ + public function quads(): array + { + return array_values($this->quads); + } + + /** + * @return \ArrayIterator + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->quads()); + } + + public function count(): int + { + return \count($this->quads); + } +} diff --git a/src/JsonLd/Algorithms/Rdf/RdfVocabulary.php b/src/JsonLd/Algorithms/Rdf/RdfVocabulary.php new file mode 100644 index 000000000..daa536e83 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/RdfVocabulary.php @@ -0,0 +1,41 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * The IRIs the RDF serialization and deserialization algorithms rely on. + */ +final class RdfVocabulary +{ + public const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; + public const RDF_TYPE = self::RDF . 'type'; + public const RDF_FIRST = self::RDF . 'first'; + public const RDF_REST = self::RDF . 'rest'; + public const RDF_NIL = self::RDF . 'nil'; + public const RDF_LIST = self::RDF . 'List'; + public const RDF_JSON = self::RDF . 'JSON'; + public const RDF_LANG_STRING = self::RDF . 'langString'; + public const RDF_VALUE = self::RDF . 'value'; + public const RDF_LANGUAGE = self::RDF . 'language'; + public const RDF_DIRECTION = self::RDF . 'direction'; + + public const XSD = 'http://www.w3.org/2001/XMLSchema#'; + public const XSD_STRING = self::XSD . 'string'; + public const XSD_BOOLEAN = self::XSD . 'boolean'; + public const XSD_INTEGER = self::XSD . 'integer'; + public const XSD_DOUBLE = self::XSD . 'double'; + + public const I18N = 'https://www.w3.org/ns/i18n#'; + + public const RDF_DIRECTION_I18N_DATATYPE = 'i18n-datatype'; + public const RDF_DIRECTION_COMPOUND_LITERAL = 'compound-literal'; +} diff --git a/src/JsonLd/Algorithms/Rdf/ToRdfConverter.php b/src/JsonLd/Algorithms/Rdf/ToRdfConverter.php new file mode 100644 index 000000000..140f53625 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/ToRdfConverter.php @@ -0,0 +1,353 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; +use JoliCode\StructuredData\JsonLd\Algorithms\Flatten\NodeMapGenerator; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\DocumentLoaderInterface; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\HttpDocumentLoader; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\FramingKeyword; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\Keyword; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Services\IdentifierGenerator; + +/** + * Deserializes a JSON-LD document to an RDF dataset. + * + * This is a PHP implementation of the Deserialize JSON-LD to RDF algorithm + * based on the JSON-LD 1.1 Processing Algorithms and API W3C Recommendation + * published on July 16th, 2020. + * + * see https://www.w3.org/TR/json-ld11-api/#deserialize-json-ld-to-rdf-algorithm + */ +class ToRdfConverter +{ + private readonly Expander $expander; + + public function __construct( + ?Expander $expander = null, + ?DocumentLoaderInterface $documentLoader = null, + ) { + $this->expander = $expander ?? new Expander(documentLoader: $documentLoader ?? new HttpDocumentLoader()); + } + + /** + * @param string|\stdClass $json The JSON-LD document to deserialize. It can be a URI, a JSON string or a JSON object. + */ + public function toRdf(string|\stdClass $json, ProcessorOptions $options = new ProcessorOptions()): RdfDataset + { + self::assertRdfDirection($options->rdfDirection); + + // The expansion writes to the options and to the document it is handed: + // both are the caller's. + $options = clone $options; + $options->ordered = false; + + if ($json instanceof \stdClass) { + $copy = unserialize(serialize($json)); + $json = $copy instanceof \stdClass ? $copy : $json; + } + + $expanded = $this->expander->expand($json, $options, false); + + if ($expanded instanceof \stdClass) { + $expanded = [$expanded]; + } + + $identifierGenerator = new IdentifierGenerator(); + /** @var array>|null> $nodeMap */ + $nodeMap = [FramingKeyword::DEFAULT->value => []]; + + if (\is_array($expanded)) { + self::unnameNullIdentifiers($expanded); + (new NodeMapGenerator($identifierGenerator))->buildNode($expanded, $nodeMap); + } + + $dataset = new RdfDataset(); + + // 1 + foreach ($nodeMap as $graphName => $graph) { + $graphName = (string) $graphName; + $graphTerm = null; + + // 1.1 + if (FramingKeyword::DEFAULT->value !== $graphName) { + $graphTerm = self::node($graphName); + + if (null === $graphTerm) { + continue; + } + } + + // 1.3 + foreach ($graph ?? [] as $subject => $node) { + // 1.3.1 + $subjectTerm = self::node((string) $subject); + + if (null === $subjectTerm) { + continue; + } + + // 1.3.2 + foreach ($node as $property => $values) { + $property = (string) $property; + + if (!\is_array($values)) { + continue; + } + + // 1.3.2.1 + if (Keyword::TYPE->value === $property) { + foreach ($values as $type) { + $typeTerm = \is_string($type) ? self::node($type) : null; + + if (null !== $typeTerm) { + $dataset->add(new Quad($subjectTerm, new Iri(RdfVocabulary::RDF_TYPE), $typeTerm, $graphTerm)); + } + } + + continue; + } + + // 1.3.2.2 + if (str_starts_with($property, '@')) { + continue; + } + + // 1.3.2.3 and 1.3.2.4 + $predicate = self::node($property); + + if (null === $predicate || ($predicate instanceof BlankNode && !$options->produceGeneralizedRdf)) { + continue; + } + + // 1.3.2.5 + foreach ($values as $item) { + $object = $this->objectToRdf($item, $dataset, $graphTerm, $options, $identifierGenerator); + + if (null !== $object) { + $dataset->add(new Quad($subjectTerm, $predicate, $object, $graphTerm)); + } + } + } + } + } + + return $dataset; + } + + public static function assertRdfDirection(?string $rdfDirection): void + { + if (!\in_array($rdfDirection, [null, RdfVocabulary::RDF_DIRECTION_I18N_DATATYPE, RdfVocabulary::RDF_DIRECTION_COMPOUND_LITERAL], true)) { + throw new JsonLdException(\sprintf('The "rdfDirection" option must be null, "%s" or "%s".', RdfVocabulary::RDF_DIRECTION_I18N_DATATYPE, RdfVocabulary::RDF_DIRECTION_COMPOUND_LITERAL)); + } + } + + /** + * The Object to RDF Conversion algorithm. The triples a list or a compound + * literal needs are added to the dataset on the way. + * + * see https://www.w3.org/TR/json-ld11-api/#object-to-rdf-conversion + */ + private function objectToRdf( + mixed $item, + RdfDataset $dataset, + Iri|BlankNode|null $graph, + ProcessorOptions $options, + IdentifierGenerator $identifierGenerator, + ): Iri|BlankNode|Literal|null { + // The node map holds a list as an array, the expanded document as a map. + if ($item instanceof \stdClass && property_exists($item, Keyword::LIST->value)) { + $item = [Keyword::LIST->value => $item->{Keyword::LIST->value}]; + } + + if (\is_array($item)) { + $list = $item[Keyword::LIST->value] ?? []; + + return $this->listToRdf(\is_array($list) ? array_values($list) : [], $dataset, $graph, $options, $identifierGenerator); + } + + if (!$item instanceof \stdClass) { + return null; + } + + // 1 and 2 + if (!property_exists($item, Keyword::VALUE->value)) { + return self::node($item->{Keyword::ID->value} ?? null); + } + + // 4 + $value = $item->{Keyword::VALUE->value}; + // 5 + $datatype = $item->{Keyword::TYPE->value} ?? null; + $language = $item->{Keyword::LANGUAGE->value} ?? null; + + // 6 + if (null !== $datatype && Keyword::JSON->value !== $datatype && !WellFormedness::isIri($datatype)) { + return null; + } + + // 7 + if (null !== $language && !WellFormedness::isLanguageTag($language)) { + return null; + } + + if (Keyword::JSON->value === $datatype) { + // 8 + $value = JsonCanonicalizer::canonicalize($value); + $datatype = RdfVocabulary::RDF_JSON; + } elseif (\is_bool($value)) { + // 9 + $value = CanonicalLexicalForm::boolean($value); + $datatype ??= RdfVocabulary::XSD_BOOLEAN; + } elseif (\is_int($value) || \is_float($value)) { + if (RdfVocabulary::XSD_DOUBLE === $datatype || CanonicalLexicalForm::isDouble($value)) { + // 10 + $value = CanonicalLexicalForm::double($value); + $datatype ??= RdfVocabulary::XSD_DOUBLE; + } else { + // 11 + $value = CanonicalLexicalForm::integer($value); + $datatype ??= RdfVocabulary::XSD_INTEGER; + } + } else { + // 12 + $datatype ??= null === $language ? RdfVocabulary::XSD_STRING : RdfVocabulary::RDF_LANG_STRING; + } + + if (!\is_string($value) || !\is_string($datatype)) { + return null; + } + + $direction = $item->{Keyword::DIRECTION->value} ?? null; + + // 13 + if (\is_string($direction) && null !== $options->rdfDirection) { + // 13.1 + $normalizedLanguage = \is_string($language) ? strtolower($language) : ''; + + // 13.2 + if (RdfVocabulary::RDF_DIRECTION_I18N_DATATYPE === $options->rdfDirection) { + return new Literal($value, RdfVocabulary::I18N . $normalizedLanguage . '_' . $direction); + } + + // 13.3 + $compoundLiteral = new BlankNode($identifierGenerator->getIdentifier(null)); + $dataset->add(new Quad($compoundLiteral, new Iri(RdfVocabulary::RDF_VALUE), new Literal($value), $graph)); + + if (\is_string($language)) { + $dataset->add(new Quad($compoundLiteral, new Iri(RdfVocabulary::RDF_LANGUAGE), new Literal($normalizedLanguage), $graph)); + } + + $dataset->add(new Quad($compoundLiteral, new Iri(RdfVocabulary::RDF_DIRECTION), new Literal($direction), $graph)); + + return $compoundLiteral; + } + + // 14 + return new Literal($value, $datatype, \is_string($language) ? $language : null); + } + + /** + * The List to RDF Conversion algorithm. + * + * see https://www.w3.org/TR/json-ld11-api/#list-to-rdf-conversion + * + * @param list $list + */ + private function listToRdf( + array $list, + RdfDataset $dataset, + Iri|BlankNode|null $graph, + ProcessorOptions $options, + IdentifierGenerator $identifierGenerator, + ): Iri|BlankNode { + // 1 + if ([] === $list) { + return new Iri(RdfVocabulary::RDF_NIL); + } + + // 2 + $blankNodes = []; + + foreach ($list as $ignored) { + $blankNodes[] = new BlankNode($identifierGenerator->getIdentifier(null)); + } + + // 3 + foreach ($list as $index => $item) { + $subject = $blankNodes[$index]; + // 3.2 + $object = $this->objectToRdf($item, $dataset, $graph, $options, $identifierGenerator); + + // 3.3 + if (null !== $object) { + $dataset->add(new Quad($subject, new Iri(RdfVocabulary::RDF_FIRST), $object, $graph)); + } + + // 3.4 + $dataset->add(new Quad( + $subject, + new Iri(RdfVocabulary::RDF_REST), + $blankNodes[$index + 1] ?? new Iri(RdfVocabulary::RDF_NIL), + $graph, + )); + } + + // 4 + return $blankNodes[0]; + } + + /** + * Expansion leaves a null "@id" where an IRI had the form of a keyword. Such + * a node names nothing: it is neither a subject nor an object, while the + * nodes it holds still are. The node map generation would give it a fresh + * blank node identifier, so it is handed an identifier that is not + * well-formed instead, which is what the deserialization leaves out. + */ + private static function unnameNullIdentifiers(mixed $element): void + { + if (\is_array($element)) { + foreach ($element as $item) { + self::unnameNullIdentifiers($item); + } + + return; + } + + if (!$element instanceof \stdClass || property_exists($element, Keyword::VALUE->value)) { + return; + } + + if (property_exists($element, Keyword::ID->value) && null === $element->{Keyword::ID->value}) { + $element->{Keyword::ID->value} = ''; + } + + foreach (get_object_vars($element) as $value) { + self::unnameNullIdentifiers($value); + } + } + + private static function node(mixed $identifier): Iri|BlankNode|null + { + if (!\is_string($identifier)) { + return null; + } + + if (WellFormedness::isBlankNode($identifier)) { + return new BlankNode($identifier); + } + + return WellFormedness::isIri($identifier) ? new Iri($identifier) : null; + } +} diff --git a/src/JsonLd/Algorithms/Rdf/WellFormedness.php b/src/JsonLd/Algorithms/Rdf/WellFormedness.php new file mode 100644 index 000000000..92ad5e460 --- /dev/null +++ b/src/JsonLd/Algorithms/Rdf/WellFormedness.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\JsonLd\Algorithms\Rdf; + +/** + * RDF only holds well-formed IRIs and language tags: a triple that would carry + * anything else is left out of the dataset, without an error. + */ +final class WellFormedness +{ + public static function isIri(mixed $value): bool + { + return \is_string($value) + && 1 === preg_match('/^[A-Za-z][A-Za-z0-9+.\-]*:[^\x00-\x20<>"{}|\\\\^`#]*(#[^\x00-\x20<>"{}|\\\\^`#]*)?$/', $value); + } + + public static function isBlankNode(mixed $value): bool + { + return \is_string($value) && str_starts_with($value, '_:') && 1 !== preg_match('/\s/', $value); + } + + /** + * A language tag as BCP 47 shapes it. + */ + public static function isLanguageTag(mixed $value): bool + { + return \is_string($value) && 1 === preg_match('/^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/', $value); + } +} diff --git a/tests/Algorithms/FromRdfTest.php b/tests/Algorithms/FromRdfTest.php new file mode 100644 index 000000000..98c37ab07 --- /dev/null +++ b/tests/Algorithms/FromRdfTest.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms; + +use JoliCode\StructuredData\JsonLd\Algorithms; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; +use JoliCode\StructuredData\Tests\Algorithms\Rdf\JsonLdComparator; +use JoliCode\StructuredData\Tests\Algorithms\Rdf\ManifestTestProvider; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * @see https://w3c.github.io/json-ld-api/tests/fromRdf-manifest.html + */ +#[Group('fromRdf')] +class FromRdfTest extends TestCase +{ + #[DataProvider('provideManifestEntries')] + public function testFromRdf(string $input, ?string $expect, ?string $errorCode, ProcessorOptions $options): void + { + $converter = new FromRdfConverter(); + + if (null !== $errorCode) { + try { + $converter->fromRdf($input, $options); + } catch (JsonLdException $exception) { + $this->assertSame($errorCode, $exception->getMessage()); + + return; + } + + $this->fail(\sprintf('An exception was expected for this test but none were thrown. Expected error message was : %s', $errorCode)); + } + + $actual = $converter->fromRdf($input, $options); + + $this->assertNotNull($expect, 'A positive evaluation test names its expected output.'); + $this->assertTrue( + JsonLdComparator::areEquivalent(json_decode($expect), json_decode($actual)), + \sprintf("The documents are not equivalent.\nExpected:\n%s\nActual:\n%s", $expect, $actual), + ); + } + + /** + * @return iterable + */ + public static function provideManifestEntries(): iterable + { + return ManifestTestProvider::provide(Algorithms::FROM_RDF->value); + } +} diff --git a/tests/Algorithms/Rdf/ComparatorTest.php b/tests/Algorithms/Rdf/ComparatorTest.php new file mode 100644 index 000000000..dc38699ec --- /dev/null +++ b/tests/Algorithms/Rdf/ComparatorTest.php @@ -0,0 +1,132 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * The two comparators the W3C RDF suites are judged with: a comparator that + * says yes too easily would make every one of those tests pass. + */ +#[Group('rdf')] +class ComparatorTest extends TestCase +{ + #[DataProvider('provideDatasets')] + public function testDatasetIsomorphism(string $first, string $second, bool $isomorphic): void + { + $parser = new NQuadsParser(); + + $this->assertSame($isomorphic, RdfDatasetIsomorphism::areIsomorphic($parser->parse($first), $parser->parse($second))); + $this->assertSame($isomorphic, RdfDatasetIsomorphism::areIsomorphic($parser->parse($second), $parser->parse($first))); + } + + /** + * @return iterable + */ + public static function provideDatasets(): iterable + { + yield 'same ground statements in another order' => [ + " \"a\" .\n \"b\" .", + " \"b\" .\n \"a\" .", + true, + ]; + yield 'renamed blank nodes' => [ + "_:a _:b .\n_:b \"leaf\" .", + "_:x _:y .\n_:y \"leaf\" .", + true, + ]; + yield 'a list, relabelled and shuffled' => [ + " _:l1 .\n_:l1 \"a\" .\n_:l1 _:l2 .\n_:l2 \"b\" .\n_:l2 .", + "_:z .\n_:z \"b\" .\n_:y _:z .\n_:y \"a\" .\n _:y .", + true, + ]; + yield 'a cycle of indistinguishable blank nodes' => [ + "_:a _:b .\n_:b _:c .\n_:c _:a .", + "_:x _:z .\n_:z _:y .\n_:y _:x .", + true, + ]; + yield 'language tags compare without case' => [ + ' "a"@en-US .', + ' "a"@en-us .', + true, + ]; + yield 'a different literal' => [ + ' "a" .', + ' "b" .', + false, + ]; + yield 'a different datatype' => [ + ' "1" .', + ' "1"^^ .', + false, + ]; + yield 'a missing statement' => [ + " \"a\" .\n \"b\" .", + ' "a" .', + false, + ]; + yield 'another graph' => [ + ' "a" .', + ' "a" .', + false, + ]; + yield 'a blank node where an IRI is expected' => [ + ' _:b .', + ' .', + false, + ]; + yield 'two blank nodes merged into one' => [ + "_:a \"x\" .\n_:b \"y\" .", + "_:a \"x\" .\n_:a \"y\" .", + false, + ]; + yield 'the same shapes wired differently' => [ + "_:a _:b .\n_:b _:a .\n_:c _:c .", + "_:a _:b .\n_:b _:c .\n_:c _:a .", + false, + ]; + yield 'a list in another order' => [ + " _:l1 .\n_:l1 \"a\" .\n_:l1 _:l2 .\n_:l2 \"b\" .\n_:l2 .", + " _:l1 .\n_:l1 \"b\" .\n_:l1 _:l2 .\n_:l2 \"a\" .\n_:l2 .", + false, + ]; + } + + #[DataProvider('provideDocuments')] + public function testJsonLdEquivalence(string $first, string $second, bool $equivalent): void + { + $this->assertSame($equivalent, JsonLdComparator::areEquivalent(json_decode($first), json_decode($second))); + $this->assertSame($equivalent, JsonLdComparator::areEquivalent(json_decode($second), json_decode($first))); + } + + /** + * @return iterable + */ + public static function provideDocuments(): iterable + { + yield 'keys in another order' => ['[{"@id": "urn:a", "urn:p": [{"@value": 1}]}]', '[{"urn:p": [{"@value": 1}], "@id": "urn:a"}]', true]; + yield 'values in another order' => ['[{"urn:p": [{"@value": 1}, {"@value": 2}]}]', '[{"urn:p": [{"@value": 2}, {"@value": 1}]}]', true]; + yield 'nodes in another order' => ['[{"@id": "urn:a"}, {"@id": "urn:b"}]', '[{"@id": "urn:b"}, {"@id": "urn:a"}]', true]; + yield 'an integer and the same float' => ['[{"@value": 1}]', '[{"@value": 1.0}]', true]; + yield 'a list in the same order' => ['[{"urn:p": [{"@list": [{"@value": 1}, {"@value": 2}]}]}]', '[{"urn:p": [{"@list": [{"@value": 1}, {"@value": 2}]}]}]', true]; + yield 'a list in another order' => ['[{"urn:p": [{"@list": [{"@value": 1}, {"@value": 2}]}]}]', '[{"urn:p": [{"@list": [{"@value": 2}, {"@value": 1}]}]}]', false]; + yield 'a different value' => ['[{"urn:p": [{"@value": 1}]}]', '[{"urn:p": [{"@value": 2}]}]', false]; + yield 'a string and a number' => ['[{"@value": "1"}]', '[{"@value": 1}]', false]; + yield 'a missing entry' => ['[{"@id": "urn:a", "urn:p": []}]', '[{"@id": "urn:a"}]', false]; + yield 'a duplicated value' => ['[{"urn:p": [{"@value": 1}, {"@value": 1}]}]', '[{"urn:p": [{"@value": 1}, {"@value": 2}]}]', false]; + yield 'an object and an array' => ['[{"@value": {}}]', '[{"@value": []}]', false]; + yield 'a missing value' => ['[{"urn:p": [{"@value": 1}, {"@value": 2}]}]', '[{"urn:p": [{"@value": 1}]}]', false]; + } +} diff --git a/tests/Algorithms/Rdf/ConvertersTest.php b/tests/Algorithms/Rdf/ConvertersTest.php new file mode 100644 index 000000000..5255e1235 --- /dev/null +++ b/tests/Algorithms/Rdf/ConvertersTest.php @@ -0,0 +1,171 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfVocabulary; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * What the W3C suites do not ask of the two converters. + */ +#[Group('rdf')] +class ConvertersTest extends TestCase +{ + private const DOCUMENT = <<<'JSON' + { + "@context": {"@vocab": "http://example.com/", "knows": {"@container": "@list"}}, + "@id": "http://example.com/alice", + "@type": "Person", + "name": {"@value": "Alice", "@language": "fr"}, + "age": 42, + "height": 1.72, + "member": true, + "data": {"@type": "@json", "@value": {"b": [], "a": {}}}, + "knows": [{"@id": "http://example.com/bob"}, {"name": "Carole"}] + } + JSON; + + public function testADocumentSurvivesTheRoundTrip(): void + { + $toRdf = new ToRdfConverter(); + $dataset = $toRdf->toRdf(self::DOCUMENT); + + $this->assertCount(12, $dataset); + + $document = (new FromRdfConverter())->fromRdf($dataset, new ProcessorOptions(useNativeTypes: true)); + + $this->assertStringContainsString('"@value": 1.72', $document); + $this->assertTrue(RdfDatasetIsomorphism::areIsomorphic($dataset, $toRdf->toRdf($document))); + } + + public function testTheCallersDocumentAndOptionsAreLeftAlone(): void + { + $document = json_decode(self::DOCUMENT); + $this->assertInstanceOf(\stdClass::class, $document); + $options = new ProcessorOptions(ordered: true); + + (new ToRdfConverter())->toRdf($document, $options); + + $this->assertEquals(json_decode(self::DOCUMENT), $document); + $this->assertTrue($options->ordered); + } + + public function testABlankNodePredicateIsDroppedUnlessAskedFor(): void + { + $document = '{"@id": "http://example.com/s", "_:p": "o"}'; + $converter = new ToRdfConverter(); + + $this->assertCount(0, $converter->toRdf($document)); + $this->assertSame( + " _:b0 \"o\" .\n", + NQuadsSerializer::serialize($converter->toRdf($document, new ProcessorOptions(produceGeneralizedRdf: true))), + ); + } + + public function testTheBaseDirectionIsDroppedUnlessAskedFor(): void + { + $document = '{"@id": "http://example.com/s", "http://example.com/p": {"@value": "שלום", "@language": "he", "@direction": "rtl"}}'; + $converter = new ToRdfConverter(); + + $this->assertSame( + " \"שלום\"@he .\n", + NQuadsSerializer::serialize($converter->toRdf($document)), + ); + $this->assertSame( + " \"שלום\"^^ .\n", + NQuadsSerializer::serialize($converter->toRdf($document, new ProcessorOptions(rdfDirection: RdfVocabulary::RDF_DIRECTION_I18N_DATATYPE))), + ); + $this->assertCount(4, $converter->toRdf($document, new ProcessorOptions(rdfDirection: RdfVocabulary::RDF_DIRECTION_COMPOUND_LITERAL))); + } + + public function testAnUnknownRdfDirectionIsRefused(): void + { + $options = new ProcessorOptions(rdfDirection: 'sideways'); + + try { + (new ToRdfConverter())->toRdf('{}', $options); + $this->fail('toRdf accepted an unknown rdfDirection.'); + } catch (JsonLdException) { + } + + $this->expectException(JsonLdException::class); + + (new FromRdfConverter())->fromRdf('', $options); + } + + public function testFromRdfHandsBackObjectsWhenAsked(): void + { + $document = (new FromRdfConverter())->fromRdf(' "o" .', encodeResult: false); + + $this->assertEquals([(object) ['@id' => 'http://example.com/s', 'http://example.com/p' => [(object) ['@value' => 'o']]]], $document); + } + + public function testFromRdfOrdersTheNodesWhenAsked(): void + { + $nQuads = " \"1\" .\n \"2\" ."; + $converter = new FromRdfConverter(); + + $this->assertSame(['http://example.com/b', 'http://example.com/a'], array_column($converter->fromRdf($nQuads, encodeResult: false), '@id')); + $this->assertSame(['http://example.com/a', 'http://example.com/b'], array_column($converter->fromRdf($nQuads, new ProcessorOptions(ordered: true), false), '@id')); + } + + public function testAnIntegerPhpCannotHoldKeepsItsLexicalForm(): void + { + $document = (new FromRdfConverter())->fromRdf( + <<<'NQUADS' + "123456789012345678901234567890"^^ . + "+007"^^ . + NQUADS, + new ProcessorOptions(useNativeTypes: true), + false, + ); + + $this->assertEquals( + [ + (object) ['@value' => '123456789012345678901234567890', '@type' => RdfVocabulary::XSD_INTEGER], + (object) ['@value' => 7], + ], + $document[0]->{'http://example.com/p'}, + ); + } + + #[DataProvider('provideCompoundLiterals')] + public function testAnIllFormedCompoundLiteralIsRefused(string $nQuads, string $errorCode): void + { + $this->expectExceptionObject(new JsonLdException($errorCode)); + + (new FromRdfConverter())->fromRdf($nQuads, new ProcessorOptions(rdfDirection: RdfVocabulary::RDF_DIRECTION_COMPOUND_LITERAL)); + } + + /** + * @return iterable + */ + public static function provideCompoundLiterals(): iterable + { + $compoundLiteral = <<<'NQUADS' + _:cl . + _:cl "v" . + _:cl "%s" . + _:cl "%s" . + NQUADS; + + yield 'language' => [\sprintf($compoundLiteral, 'not a language', 'rtl'), 'invalid language-tagged string']; + yield 'direction' => [\sprintf($compoundLiteral, 'en', 'sideways'), 'invalid base direction']; + } +} diff --git a/tests/Algorithms/Rdf/JsonLdComparator.php b/tests/Algorithms/Rdf/JsonLdComparator.php new file mode 100644 index 000000000..a0126d5db --- /dev/null +++ b/tests/Algorithms/Rdf/JsonLdComparator.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +/** + * Compares two decoded JSON-LD documents the way the W3C test suite asks a + * fromRdf result to be compared: the order of an array only matters inside a + * list, since an RDF dataset has no order to give to anything else. + */ +final class JsonLdComparator +{ + public static function areEquivalent(mixed $expected, mixed $actual, bool $ordered = false): bool + { + if ($expected instanceof \stdClass && $actual instanceof \stdClass) { + $expectedEntries = get_object_vars($expected); + $actualEntries = get_object_vars($actual); + + if (\count($expectedEntries) !== \count($actualEntries)) { + return false; + } + + foreach ($expectedEntries as $key => $value) { + if (!\array_key_exists($key, $actualEntries) || !self::areEquivalent($value, $actualEntries[$key], '@list' === (string) $key)) { + return false; + } + } + + return true; + } + + if (\is_array($expected) && \is_array($actual)) { + if (\count($expected) !== \count($actual)) { + return false; + } + + $expected = array_values($expected); + $remaining = array_values($actual); + + if ($ordered) { + foreach ($expected as $index => $value) { + if (!self::areEquivalent($value, $remaining[$index])) { + return false; + } + } + + return true; + } + + foreach ($expected as $value) { + foreach ($remaining as $index => $candidate) { + if (self::areEquivalent($value, $candidate)) { + unset($remaining[$index]); + + continue 2; + } + } + + return false; + } + + return true; + } + + if ((\is_int($expected) || \is_float($expected)) && (\is_int($actual) || \is_float($actual))) { + return (float) $expected === (float) $actual; + } + + return $expected === $actual; + } +} diff --git a/tests/Algorithms/Rdf/LexicalFormTest.php b/tests/Algorithms/Rdf/LexicalFormTest.php new file mode 100644 index 000000000..1a149037b --- /dev/null +++ b/tests/Algorithms/Rdf/LexicalFormTest.php @@ -0,0 +1,131 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\CanonicalLexicalForm; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\JsonCanonicalizer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\WellFormedness; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +#[Group('rdf')] +class LexicalFormTest extends TestCase +{ + #[DataProvider('provideDoubles')] + public function testCanonicalDouble(int|float $value, string $expected): void + { + $this->assertSame($expected, CanonicalLexicalForm::double($value)); + } + + /** + * @return iterable + */ + public static function provideDoubles(): iterable + { + yield 'one' => [1, '1.0E0']; + yield 'a fraction' => [5.3, '5.3E0']; + yield 'negative' => [-0.5, '-5.0E-1']; + yield 'large' => [1.0E21, '1.0E21']; + yield 'small' => [0.00000123, '1.23E-6']; + yield 'fifteen digits' => [1.234567890123456, '1.234567890123456E0']; + yield 'zero' => [0.0, '0.0E0']; + yield 'infinity' => [\INF, 'INF']; + yield 'minus infinity' => [-\INF, '-INF']; + yield 'not a number' => [\NAN, 'NaN']; + } + + #[DataProvider('provideIntegers')] + public function testCanonicalInteger(int|float $value, string $expected): void + { + $this->assertSame($expected, CanonicalLexicalForm::integer($value)); + } + + /** + * @return iterable + */ + public static function provideIntegers(): iterable + { + yield 'an integer' => [42, '42']; + yield 'a negative integer' => [-42, '-42']; + yield 'a float without fraction' => [1.0, '1']; + yield 'a float too large for an int' => [1.0E20, '100000000000000000000']; + yield 'minus zero' => [-0.0, '0']; + } + + public function testWhichNumbersAreDoubles(): void + { + $this->assertFalse(CanonicalLexicalForm::isDouble(1)); + $this->assertFalse(CanonicalLexicalForm::isDouble(1.0)); + $this->assertFalse(CanonicalLexicalForm::isDouble(1.0E20)); + $this->assertTrue(CanonicalLexicalForm::isDouble(1.5)); + $this->assertTrue(CanonicalLexicalForm::isDouble(1.0E21)); + $this->assertTrue(CanonicalLexicalForm::isDouble(-1.0E21)); + } + + public function testBooleans(): void + { + $this->assertSame('true', CanonicalLexicalForm::boolean(true)); + $this->assertSame('false', CanonicalLexicalForm::boolean(false)); + } + + #[DataProvider('provideJson')] + public function testJsonCanonicalization(string $json, string $expected): void + { + $this->assertSame($expected, JsonCanonicalizer::canonicalize(json_decode($json))); + } + + /** + * The numbers are the ones of RFC 8785, appendix B. + * + * @return iterable + */ + public static function provideJson(): iterable + { + yield 'literals' => ['[null, true, false]', '[null,true,false]']; + yield 'empty object and array' => ['{"b": [], "a": {}}', '{"a":{},"b":[]}']; + yield 'keys sorted by UTF-16 code units' => ['{"\u20ac": 1, "\r": 2, "\ud83d\ude00": 3, "\ufb33": 4, "1": 5, "\u0080": 6, "\u00f6": 7}', "{\"\\r\":2,\"1\":5,\"\u{80}\":6,\"ö\":7,\"€\":1,\"😀\":3,\"\u{FB33}\":4}"]; + yield 'string escapes' => ['"\u20ac$\u000f\nA\'B\"\\\\\"/"', '"€$\u000f\nA\'B\"\\\\\"/"']; + yield 'nested' => ['{"numbers": [333333333.33333329, 1E30, 4.50, 2e-3, 0.000000000000000000000000001], "literals": [null, true, false]}', '{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27]}']; + yield 'zero' => ['[0, 0.0, -0.0]', '[0,0,0]']; + yield 'integer valued float' => ['[1.0, 100.0, 1e2]', '[1,100,100]']; + yield 'largest decimal notation' => ['[1e20, 123456789012345680000, 1e21]', '[100000000000000000000,123456789012345680000,1e+21]']; + yield 'smallest decimal notation' => ['[0.000001, 0.0000001]', '[0.000001,1e-7]']; + yield 'extremes' => ['[5e-324, 1.7976931348623157e308, -1.7976931348623157e308]', '[5e-324,1.7976931348623157e+308,-1.7976931348623157e+308]']; + yield 'shortest round trip' => ['[0.1, 0.30000000000000004, 9007199254740992, 295147905179352830000, 9.999999999999997e22]', '[0.1,0.30000000000000004,9007199254740992,295147905179352830000,9.999999999999997e+22]']; + } + + public function testWellFormedIris(): void + { + $this->assertTrue(WellFormedness::isIri('http://example.com/a?b#c')); + $this->assertTrue(WellFormedness::isIri('urn:ex:s')); + $this->assertFalse(WellFormedness::isIri('relative')); + $this->assertFalse(WellFormedness::isIri('http://example.com/a b')); + $this->assertFalse(WellFormedness::isIri('http://example.com/')); + $this->assertFalse(WellFormedness::isIri('http://example.com/#a#b')); + $this->assertFalse(WellFormedness::isIri('_:b0')); + $this->assertFalse(WellFormedness::isIri(null)); + } + + public function testWellFormedBlankNodesAndLanguageTags(): void + { + $this->assertTrue(WellFormedness::isBlankNode('_:b0')); + $this->assertFalse(WellFormedness::isBlankNode('_:b 0')); + $this->assertFalse(WellFormedness::isBlankNode('http://example.com/')); + + $this->assertTrue(WellFormedness::isLanguageTag('en')); + $this->assertTrue(WellFormedness::isLanguageTag('zh-Hant-TW')); + $this->assertFalse(WellFormedness::isLanguageTag('en us')); + $this->assertFalse(WellFormedness::isLanguageTag('a-very-long-subtag-123456789')); + $this->assertFalse(WellFormedness::isLanguageTag('')); + } +} diff --git a/tests/Algorithms/Rdf/ManifestTestProvider.php b/tests/Algorithms/Rdf/ManifestTestProvider.php new file mode 100644 index 000000000..6f0a600ee --- /dev/null +++ b/tests/Algorithms/Rdf/ManifestTestProvider.php @@ -0,0 +1,126 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\ContextProcessing\Context; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\Tests\Algorithms\AbstractJsonLdTestCase; + +/** + * Turns a W3C manifest into PHPUnit data sets, one per entry and named after + * the fragment of its IRI ("#t0001"), which is what the EARL report maps the + * outcomes back with. + * + * The entries written for a JSON-LD 1.0 processor only are left out: they + * describe a behaviour JSON-LD 1.1 changed. + */ +final class ManifestTestProvider +{ + public const BASE_IRI = 'https://w3c.github.io/json-ld-api/tests/'; + + private const OPTIONS = ['base', 'expandContext', 'processingMode', 'produceGeneralizedRdf', 'rdfDirection', 'useNativeTypes', 'useRdfType']; + + /** + * What a manifest says of a test without it being an option of the + * processor: the version of the specification it was written for, whether + * it is normative, and the canonicalization the JSON literals are compared + * under, which is the only one there is. + */ + private const IGNORED_OPTIONS = ['specVersion', 'normative', 'useJCS']; + + /** + * @return iterable + */ + public static function provide(string $suite): iterable + { + $manifestFile = \sprintf('%s/%s-manifest.jsonld', AbstractJsonLdTestCase::DATA_PATH, $suite); + + if (!is_file($manifestFile)) { + throw new \RuntimeException(\sprintf('The manifest "%s" does not exist. Did you forget to install the test suite? Please run the following command : `castor qa:phpunit:prepare`', $manifestFile)); + } + + $manifest = json_decode((string) file_get_contents($manifestFile), true); + + if (!\is_array($manifest) || !\is_array($manifest['sequence'] ?? null)) { + throw new \RuntimeException(\sprintf('The manifest "%s" could not be read.', $manifestFile)); + } + + foreach ($manifest['sequence'] as $entry) { + if (!\is_array($entry) || !\is_string($entry['@id'] ?? null) || !\is_string($entry['input'] ?? null)) { + continue; + } + + $entryOptions = \is_array($entry['option'] ?? null) ? $entry['option'] : []; + + if ('json-ld-1.0' === ($entryOptions['specVersion'] ?? null)) { + continue; + } + + $unknownOptions = array_diff(array_keys($entryOptions), self::OPTIONS, self::IGNORED_OPTIONS); + + if ([] !== $unknownOptions) { + throw new \RuntimeException(\sprintf('The test "%s" sets options this provider does not know: %s.', $entry['@id'], implode(', ', $unknownOptions))); + } + + $options = new ProcessorOptions( + base: \is_string($entryOptions['base'] ?? null) ? $entryOptions['base'] : self::BASE_IRI . $entry['input'], + expandContext: \is_string($entryOptions['expandContext'] ?? null) ? self::BASE_IRI . $entryOptions['expandContext'] : null, + processingMode: 'json-ld-1.0' === ($entryOptions['processingMode'] ?? null) ? Context::PROCESSING_MODE_10 : Context::PROCESSING_MODE_11, + produceGeneralizedRdf: true === ($entryOptions['produceGeneralizedRdf'] ?? false), + rdfDirection: \is_string($entryOptions['rdfDirection'] ?? null) ? $entryOptions['rdfDirection'] : null, + useNativeTypes: true === ($entryOptions['useNativeTypes'] ?? false), + useRdfType: true === ($entryOptions['useRdfType'] ?? false), + ); + + yield $entry['@id'] => [ + 'input' => self::read($entry['input']), + 'expect' => \is_string($entry['expect'] ?? null) ? self::read($entry['expect']) : null, + 'errorCode' => \is_string($entry['expectErrorCode'] ?? null) ? $entry['expectErrorCode'] : null, + 'options' => $options, + ]; + } + } + + /** + * Where a file of the test suite is, given its path in the manifest. The + * RDF suites keep the upstream layout; the few files they borrow from the + * other suites are filed by kind ("expand/er56-in.jsonld" is in + * "expand/input/"). + */ + public static function fixturePath(string $path): string + { + $file = \sprintf('%s/%s', AbstractJsonLdTestCase::DATA_PATH, $path); + + if (is_file($file)) { + return $file; + } + + foreach (['-in.jsonld' => 'input', '-out.jsonld' => 'output', '-context.jsonld' => 'context'] as $suffix => $directory) { + if (str_ends_with($path, $suffix)) { + return \sprintf('%s/%s/%s/%s', AbstractJsonLdTestCase::DATA_PATH, \dirname($path), $directory, basename($path)); + } + } + + return $file; + } + + private static function read(string $path): string + { + $content = @file_get_contents(self::fixturePath($path)); + + if (false === $content) { + throw new \RuntimeException(\sprintf('The fixture "%s" could not be read.', $path)); + } + + return $content; + } +} diff --git a/tests/Algorithms/Rdf/NQuadsTest.php b/tests/Algorithms/Rdf/NQuadsTest.php new file mode 100644 index 000000000..4e534d0da --- /dev/null +++ b/tests/Algorithms/Rdf/NQuadsTest.php @@ -0,0 +1,133 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\BlankNode; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Iri; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Literal; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Quad; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfDataset; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfVocabulary; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +#[Group('rdf')] +class NQuadsTest extends TestCase +{ + public function testItReadsEveryKindOfTerm(): void + { + $dataset = (new NQuadsParser())->parse(<<<'NQUADS' + # a comment, then an empty line + + . + _:b0 "plain" . # trailing comment + _:b0 "bonjour"@fr-FR . + "1"^^ _:g . + NQUADS); + + $this->assertEquals([ + new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Iri('http://example.com/o')), + new Quad(new BlankNode('_:b0'), new Iri('http://example.com/p'), new Literal('plain')), + new Quad(new BlankNode('_:b0'), new Iri('http://example.com/p'), new Literal('bonjour', RdfVocabulary::RDF_LANG_STRING, 'fr-FR'), new Iri('http://example.com/g')), + new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal('1', RdfVocabulary::XSD_INTEGER), new BlankNode('_:g')), + ], $dataset->quads()); + } + + public function testItUnescapesLiteralsAndIris(): void + { + $dataset = (new NQuadsParser())->parse(' "a\tb\nc \"d\" \\\\ \u00E9 \U0001F600" .'); + $quad = $dataset->quads()[0]; + + $this->assertEquals(new Iri('http://example.com/é'), $quad->subject); + $this->assertEquals(new Literal("a\tb\nc \"d\" \\ é 😀"), $quad->object); + } + + public function testItReadsABlankNodeEndingTheStatement(): void + { + $dataset = (new NQuadsParser())->parse('_:a.b _:c.'); + + $this->assertEquals(new BlankNode('_:a.b'), $dataset->quads()[0]->subject); + $this->assertEquals(new BlankNode('_:c'), $dataset->quads()[0]->object); + } + + public function testItReadsABlankNodePredicate(): void + { + $dataset = (new NQuadsParser())->parse('_:s _:p _:o .'); + + $this->assertEquals(new BlankNode('_:p'), $dataset->quads()[0]->predicate); + } + + #[DataProvider('provideInvalidStatements')] + public function testItRefusesWhatIsNotAStatement(string $statement): void + { + $this->expectException(JsonLdException::class); + + (new NQuadsParser())->parse($statement); + } + + /** + * @return iterable + */ + public static function provideInvalidStatements(): iterable + { + yield 'no final dot' => [' ']; + yield 'literal subject' => ['"s" .']; + yield 'literal predicate' => [' "p" .']; + yield 'two terms' => [' .']; + yield 'unterminated literal' => [' "o .']; + yield 'unknown escape' => [' "\q" .']; + yield 'space in an IRI' => [' "o" .']; + } + + public function testItWritesCanonicalStatements(): void + { + $dataset = new RdfDataset([ + new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal("line\nbreak \"quoted\" \\ é")), + new Quad(new BlankNode('_:b0'), new Iri('http://example.com/p'), new Literal('bonjour', RdfVocabulary::RDF_LANG_STRING, 'fr'), new Iri('http://example.com/g')), + new Quad(new BlankNode('_:b0'), new Iri('http://example.com/p'), new Literal('1.0E0', RdfVocabulary::XSD_DOUBLE)), + ]); + + $this->assertSame( + <<<'NQUADS' + "line\nbreak \"quoted\" \\ é" . + _:b0 "bonjour"@fr . + _:b0 "1.0E0"^^ . + + NQUADS, + NQuadsSerializer::serialize($dataset), + ); + } + + public function testADatasetIsASet(): void + { + $dataset = new RdfDataset(); + $dataset->add(new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal('o'))); + $dataset->add(new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal('o'))); + $dataset->add(new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal('o'), new Iri('http://example.com/g'))); + + $this->assertCount(2, $dataset); + $this->assertCount(2, iterator_to_array($dataset)); + } + + public function testWhatIsWrittenReadsBackTheSame(): void + { + $dataset = new RdfDataset([ + new Quad(new BlankNode('_:b0'), new BlankNode('_:b1'), new Literal("tab\t, feed\f, return\r, quote\", backslash\\"), new BlankNode('_:b2')), + ]); + + $this->assertEquals($dataset->quads(), (new NQuadsParser())->parse(NQuadsSerializer::serialize($dataset))->quads()); + } +} diff --git a/tests/Algorithms/Rdf/RdfDatasetIsomorphism.php b/tests/Algorithms/Rdf/RdfDatasetIsomorphism.php new file mode 100644 index 000000000..151d4bbd8 --- /dev/null +++ b/tests/Algorithms/Rdf/RdfDatasetIsomorphism.php @@ -0,0 +1,235 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\BlankNode; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Iri; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Literal; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfDataset; + +/** + * Tells whether two RDF datasets are the same up to the labels of their blank + * nodes, which is how the W3C test suite asks a toRdf result to be compared. + * + * The blank nodes are first told apart by what surrounds them, then a + * backtracking search looks for a one to one mapping that turns one dataset + * into the other. + * + * @phpstan-type Term array{bool, string} + * @phpstan-type Statement array{Term, Term, Term, Term} + */ +final class RdfDatasetIsomorphism +{ + public static function areIsomorphic(RdfDataset $first, RdfDataset $second): bool + { + $firstStatements = self::statements($first); + $secondStatements = self::statements($second); + + if (\count($firstStatements) !== \count($secondStatements)) { + return false; + } + + $firstColors = self::colors($firstStatements); + $secondColors = self::colors($secondStatements); + + $firstClasses = array_count_values($firstColors); + $secondClasses = array_count_values($secondColors); + ksort($firstClasses); + ksort($secondClasses); + + if ($firstClasses !== $secondClasses) { + return false; + } + + // The rarest colors first: they leave the fewest candidates to try. + $blankNodes = array_keys($firstColors); + usort($blankNodes, static fn (string $a, string $b): int => [$firstClasses[$firstColors[$a]], $a] <=> [$firstClasses[$firstColors[$b]], $b]); + + $target = []; + + foreach ($secondStatements as $statement) { + $target[self::writtenKey($statement)] = true; + } + + return self::search($blankNodes, 0, [], [], $firstColors, $secondColors, $firstStatements, $target); + } + + /** + * @param list $blankNodes + * @param array $mapping + * @param array $used + * @param array $firstColors + * @param array $secondColors + * @param list $statements + * @param array $target + */ + private static function search(array $blankNodes, int $index, array $mapping, array $used, array $firstColors, array $secondColors, array $statements, array $target): bool + { + foreach ($statements as $statement) { + $key = self::key($statement, $mapping); + + if (null !== $key && !\array_key_exists($key, $target)) { + return false; + } + } + + if (!\array_key_exists($index, $blankNodes)) { + return true; + } + + $blankNode = $blankNodes[$index]; + + foreach ($secondColors as $candidate => $color) { + if ($color !== $firstColors[$blankNode] || \array_key_exists($candidate, $used)) { + continue; + } + + if (self::search($blankNodes, $index + 1, $mapping + [$blankNode => $candidate], $used + [$candidate => true], $firstColors, $secondColors, $statements, $target)) { + return true; + } + } + + return false; + } + + /** + * A color per blank node, refined until the blank nodes that can be told + * apart are: it only depends on the shape of the dataset, never on a label. + * + * @param list $statements + * + * @return array + */ + private static function colors(array $statements): array + { + $colors = []; + + foreach ($statements as $statement) { + foreach ($statement as [$isBlankNode, $value]) { + if ($isBlankNode) { + $colors[$value] = ''; + } + } + } + + for ($round = 0; $round <= \count($colors); ++$round) { + $signatures = array_fill_keys(array_keys($colors), []); + + foreach ($statements as $statement) { + foreach ($statement as [$isBlankNode, $value]) { + if (!$isBlankNode) { + continue; + } + + $parts = []; + + foreach ($statement as [$isOtherBlankNode, $other]) { + $parts[] = match (true) { + !$isOtherBlankNode => 'G' . $other, + $other === $value => 'S', + default => 'B' . $colors[$other], + }; + } + + $signatures[$value][] = implode("\x1F", $parts); + } + } + + $refined = []; + + foreach ($signatures as $blankNode => $signature) { + sort($signature); + $refined[(string) $blankNode] = hash('xxh128', implode("\x1E", $signature)); + } + + if (\count(array_unique($refined)) === \count(array_unique($colors))) { + return $refined; + } + + $colors = $refined; + } + + return $colors; + } + + /** + * The identity of a statement once its blank nodes are renamed, or null + * when it holds a blank node the mapping does not cover yet. + * + * @param Statement $statement + * @param array $mapping + */ + private static function key(array $statement, array $mapping): ?string + { + $parts = []; + + foreach ($statement as [$isBlankNode, $value]) { + if (!$isBlankNode) { + $parts[] = 'G' . $value; + + continue; + } + + if (!\array_key_exists($value, $mapping)) { + return null; + } + + $parts[] = 'B' . $mapping[$value]; + } + + return implode("\x1F", $parts); + } + + /** + * The identity of a statement as it is written, blank node labels included. + * + * @param Statement $statement + */ + private static function writtenKey(array $statement): string + { + $parts = []; + + foreach ($statement as [$isBlankNode, $value]) { + $parts[] = ($isBlankNode ? 'B' : 'G') . $value; + } + + return implode("\x1F", $parts); + } + + /** + * @return list + */ + private static function statements(RdfDataset $dataset): array + { + $statements = []; + + foreach ($dataset->quads() as $quad) { + $statements[] = [self::term($quad->subject), self::term($quad->predicate), self::term($quad->object), self::term($quad->graph)]; + } + + return $statements; + } + + /** + * @return Term + */ + private static function term(Iri|BlankNode|Literal|null $term): array + { + return match (true) { + null === $term => [false, ''], + $term instanceof BlankNode => [true, $term->label], + $term instanceof Iri => [false, '<' . $term->value . '>'], + // Language tags are case insensitive. + default => [false, json_encode([$term->value, $term->datatype, null === $term->language ? null : strtolower($term->language)], \JSON_THROW_ON_ERROR)], + }; + } +} diff --git a/tests/Algorithms/Rdf/W3cFixtureDocumentLoader.php b/tests/Algorithms/Rdf/W3cFixtureDocumentLoader.php new file mode 100644 index 000000000..a7538e877 --- /dev/null +++ b/tests/Algorithms/Rdf/W3cFixtureDocumentLoader.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\ContextProcessingException; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\DocumentLoaderInterface; + +/** + * Serves the documents the W3C test suite hosts from the copy downloaded at + * the pinned commit: the tests then run offline, against the very revision + * their manifest comes from. Anything else is refused. + */ +final class W3cFixtureDocumentLoader implements DocumentLoaderInterface +{ + public function load(string $url): \stdClass + { + $path = (string) preg_replace('/[?#].*$/', '', $url); + + if (!str_starts_with($path, ManifestTestProvider::BASE_IRI) || str_contains($path, '..')) { + throw new ContextProcessingException('loading remote context failed'); + } + + $file = ManifestTestProvider::fixturePath(substr($path, \strlen(ManifestTestProvider::BASE_IRI))); + + if (!is_file($file)) { + throw new ContextProcessingException('loading remote context failed'); + } + + $document = json_decode((string) file_get_contents($file)); + + if (!$document instanceof \stdClass) { + throw new ContextProcessingException('invalid remote context'); + } + + return $document; + } + + public function getCacheNamespace(): string + { + return 'w3c-fixtures'; + } +} diff --git a/tests/Algorithms/ToRdfTest.php b/tests/Algorithms/ToRdfTest.php new file mode 100644 index 000000000..9d502ce6f --- /dev/null +++ b/tests/Algorithms/ToRdfTest.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms; + +use JoliCode\StructuredData\JsonLd\Algorithms; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use JoliCode\StructuredData\Tests\Algorithms\Rdf\ManifestTestProvider; +use JoliCode\StructuredData\Tests\Algorithms\Rdf\RdfDatasetIsomorphism; +use JoliCode\StructuredData\Tests\Algorithms\Rdf\W3cFixtureDocumentLoader; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * @see https://w3c.github.io/json-ld-api/tests/toRdf-manifest.html + */ +#[Group('toRdf')] +class ToRdfTest extends TestCase +{ + #[DataProvider('provideManifestEntries')] + public function testToRdf(string $input, ?string $expect, ?string $errorCode, ProcessorOptions $options): void + { + $converter = new ToRdfConverter(documentLoader: new W3cFixtureDocumentLoader()); + + if (null !== $errorCode) { + try { + $converter->toRdf($input, $options); + } catch (JsonLdException $exception) { + $this->assertSame($errorCode, $exception->getMessage()); + + return; + } + + $this->fail(\sprintf('An exception was expected for this test but none were thrown. Expected error message was : %s', $errorCode)); + } + + $dataset = $converter->toRdf($input, $options); + $parser = new NQuadsParser(); + $serialized = NQuadsSerializer::serialize($dataset); + + // What is written must read back as the same dataset, and this is all a + // syntax test asks for. + $this->assertTrue(RdfDatasetIsomorphism::areIsomorphic($dataset, $parser->parse($serialized)), 'The dataset does not survive its own serialization.'); + + if (null !== $expect) { + $this->assertTrue( + RdfDatasetIsomorphism::areIsomorphic($parser->parse($expect), $dataset), + \sprintf("The datasets are not isomorphic.\nExpected:\n%s\nActual:\n%s", $expect, $serialized), + ); + } + } + + /** + * @return iterable + */ + public static function provideManifestEntries(): iterable + { + return ManifestTestProvider::provide(Algorithms::TO_RDF->value); + } +} From c3eb7ea778403c8dced12d9edf2797b547f997ca Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sat, 21 Nov 2026 11:38:08 +0100 Subject: [PATCH 05/10] Add toRdf and fromRdf benchmarks and refresh the benchmark figures --- BENCHMARKS.md | 60 +++++--- .../Benchmark/AbstractJsonLdBench.php | 16 ++- tests/Algorithms/Benchmark/FromRdfBench.php | 128 ++++++++++++++++++ tests/Algorithms/Benchmark/ToRdfBench.php | 110 +++++++++++++++ 4 files changed, 289 insertions(+), 25 deletions(-) create mode 100644 tests/Algorithms/Benchmark/FromRdfBench.php create mode 100644 tests/Algorithms/Benchmark/ToRdfBench.php diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 052001e52..390b36309 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -1,7 +1,8 @@ # Benchmarks -The figures below come from `castor qa:bench:all`, run on 2026-11-13 on a developer -laptop, with PHP 8.5 in CLI, opcache and JIT disabled. They are +The figures below come from `castor qa:bench:all`, run on 2026-11-21 on a developer +laptop, with PHP 8.5 in CLI, opcache and JIT disabled, and Composer's optimized +autoloader. They are [PHPBench](https://github.com/phpbench/phpbench) *mode* values: the most frequent measurement over the iterations, with the relative standard deviation next to it. Memory is the peak of the benchmark process. Take them as orders of magnitude: the @@ -24,9 +25,9 @@ content-keyed cache can serve them. | Scenario | Document | Time per document | Peak memory | | --- | --- | --- | --- | -| 25 distinct variants of the Google *Book* fixture | 9 KB JSON-LD, 10 nested types | 12.7 ms | 20.6 MB | +| 25 distinct variants of the Google *Book* fixture | 9 KB JSON-LD, 10 nested types | 13.2 ms | 20.8 MB | -The 25 documents took 318 ms in total (±0.25 %). +The 25 documents took 330 ms in total (±2.36 %). ### The same document, again and again @@ -37,12 +38,12 @@ costs. | Document | Size | Time per audit | Peak memory | | --- | --- | --- | --- | -| schema.org fixture, a single type | 0.4 KB JSON-LD | 1.5 ms | 5.2 MB | -| schema.org fixture, nested types | 6 KB JSON-LD | 3.3 ms | 5.8 MB | -| Google *Book* fixture | 9 KB JSON-LD | 12.6 ms | 8.1 MB | -| jolicode.com homepage | 139 KB HTML | 6.8 ms | 6.6 MB | -| jolicampus.com homepage | 95 KB HTML | 5.5 ms | 6.5 MB | -| Google structured data introduction | 187 KB HTML | 10.5 ms | 6.5 MB | +| schema.org fixture, a single type | 0.4 KB JSON-LD | 1.6 ms | 5.2 MB | +| schema.org fixture, nested types | 6 KB JSON-LD | 4.0 ms | 6.2 MB | +| Google *Book* fixture | 9 KB JSON-LD | 13.1 ms | 8.2 MB | +| jolicode.com homepage | 139 KB HTML | 7.1 ms | 6.6 MB | +| jolicampus.com homepage | 95 KB HTML | 5.9 ms | 6.5 MB | +| Google structured data introduction | 187 KB HTML | 10.9 ms | 6.6 MB | The HTML pages are real pages, downloaded by `castor qa:phpunit:download-fixtures` from hosts JoliCode owns or operates (plus the Google documentation page), and never @@ -56,18 +57,28 @@ processor benchmarks measure the context processing step alone. | Algorithm | Input | Time | Peak memory | | --- | --- | --- | --- | | Context processing | inline context | 11 µs | 3.9 MB | -| Context processing | scoped contexts | 24 µs | 3.9 MB | +| Context processing | scoped contexts | 25 µs | 3.9 MB | | Context processing | nested contexts | 12 µs | 3.9 MB | | Expansion | minimal document (`expand/0002`) | 224 µs | 3.9 MB | -| Expansion | context-heavy document (`expand/0036`) | 409 µs | 3.9 MB | -| Expansion | nested `@graph` (`expand/pr25`) | 829 µs | 3.9 MB | -| Expansion | 8 nodes each repeating the schema.org context | 3.1 ms | 5.1 MB | +| Expansion | context-heavy document (`expand/0036`) | 412 µs | 3.9 MB | +| Expansion | nested `@graph` (`expand/pr25`) | 837 µs | 3.9 MB | +| Expansion | 8 nodes each repeating the schema.org context | 3.2 ms | 5.1 MB | | Compaction | inline context | 215 µs | 3.9 MB | -| Compaction | into the schema.org context | 13.4 ms | 10.2 MB | -| Flattening | minimal document | 266 µs | 3.9 MB | +| Compaction | into the schema.org context | 13.8 ms | 10.2 MB | +| Flattening | minimal document | 264 µs | 3.9 MB | | Flattening | nested lists | 600 µs | 3.9 MB | -| Framing | by type, schema.org context | 16.2 ms | 10.5 MB | -| Framing | embedded node, schema.org context | 16.2 ms | 10.5 MB | +| Framing | by type, schema.org context | 16.3 ms | 10.5 MB | +| Framing | embedded node, schema.org context | 16.3 ms | 10.5 MB | +| Deserialization to RDF | minimal document (`toRdf/0002`) | 126 µs | 3.9 MB | +| Deserialization to RDF | list (`toRdf/0036`) | 182 µs | 3.9 MB | +| Deserialization to RDF | nested `@graph` (`toRdf/pr25`) | 987 µs | 3.9 MB | +| Deserialization to RDF | JSON literal (`toRdf/js12`) | 182 µs | 3.9 MB | +| Deserialization to RDF | 8 schema.org nodes, written as N-Quads | 1.5 ms | 5.2 MB | +| Serialization from RDF | minimal dataset (`fromRdf/0002`) | 87 µs | 3.9 MB | +| Serialization from RDF | lists (`fromRdf/li03`) | 274 µs | 3.9 MB | +| Serialization from RDF | native types (`fromRdf/0027`) | 184 µs | 3.9 MB | +| Serialization from RDF | 1,600 statements, read from N-Quads | 15.7 ms | 6.4 MB | +| Serialization from RDF | the same 1,600 statements, already parsed | 5.6 ms | 5.3 MB | Compaction into the schema.org context and framing with it both cost around 15 ms: that is the price of building the inverse context of the roughly 3,000 schema.org @@ -76,18 +87,29 @@ is cheap in comparison, because the processed context is served from the static vocabulary files the library ships with. The "repeated remote context" subject is the regression guard for that path. +The deserialization to RDF is an expansion followed by the node map generation: on the +nested `@graph` document it costs 18 % more than the expansion alone. The serialization from RDF takes an +`RdfDataset` or N-Quads: on the 1,600 statements dataset, reading the N-Quads is two +thirds of the time (about 6 µs per statement), the algorithm itself the last third +(about 3.5 µs per statement). + ## Reproducing ```bash castor qa:install # phpbench and the other QA tools castor qa:phpunit:prepare # the W3C test suites castor qa:phpunit:download-fixtures # the HTML pages +composer dump-autoload -o # the optimized autoloader the figures are taken with castor qa:bench:all ``` `castor qa:bench:validators -d` additionally breaks the HTML pipeline down step by step (format detection, extraction, parsing, mapping, validation); it is slow. +The autoloader matters: without the optimized class map, the audits of a single document +are 2 to 10 % slower and the peak memory figures are 1.3 to 3 MB lower, the class map of +the 3,000 generated vocabulary classes not being loaded. + For finer time units than the default seconds, call PHPBench directly: ```bash @@ -95,5 +117,5 @@ tools/phpbench/vendor/bin/phpbench run tests/Algorithms/Benchmark --report=reada tools/phpbench/vendor/bin/phpbench run tests/Validation/Benchmark/JsonLdValidatorBench.php tests/Validation/Benchmark/WorkerValidationBench.php --report=readable --time-unit=milliseconds ``` -For the record, the full PHPUnit suite (1,496 tests, 3,317 assertions, W3C suites +For the record, the full PHPUnit suite (2,175 tests, 4,544 assertions, W3C suites included) runs in about 20 seconds on the same machine. diff --git a/tests/Algorithms/Benchmark/AbstractJsonLdBench.php b/tests/Algorithms/Benchmark/AbstractJsonLdBench.php index 8b44cc74e..258e96382 100644 --- a/tests/Algorithms/Benchmark/AbstractJsonLdBench.php +++ b/tests/Algorithms/Benchmark/AbstractJsonLdBench.php @@ -19,12 +19,16 @@ abstract protected function getAlgorithmName(): string; protected function loadJson(string $filename): string { - $filePath = \sprintf( - '%s/%s/input/%s', - static::DATA_PATH, - $this->getAlgorithmName(), - $filename, - ); + return $this->loadFixture(\sprintf('%s/input/%s', $this->getAlgorithmName(), $filename)); + } + + /** + * Loads a fixture by its path in the test suite. The RDF suites keep the + * upstream layout, where the files of a suite are not filed by kind. + */ + protected function loadFixture(string $path): string + { + $filePath = \sprintf('%s/%s', static::DATA_PATH, $path); $content = file_get_contents($filePath); if (false === $content) { diff --git a/tests/Algorithms/Benchmark/FromRdfBench.php b/tests/Algorithms/Benchmark/FromRdfBench.php new file mode 100644 index 000000000..3d9f98813 --- /dev/null +++ b/tests/Algorithms/Benchmark/FromRdfBench.php @@ -0,0 +1,128 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Benchmark; + +use JoliCode\StructuredData\JsonLd\Algorithms; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfDataset; + +class FromRdfBench extends AbstractJsonLdBench +{ + public const LARGE_DATASET_NODES = 200; + + private readonly string $largeNQuads; + private readonly RdfDataset $largeDataset; + + public function __construct( + private readonly FromRdfConverter $converter = new FromRdfConverter(), + ) { + $this->largeNQuads = self::buildLargeNQuads(); + $this->largeDataset = (new NQuadsParser())->parse($this->largeNQuads); + } + + /** + * @Revs(50) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchMinimalDatasetSerialization(): void + { + $this->serializeNQuadsFile('0002-in.nq'); + } + + /** + * @Revs(50) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchListSerialization(): void + { + $this->serializeNQuadsFile('li03-in.nq'); + } + + /** + * @Revs(50) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchNativeTypesSerialization(): void + { + $this->serializeNQuadsFile('0027-in.nq', new ProcessorOptions(useNativeTypes: true)); + } + + /** + * 200 nodes of 8 statements each, a two-item list among them, read from + * N-Quads: the parsing is part of the measure. + * + * @Revs(10) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchLargeNQuadsSerialization(): void + { + $this->converter->fromRdf($this->largeNQuads); + } + + /** + * The same dataset, already parsed: the algorithm alone. + * + * @Revs(10) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchLargeDatasetSerialization(): void + { + $this->converter->fromRdf($this->largeDataset); + } + + protected function getAlgorithmName(): string + { + return Algorithms::FROM_RDF->value; + } + + private function serializeNQuadsFile(string $filename, ProcessorOptions $options = new ProcessorOptions()): void + { + $this->converter->fromRdf($this->loadFixture(\sprintf('%s/%s', $this->getAlgorithmName(), $filename)), $options); + } + + private static function buildLargeNQuads(): string + { + $rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; + $lines = []; + + for ($i = 0; $i < self::LARGE_DATASET_NODES; ++$i) { + $subject = \sprintf('', $i); + $lines[] = \sprintf('%s <%stype> .', $subject, $rdf); + $lines[] = \sprintf('%s "person %d"@en .', $subject, $i); + $lines[] = \sprintf('%s "1.75E0"^^ .', $subject); + $lines[] = \sprintf('%s _:l%da .', $subject, $i); + $lines[] = \sprintf('_:l%da <%sfirst> .', $i, $rdf); + $lines[] = \sprintf('_:l%da <%srest> _:l%db .', $i, $rdf, $i); + $lines[] = \sprintf('_:l%db <%sfirst> "a friend" .', $i, $rdf); + $lines[] = \sprintf('_:l%db <%srest> <%snil> .', $i, $rdf, $rdf); + } + + return implode("\n", $lines) . "\n"; + } +} diff --git a/tests/Algorithms/Benchmark/ToRdfBench.php b/tests/Algorithms/Benchmark/ToRdfBench.php new file mode 100644 index 000000000..96076b28a --- /dev/null +++ b/tests/Algorithms/Benchmark/ToRdfBench.php @@ -0,0 +1,110 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Benchmark; + +use JoliCode\StructuredData\JsonLd\Algorithms; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; + +class ToRdfBench extends AbstractJsonLdBench +{ + public function __construct( + private readonly ToRdfConverter $converter = new ToRdfConverter(), + ) { + } + + /** + * @Revs(50) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchMinimalDocumentDeserialization(): void + { + $this->deserializeJsonFile('0002-in.jsonld'); + } + + /** + * @Revs(50) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchListDeserialization(): void + { + $this->deserializeJsonFile('0036-in.jsonld'); + } + + /** + * @Revs(50) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchNestedGraphDeserialization(): void + { + $this->deserializeJsonFile('pr25-in.jsonld'); + } + + /** + * A JSON literal is written in its canonical form (RFC 8785), numbers + * included: this is the one value the deserialization has to compute. + * + * @Revs(50) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchJsonLiteralDeserialization(): void + { + $this->deserializeJsonFile('js12-in.jsonld'); + } + + /** + * The whole way from a schema.org document to N-Quads: expansion with the + * schema.org context, node map, dataset, then serialization. + * + * @Revs(20) + * + * @Iterations(5) + * + * @RetryThreshold(2.0) + */ + public function benchSchemaOrgDocumentToNQuads(): string + { + $nodes = []; + + for ($i = 0; $i < 8; ++$i) { + $nodes[] = \sprintf('{"@id": "https://example.com/person/%1$d", "@type": "Person", "name": "person %1$d", "knows": {"@id": "https://example.com/person/0"}, "height": 1.75, "birthDate": "1990-01-01"}', $i); + } + + return NQuadsSerializer::serialize($this->converter->toRdf(\sprintf('{"@context": "https://schema.org", "@graph": [%s]}', implode(',', $nodes)))); + } + + protected function getAlgorithmName(): string + { + return Algorithms::TO_RDF->value; + } + + private function deserializeJsonFile(string $filename): void + { + $this->converter->toRdf( + $this->loadFixture(\sprintf('%s/%s', $this->getAlgorithmName(), $filename)), + new ProcessorOptions(base: $this->getBaseUrlForW3CTests($filename)), + ); + } +} From 755ac086158d836479be043b4ed9a67a551124df Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sun, 22 Nov 2026 17:08:56 +0100 Subject: [PATCH 06/10] Read microdata and RDFa with the HTML5 parser of PHP 8.4 --- CHANGELOG.md | 9 +++ src/Extraction/AbstractHtmlExtractor.php | 29 ++++--- src/Extraction/HtmlDocumentLoader.php | 27 ++----- src/Extraction/MicrodataExtractor.php | 56 ++++++-------- src/Extraction/RdfaExtractor.php | 52 ++++++------- src/Extraction/RdfaTermResolver.php | 22 +++--- tests/Validation/ExtractorTest.php | 98 ++++++++++++++++++++++++ 7 files changed, 193 insertions(+), 100 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cfa5eb9f..bbdd7b05b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,11 @@ - `ProcessorOptions::$produceGeneralizedRdf` now defaults to `false`, as the specification says. Nothing read the option before. +- **Breaking**: microdata and RDFa are read with the HTML5 parser of PHP 8.4 + (`Dom\HTMLDocument`) instead of libxml's HTML 4 one. `HtmlDocumentLoader::load()` returns a + `Dom\HTMLDocument` and no longer takes a format name, and the protected helpers of + `AbstractHtmlExtractor` take a `Dom\Element`: a custom HTML extractor has to follow. + Parsing a page is about 2.5 times faster. - Relative IRIs are resolved as RFC 3986 section 5.2 describes it and nothing more, as JSON-LD asks: non-ASCII characters are no longer percent-encoded, the host keeps its case, and a reference without a path keeps the dot segments of the base (`?y` against @@ -25,6 +30,10 @@ ### Fixed +- Microdata and RDFa values of a page that declares no encoding are read as UTF-8. They + were read as ISO-8859-1, which turned `Zoé` into `Zoé`. +- A microdata or RDFa element is located on the line its start tag opens on. It was + located on the line the tag ends on, wrong for a tag written over several lines. - Expansion reported `invalid @reverse property value` where the specification names the error `invalid reverse property value` (W3C test `expand#ter34`). - Flattening and framing merged a plain string into a language-tagged string holding the diff --git a/src/Extraction/AbstractHtmlExtractor.php b/src/Extraction/AbstractHtmlExtractor.php index 9f9d3c24d..9c5bed00f 100644 --- a/src/Extraction/AbstractHtmlExtractor.php +++ b/src/Extraction/AbstractHtmlExtractor.php @@ -14,7 +14,7 @@ /** * Base class for extractors that parse structured data from HTML DOM trees. * - * Provides shared helpers for loading an HTML document into a DOMDocument and + * Provides shared helpers for loading an HTML document into a Dom\HTMLDocument and * for building line-location hints for diagnostic messages. * Concrete subclasses must declare their format so that error messages remain * format-specific. @@ -34,13 +34,11 @@ protected function getFormatName(): string } /** - * Parses $body into a DOMDocument, suppressing libxml noise. - * - * @throws \RuntimeException when the HTML cannot be loaded at all + * Parses $body with the HTML5 parser, which never rejects a document. */ - protected function loadDocument(string $body): \DOMDocument + protected function loadDocument(string $body): \Dom\HTMLDocument { - return $this->documentLoader->load($body, $this->getFormatName()); + return $this->documentLoader->load($body); } /** @@ -67,12 +65,22 @@ protected function formatLineHint(array $lineNumbers): string : \sprintf(' at lines %s', implode(', ', $lineNumbers)); } + /** + * The line an element's start tag opens on, counted from 1. + * + * Dom\HTMLDocument counts lines from 0. + */ + protected static function lineOf(\Dom\Element $node): int + { + return $node->getLineNo() + 1; + } + /** * Encodes one extracted item into a JsonLdElement anchored on its DOM node. * * @throws ExtractionException when the item cannot be encoded */ - protected function encodeAsJsonLdElement(\DOMElement $node, mixed $item, string $encodeFailureMessage): JsonLdElement + protected function encodeAsJsonLdElement(\Dom\Element $node, mixed $item, string $encodeFailureMessage): JsonLdElement { $encoded = json_encode($item, \JSON_UNESCAPED_SLASHES); @@ -80,20 +88,21 @@ protected function encodeAsJsonLdElement(\DOMElement $node, mixed $item, string throw new ExtractionException($encodeFailureMessage); } - return new JsonLdElement(max(0, $node->getLineNo() - 1), 0, $encoded, $this->getFormat()); + // JsonLdElement counts lines from 0, as the parser does. + return new JsonLdElement($node->getLineNo(), 0, $encoded, $this->getFormat()); } /** * Reports that no element could be extracted, pointing at the candidate nodes. * - * @param array<\DOMElement> $nodes + * @param array<\Dom\Element> $nodes * * @throws ExtractionException */ protected function throwEmptyResult(array $nodes, string $message): never { $lineNumbers = array_values( - array_map(static fn (\DOMElement $node): int => $node->getLineNo(), $nodes), + array_map(static fn (\Dom\Element $node): int => self::lineOf($node), $nodes), ); throw new ExtractionException($message . $this->formatLineHint($lineNumbers) . '.', $this->formatRanges($lineNumbers)); diff --git a/src/Extraction/HtmlDocumentLoader.php b/src/Extraction/HtmlDocumentLoader.php index 321d6a270..c885de8b5 100644 --- a/src/Extraction/HtmlDocumentLoader.php +++ b/src/Extraction/HtmlDocumentLoader.php @@ -12,7 +12,7 @@ namespace JoliCode\StructuredData\Extraction; /** - * Parses an HTML body into a DOMDocument, memoizing the last parsed document. + * Parses an HTML body with PHP's HTML5 parser, memoizing the last parsed document. * * A single loader instance is shared by all the HTML-based extractors of an * ExtractorsContainer, so that when several extractors (microdata, RDFa) process @@ -26,34 +26,21 @@ class HtmlDocumentLoader { private ?string $lastBody = null; - private ?\DOMDocument $lastDocument = null; + private ?\Dom\HTMLDocument $lastDocument = null; /** - * Parses $body into a DOMDocument, suppressing libxml noise. + * Parses $body as HTML5: malformed markup is recovered from, never refused. * - * @param string $formatName a human-readable format name, used in error messages - * - * @throws ExtractionException when the HTML cannot be loaded at all + * The encoding is the one the page declares (BOM, then meta charset), and + * UTF-8 when it declares none. */ - public function load(string $body, string $formatName): \DOMDocument + public function load(string $body): \Dom\HTMLDocument { if ($this->lastBody === $body && null !== $this->lastDocument) { return $this->lastDocument; } - $document = new \DOMDocument(); - - set_error_handler(static fn (): bool => true); - - try { - $loaded = $document->loadHTML($body, \LIBXML_NOERROR | \LIBXML_NOWARNING | \LIBXML_NONET); - } finally { - restore_error_handler(); - } - - if (false === $loaded) { - throw new ExtractionException(\sprintf('Invalid %s document: malformed HTML content.', $formatName)); - } + $document = \Dom\HTMLDocument::createFromString($body, \LIBXML_NOERROR); $this->lastBody = $body; $this->lastDocument = $document; diff --git a/src/Extraction/MicrodataExtractor.php b/src/Extraction/MicrodataExtractor.php index f415d1ff4..87999d271 100644 --- a/src/Extraction/MicrodataExtractor.php +++ b/src/Extraction/MicrodataExtractor.php @@ -44,22 +44,16 @@ public function extractStructuredDataContent(string $body): array $document = $this->loadDocument($body); - $xpath = new \DOMXPath($document); + $xpath = new \Dom\XPath($document); $allItemScopes = $xpath->query('//*[@itemscope]'); - if (false === $allItemScopes) { - throw new ExtractionException('Invalid microdata document: could not query the HTML document.'); - } - if (0 === $allItemScopes->count()) { $candidateNodes = $xpath->query('//*[@itemtype or @itemprop]'); $candidateLines = []; - if (false !== $candidateNodes) { - foreach ($candidateNodes as $candidateNode) { - if ($candidateNode instanceof \DOMElement) { - $candidateLines[] = $candidateNode->getLineNo(); - } + foreach ($candidateNodes as $candidateNode) { + if ($candidateNode instanceof \Dom\Element) { + $candidateLines[] = self::lineOf($candidateNode); } } @@ -69,7 +63,7 @@ public function extractStructuredDataContent(string $body): array $topLevelItems = []; foreach ($allItemScopes as $itemScope) { - if (!$itemScope instanceof \DOMElement) { + if (!$itemScope instanceof \Dom\Element) { continue; } @@ -110,11 +104,11 @@ private function resetMemoization(): void $this->normalizedItemTypesCache = []; } - private function hasAncestorItemScope(\DOMElement $element): bool + private function hasAncestorItemScope(\Dom\Element $element): bool { $parent = $element->parentNode; - while ($parent instanceof \DOMElement) { + while ($parent instanceof \Dom\Element) { if ($parent->hasAttribute('itemscope')) { return true; } @@ -128,9 +122,9 @@ private function hasAncestorItemScope(\DOMElement $element): bool /** * @return array|null */ - private function extractItem(\DOMElement $itemElement, \DOMXPath $xpath): ?array + private function extractItem(\Dom\Element $itemElement, \Dom\XPath $xpath): ?array { - $itemTypeAttribute = trim($itemElement->getAttribute('itemtype')); + $itemTypeAttribute = trim($itemElement->getAttribute('itemtype') ?? ''); if ('' === $itemTypeAttribute) { return null; @@ -144,7 +138,7 @@ private function extractItem(\DOMElement $itemElement, \DOMXPath $xpath): ?array ]; if ($itemElement->hasAttribute('itemid')) { - $item['@id'] = trim($itemElement->getAttribute('itemid')); + $item['@id'] = trim($itemElement->getAttribute('itemid') ?? ''); } $properties = $this->extractProperties($itemElement, $xpath); @@ -205,12 +199,12 @@ private function normalizeItemTypes(string $itemTypeAttribute): string|array /** * @return array */ - private function extractProperties(\DOMElement $itemElement, \DOMXPath $xpath): array + private function extractProperties(\Dom\Element $itemElement, \Dom\XPath $xpath): array { $properties = []; foreach ($this->collectPropertyNodesForItem($itemElement) as $propertyNode) { - $propertyNames = preg_split('/\s+/', trim($propertyNode->getAttribute('itemprop'))); + $propertyNames = preg_split('/\s+/', trim($propertyNode->getAttribute('itemprop') ?? '')); if (!\is_array($propertyNames)) { continue; @@ -245,15 +239,15 @@ private function extractProperties(\DOMElement $itemElement, \DOMXPath $xpath): } /** - * @return array<\DOMElement> + * @return array<\Dom\Element> */ - private function collectPropertyNodesForItem(\DOMElement $itemElement): array + private function collectPropertyNodesForItem(\Dom\Element $itemElement): array { $propertyNodes = []; $stack = []; foreach ($itemElement->childNodes as $childNode) { - if ($childNode instanceof \DOMElement) { + if ($childNode instanceof \Dom\Element) { $stack[] = $childNode; } } @@ -271,7 +265,7 @@ private function collectPropertyNodesForItem(\DOMElement $itemElement): array } foreach ($node->childNodes as $childNode) { - if ($childNode instanceof \DOMElement) { + if ($childNode instanceof \Dom\Element) { $stack[] = $childNode; } } @@ -280,42 +274,42 @@ private function collectPropertyNodesForItem(\DOMElement $itemElement): array return $propertyNodes; } - private function extractPropertyValue(\DOMElement $propertyNode): ?string + private function extractPropertyValue(\Dom\Element $propertyNode): ?string { $tagName = strtolower($propertyNode->tagName); if ('meta' === $tagName && $propertyNode->hasAttribute('content')) { - return trim($propertyNode->getAttribute('content')); + return trim($propertyNode->getAttribute('content') ?? ''); } if (\in_array($tagName, ['audio', 'embed', 'iframe', 'img', 'source', 'track', 'video'], true) && $propertyNode->hasAttribute('src')) { - return trim($propertyNode->getAttribute('src')); + return trim($propertyNode->getAttribute('src') ?? ''); } if (\in_array($tagName, ['a', 'area', 'link'], true) && $propertyNode->hasAttribute('href')) { - return trim($propertyNode->getAttribute('href')); + return trim($propertyNode->getAttribute('href') ?? ''); } if ('object' === $tagName && $propertyNode->hasAttribute('data')) { - return trim($propertyNode->getAttribute('data')); + return trim($propertyNode->getAttribute('data') ?? ''); } if (\in_array($tagName, ['data', 'meter'], true) && $propertyNode->hasAttribute('value')) { - return trim($propertyNode->getAttribute('value')); + return trim($propertyNode->getAttribute('value') ?? ''); } if ('time' === $tagName && $propertyNode->hasAttribute('datetime')) { - return trim($propertyNode->getAttribute('datetime')); + return trim($propertyNode->getAttribute('datetime') ?? ''); } // The specification only reads "content" on , but Google reads it on // any element, and pages rely on it (a without href, // for instance). if ($propertyNode->hasAttribute('content')) { - return trim($propertyNode->getAttribute('content')); + return trim($propertyNode->getAttribute('content') ?? ''); } - $text = trim($propertyNode->textContent); + $text = trim($propertyNode->textContent ?? ''); return '' === $text ? null : $text; } diff --git a/src/Extraction/RdfaExtractor.php b/src/Extraction/RdfaExtractor.php index 0bc81c746..e4c5c8b4a 100644 --- a/src/Extraction/RdfaExtractor.php +++ b/src/Extraction/RdfaExtractor.php @@ -54,17 +54,13 @@ public function extractStructuredDataContent(string $body): array } $document = $this->loadDocument($body); - $xpath = new \DOMXPath($document); + $xpath = new \Dom\XPath($document); $candidateNodes = $xpath->query(self::RDFa_CANDIDATE_XPATH); - if (false === $candidateNodes) { - throw new ExtractionException('Invalid RDFa document: could not query the HTML document.'); - } - $schemaOrgCandidateNodes = []; foreach ($candidateNodes as $candidateNode) { - if (!$candidateNode instanceof \DOMElement) { + if (!$candidateNode instanceof \Dom\Element) { continue; } @@ -98,7 +94,7 @@ public function extractStructuredDataContent(string $body): array } if ([] === $topLevelSubjects) { - $candidateLines = array_map(static fn (\DOMElement $candidateNode): int => $candidateNode->getLineNo(), $schemaOrgCandidateNodes); + $candidateLines = array_map(static fn (\Dom\Element $candidateNode): int => self::lineOf($candidateNode), $schemaOrgCandidateNodes); throw new ExtractionException(\sprintf('Invalid RDFa document: at least one top-level schema.org subject with typeof is required%s.', $this->formatLineHint($candidateLines)), $this->formatRanges($candidateLines)); } @@ -140,14 +136,14 @@ private function containsSchemaOrgIri(string $body): bool * The test matches attribute syntax rather than bare substrings: a substring * test hits ordinary prose and unrelated markup ("about" alone matched 58% * of a 100-page sample, "property" 89% because of Open Graph meta tags), and - * every hit costs a full libxml parse of the document. + * every hit costs a full parse of the document. */ private function hasRdfaAttributeMarkers(string $body): bool { return 1 === preg_match('#\s(?:typeof|vocab)\s*=#i', $body); } - private function isSchemaOrgCandidate(\DOMElement $element): bool + private function isSchemaOrgCandidate(\Dom\Element $element): bool { $cacheKey = $this->termResolver->getNodeCacheKey($element); @@ -159,18 +155,18 @@ private function isSchemaOrgCandidate(\DOMElement $element): bool return $this->schemaOrgCandidateCache[$cacheKey] = true; } - $typeof = $element->getAttribute('typeof'); + $typeof = $element->getAttribute('typeof') ?? ''; if ('' !== $typeof && [] !== $this->termResolver->resolveTerms($typeof, $element)) { return $this->schemaOrgCandidateCache[$cacheKey] = true; } - $property = $element->getAttribute('property'); + $property = $element->getAttribute('property') ?? ''; return $this->schemaOrgCandidateCache[$cacheKey] = '' !== $property && [] !== $this->termResolver->resolveTerms($property, $element); } - private function isSchemaOrgSubject(\DOMElement $element): bool + private function isSchemaOrgSubject(\Dom\Element $element): bool { $cacheKey = $this->termResolver->getNodeCacheKey($element); @@ -178,16 +174,16 @@ private function isSchemaOrgSubject(\DOMElement $element): bool return $this->schemaOrgSubjectCache[$cacheKey]; } - $typeof = $element->getAttribute('typeof'); + $typeof = $element->getAttribute('typeof') ?? ''; return $this->schemaOrgSubjectCache[$cacheKey] = '' !== $typeof && [] !== $this->termResolver->resolveTerms($typeof, $element); } - private function hasAncestorSchemaOrgSubject(\DOMElement $element): bool + private function hasAncestorSchemaOrgSubject(\Dom\Element $element): bool { $parent = $element->parentNode; - while ($parent instanceof \DOMElement) { + while ($parent instanceof \Dom\Element) { if ($this->isSchemaOrgSubject($parent)) { return true; } @@ -201,9 +197,9 @@ private function hasAncestorSchemaOrgSubject(\DOMElement $element): bool /** * @return array|null */ - private function extractSubject(\DOMElement $subjectNode): ?array + private function extractSubject(\Dom\Element $subjectNode): ?array { - $types = $this->termResolver->resolveTerms($subjectNode->getAttribute('typeof'), $subjectNode); + $types = $this->termResolver->resolveTerms($subjectNode->getAttribute('typeof') ?? '', $subjectNode); if ([] === $types) { return null; @@ -230,12 +226,12 @@ private function extractSubject(\DOMElement $subjectNode): ?array /** * @return array */ - private function extractProperties(\DOMElement $subjectNode): array + private function extractProperties(\Dom\Element $subjectNode): array { $properties = []; foreach ($this->collectPropertyNodesForSubject($subjectNode) as $propertyNode) { - $propertyNames = $this->termResolver->resolveTerms($propertyNode->getAttribute('property'), $propertyNode); + $propertyNames = $this->termResolver->resolveTerms($propertyNode->getAttribute('property') ?? '', $propertyNode); if ([] === $propertyNames) { continue; @@ -266,15 +262,15 @@ private function extractProperties(\DOMElement $subjectNode): array } /** - * @return array<\DOMElement> + * @return array<\Dom\Element> */ - private function collectPropertyNodesForSubject(\DOMElement $subjectNode): array + private function collectPropertyNodesForSubject(\Dom\Element $subjectNode): array { $propertyNodes = []; $stack = []; foreach ($subjectNode->childNodes as $childNode) { - if ($childNode instanceof \DOMElement) { + if ($childNode instanceof \Dom\Element) { $stack[] = $childNode; } } @@ -293,7 +289,7 @@ private function collectPropertyNodesForSubject(\DOMElement $subjectNode): array } foreach ($node->childNodes as $childNode) { - if ($childNode instanceof \DOMElement) { + if ($childNode instanceof \Dom\Element) { $stack[] = $childNode; } } @@ -302,11 +298,11 @@ private function collectPropertyNodesForSubject(\DOMElement $subjectNode): array return $propertyNodes; } - private function extractSubjectIdentifier(\DOMElement $subjectNode): ?string + private function extractSubjectIdentifier(\Dom\Element $subjectNode): ?string { foreach (['about', 'resource', 'href', 'src'] as $attribute) { if ($subjectNode->hasAttribute($attribute)) { - $value = trim($subjectNode->getAttribute($attribute)); + $value = trim($subjectNode->getAttribute($attribute) ?? ''); if ('' !== $value) { return $value; @@ -317,11 +313,11 @@ private function extractSubjectIdentifier(\DOMElement $subjectNode): ?string return null; } - private function extractPropertyValue(\DOMElement $propertyNode): ?string + private function extractPropertyValue(\Dom\Element $propertyNode): ?string { foreach (['content', 'resource', 'href', 'src', 'datetime', 'value'] as $attribute) { if ($propertyNode->hasAttribute($attribute)) { - $value = trim($propertyNode->getAttribute($attribute)); + $value = trim($propertyNode->getAttribute($attribute) ?? ''); if ('' !== $value) { return $value; @@ -329,7 +325,7 @@ private function extractPropertyValue(\DOMElement $propertyNode): ?string } } - $normalizedText = preg_replace('/\s+/u', ' ', $propertyNode->textContent); + $normalizedText = preg_replace('/\s+/u', ' ', $propertyNode->textContent ?? ''); if (!\is_string($normalizedText)) { return null; diff --git a/src/Extraction/RdfaTermResolver.php b/src/Extraction/RdfaTermResolver.php index e1f11d422..5b021ed18 100644 --- a/src/Extraction/RdfaTermResolver.php +++ b/src/Extraction/RdfaTermResolver.php @@ -45,7 +45,7 @@ public function reset(): void /** * @return array */ - public function resolveTerms(string $attributeValue, \DOMElement $contextElement): array + public function resolveTerms(string $attributeValue, \Dom\Element $contextElement): array { if ('' === $attributeValue) { return []; @@ -79,7 +79,7 @@ public function resolveTerms(string $attributeValue, \DOMElement $contextElement return $this->resolvedTermsCache[$cacheKey] = array_values($resolvedTerms); } - public function resolveVocab(\DOMElement $contextElement): ?string + public function resolveVocab(\Dom\Element $contextElement): ?string { $cacheKey = $this->getNodeCacheKey($contextElement); @@ -89,19 +89,19 @@ public function resolveVocab(\DOMElement $contextElement): ?string $element = $contextElement; - while ($element instanceof \DOMElement) { + while ($element instanceof \Dom\Element) { if ($element->hasAttribute('vocab')) { - return $this->resolvedVocabCache[$cacheKey] = trim($element->getAttribute('vocab')); + return $this->resolvedVocabCache[$cacheKey] = trim($element->getAttribute('vocab') ?? ''); } $parent = $element->parentNode; - $element = $parent instanceof \DOMElement ? $parent : null; + $element = $parent instanceof \Dom\Element ? $parent : null; } return $this->resolvedVocabCache[$cacheKey] = null; } - public function getNodeCacheKey(\DOMElement $element): int + public function getNodeCacheKey(\Dom\Element $element): int { return spl_object_id($element); } @@ -111,7 +111,7 @@ public function isSchemaOrgVocab(?string $vocab): bool return \in_array($vocab, ['http://schema.org/', 'https://schema.org/'], true); } - private function resolveTerm(string $token, \DOMElement $contextElement): ?string + private function resolveTerm(string $token, \Dom\Element $contextElement): ?string { $token = trim($token); @@ -160,7 +160,7 @@ private function resolveTerm(string $token, \DOMElement $contextElement): ?strin /** * @return array */ - private function resolvePrefixMappings(\DOMElement $contextElement): array + private function resolvePrefixMappings(\Dom\Element $contextElement): array { $cacheKey = $this->getNodeCacheKey($contextElement); @@ -171,11 +171,11 @@ private function resolvePrefixMappings(\DOMElement $contextElement): array $ancestors = []; $element = $contextElement; - while ($element instanceof \DOMElement) { + while ($element instanceof \Dom\Element) { $ancestors[] = $element; $parent = $element->parentNode; - $element = $parent instanceof \DOMElement ? $parent : null; + $element = $parent instanceof \Dom\Element ? $parent : null; } $ancestors = array_reverse($ancestors); @@ -186,7 +186,7 @@ private function resolvePrefixMappings(\DOMElement $contextElement): array continue; } - preg_match_all('/([A-Za-z][\w-]*):\s*(\S+)/', $ancestor->getAttribute('prefix'), $matches, \PREG_SET_ORDER); + preg_match_all('/([A-Za-z][\w-]*):\s*(\S+)/', $ancestor->getAttribute('prefix') ?? '', $matches, \PREG_SET_ORDER); foreach ($matches as $match) { $prefixes[$match[1]] = $match[2]; diff --git a/tests/Validation/ExtractorTest.php b/tests/Validation/ExtractorTest.php index 41b65d2d2..d93e7cba1 100644 --- a/tests/Validation/ExtractorTest.php +++ b/tests/Validation/ExtractorTest.php @@ -11,6 +11,7 @@ namespace JoliCode\StructuredData\Tests\Validation; +use JoliCode\StructuredData\Extraction\ExtractionException; use JoliCode\StructuredData\Extraction\Extractor; use JoliCode\StructuredData\Extraction\ExtractorsContainer; use PHPUnit\Framework\Attributes\DataProvider; @@ -313,4 +314,101 @@ public function testItSurfacesAGenericExceptionWhenNoSupportedFormatIsDetected() $extractor->extract('

Hello world

'); } + + public function testItReadsMicrodataAsUtf8WhenThePageDeclaresNoEncoding(): void + { + $document = <<<'HTML' + + +
+ Zoé Müller 日本 +
+ + +HTML; + + $elements = (new Extractor())->extract($document); + + $this->assertCount(1, $elements); + $this->assertStringContainsString('"name":' . json_encode('Zoé Müller 日本'), $elements[0]->content); + } + + public function testItReadsRdfaAsUtf8WhenThePageDeclaresNoEncoding(): void + { + $document = <<<'HTML' + + +
+ Zoé Müller 日本 +
+ + +HTML; + + $elements = (new Extractor())->extract($document); + + $this->assertCount(1, $elements); + $this->assertStringContainsString('"name":' . json_encode('Zoé Müller 日本'), $elements[0]->content); + } + + public function testItHonoursTheEncodingThePageDeclares(): void + { + $document = mb_convert_encoding(<<<'HTML' + + + +
+ Zoé Müller +
+ + +HTML, 'ISO-8859-1', 'UTF-8'); + + $elements = (new Extractor())->extract($document); + + $this->assertCount(1, $elements); + $this->assertStringContainsString('"name":' . json_encode('Zoé Müller'), $elements[0]->content); + } + + public function testAnElementIsLocatedOnTheLineItsStartTagOpensOn(): void + { + $document = <<<'HTML' + + + +
+ Jane Doe +
+ + +HTML; + + $elements = (new Extractor())->extract($document); + + $this->assertCount(1, $elements); + // Lines of a JsonLdElement are counted from 0: the tag opens on the fourth line. + $this->assertSame(3, $elements[0]->startLine); + } + + public function testAMicrodataErrorPointsAtTheLineTheStartTagOpensOn(): void + { + $document = <<<'HTML' + + + + Jane Doe + + +HTML; + + $this->expectException(ExtractionException::class); + $this->expectExceptionMessage('no itemscope attribute at line 4.'); + + (new Extractor())->setExtractors(ExtractorsContainer::MICRODATA)->extract($document); + } } From a21a53d84ccb1547f50a0cbb2cda04396e68a853 Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sun, 22 Nov 2026 17:08:57 +0100 Subject: [PATCH 07/10] Keep a map holding only @graph as a graph object when it is an array item --- CHANGELOG.md | 2 ++ src/JsonLd/Algorithms/Expand/Expander.php | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbdd7b05b..9c3e2fddd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,8 @@ were read as ISO-8859-1, which turned `Zoé` into `Zoé`. - A microdata or RDFa element is located on the line its start tag opens on. It was located on the line the tag ends on, wrong for a tag written over several lines. +- Expanding an array that holds a map with nothing but `@graph` flattened that graph into + the array: it is now kept as a graph object, only the document itself being unwrapped. - Expansion reported `invalid @reverse property value` where the specification names the error `invalid reverse property value` (W3C test `expand#ter34`). - Flattening and framing merged a plain string into a language-tagged string holding the diff --git a/src/JsonLd/Algorithms/Expand/Expander.php b/src/JsonLd/Algorithms/Expand/Expander.php index 7db602f8a..93dda48b1 100644 --- a/src/JsonLd/Algorithms/Expand/Expander.php +++ b/src/JsonLd/Algorithms/Expand/Expander.php @@ -116,6 +116,7 @@ public function doExpand( Context $activeContext = new Context(), ?string $activeProperty = self::TOP_LEVEL_ACTIVE_PROPERTY, bool $fromMap = false, + bool $arrayItem = false, ): \stdClass|array|null { // 1 if (null === $element) { @@ -241,7 +242,9 @@ public function doExpand( } } - if (null === $activeProperty || self::TOP_LEVEL_ACTIVE_PROPERTY === $activeProperty) { + // Only the document itself: among the items of an array, a map holding + // nothing but @graph is a graph object, and stays one. + if (!$arrayItem && (null === $activeProperty || self::TOP_LEVEL_ACTIVE_PROPERTY === $activeProperty)) { if ( \is_object($result) && property_exists($result, Keyword::GRAPH->value) @@ -1220,6 +1223,7 @@ private function handleArrayElement( $activeContext, $activeProperty, $fromMap, + true, ); // 5.2.2 From 7a9b2e89de0925ca586f0c99245489751747ec7d Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sun, 22 Nov 2026 17:08:57 +0100 Subject: [PATCH 08/10] Load documents given as a URL, HTML pages included, and pass the W3C remote-doc and html suites --- .castor/earl.php | 12 + .castor/qa.php | 8 +- BENCHMARKS.md | 2 +- CHANGELOG.md | 35 +++ CONTRIBUTING.md | 9 +- docs/json-ld.md | 41 ++- docs/remote-contexts.md | 57 +++- src/JsonLd/Algorithms.php | 13 +- src/JsonLd/Algorithms/Compact/Compactor.php | 28 +- .../ContextProcessing/ContextCache.php | 11 +- .../Exception/DocumentLoadingException.php | 30 ++ src/JsonLd/Algorithms/Expand/Expander.php | 52 ++-- src/JsonLd/Algorithms/Flatten/Flattener.php | 31 +-- src/JsonLd/Algorithms/Frame/Framer.php | 28 +- .../Http/DocumentLoaderInterface.php | 28 +- .../Algorithms/Http/HtmlScriptExtractor.php | 150 ++++++++++ .../Algorithms/Http/HttpDocumentLoader.php | 213 ++++++++------ .../Algorithms/Http/LinkHeaderParser.php | 6 +- .../Algorithms/Http/LoadDocumentOptions.php | 42 +++ src/JsonLd/Algorithms/Http/RemoteDocument.php | 44 +++ .../Algorithms/JsonLd/ProcessorOptions.php | 8 +- src/JsonLd/Algorithms/Rdf/ToRdfConverter.php | 10 +- .../Services/InputDocumentResolver.php | 71 +++++ .../Algorithms/Services/ResolvedInput.php | 33 +++ tests/Algorithms/ContextProcessorTest.php | 6 +- tests/Algorithms/FromRdfTest.php | 2 +- tests/Algorithms/HtmlTest.php | 43 +++ .../Http/HtmlScriptExtractorTest.php | 150 ++++++++++ .../Http/HttpDocumentLoaderTest.php | 48 ++-- .../Http/RemoteDocumentLoadingTest.php | 261 ++++++++++++++++++ .../AbstractRemoteDocumentTestCase.php | 84 ++++++ .../Manifest/ManifestTestProvider.php | 193 +++++++++++++ .../Algorithms/Manifest/W3cFixtureServer.php | 78 ++++++ tests/Algorithms/Rdf/ManifestTestProvider.php | 126 --------- .../Rdf/W3cFixtureDocumentLoader.php | 51 ---- .../RemoteContextPolicyIntegrationTest.php | 4 +- tests/Algorithms/RemoteDocTest.php | 43 +++ tests/Algorithms/ToRdfTest.php | 6 +- tests/Validation/SnapshotDocumentLoader.php | 6 +- 39 files changed, 1655 insertions(+), 408 deletions(-) create mode 100644 src/JsonLd/Algorithms/Exception/DocumentLoadingException.php create mode 100644 src/JsonLd/Algorithms/Http/HtmlScriptExtractor.php create mode 100644 src/JsonLd/Algorithms/Http/LoadDocumentOptions.php create mode 100644 src/JsonLd/Algorithms/Http/RemoteDocument.php create mode 100644 src/JsonLd/Algorithms/Services/InputDocumentResolver.php create mode 100644 src/JsonLd/Algorithms/Services/ResolvedInput.php create mode 100644 tests/Algorithms/HtmlTest.php create mode 100644 tests/Algorithms/Http/HtmlScriptExtractorTest.php create mode 100644 tests/Algorithms/Http/RemoteDocumentLoadingTest.php create mode 100644 tests/Algorithms/Manifest/AbstractRemoteDocumentTestCase.php create mode 100644 tests/Algorithms/Manifest/ManifestTestProvider.php create mode 100644 tests/Algorithms/Manifest/W3cFixtureServer.php delete mode 100644 tests/Algorithms/Rdf/ManifestTestProvider.php delete mode 100644 tests/Algorithms/Rdf/W3cFixtureDocumentLoader.php create mode 100644 tests/Algorithms/RemoteDocTest.php diff --git a/.castor/earl.php b/.castor/earl.php index 93a3184fd..825a6646e 100644 --- a/.castor/earl.php +++ b/.castor/earl.php @@ -78,6 +78,18 @@ function earlSuites(): array 'iri' => 'https://w3c.github.io/json-ld-api/tests/fromRdf-manifest', 'byId' => true, ], + 'RemoteDocTest' => [ + 'name' => 'remote-doc', + 'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/remote-doc-manifest.jsonld', + 'iri' => 'https://w3c.github.io/json-ld-api/tests/remote-doc-manifest', + 'byId' => true, + ], + 'HtmlTest' => [ + 'name' => 'html', + 'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/html-manifest.jsonld', + 'iri' => 'https://w3c.github.io/json-ld-api/tests/html-manifest', + 'byId' => true, + ], ]; } diff --git a/.castor/qa.php b/.castor/qa.php index 061c4db0b..81c89a8b4 100644 --- a/.castor/qa.php +++ b/.castor/qa.php @@ -82,6 +82,8 @@ function suiteFixturesAreMissing(): bool || !fs()->exists(\sprintf('%s/tests/expand-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/toRdf-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/fromRdf-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) + || !fs()->exists(\sprintf('%s/tests/html-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) + || !fs()->exists(\sprintf('%s/tests/remote-doc-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/frame-manifest.jsonld', CACHE_DIR_W3C_FRAMING_TEST_SUITE)); } @@ -239,9 +241,9 @@ function phpunitPrepare( } } - // The RDF suites are driven by their manifest, which names every file of a - // test: their fixtures are copied as they are upstream, N-Quads included. - foreach (Algorithms::rdfAlgorithmNames() as $algorithm) { + // These suites are driven by their manifest, which names every file of a + // test: their fixtures are copied as they are upstream. + foreach (Algorithms::manifestDrivenSuiteNames() as $algorithm) { fs()->copy( \sprintf('%s/json-ld-api-%s/tests/%s-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE, $ref, $algorithm), \sprintf('%s/tests/%s-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE, $algorithm), diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 390b36309..289b59de1 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -117,5 +117,5 @@ tools/phpbench/vendor/bin/phpbench run tests/Algorithms/Benchmark --report=reada tools/phpbench/vendor/bin/phpbench run tests/Validation/Benchmark/JsonLdValidatorBench.php tests/Validation/Benchmark/WorkerValidationBench.php --report=readable --time-unit=milliseconds ``` -For the record, the full PHPUnit suite (2,175 tests, 4,544 assertions, W3C suites +For the record, the full PHPUnit suite (2,281 tests, 4,802 assertions, W3C suites included) runs in about 20 seconds on the same machine. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c3e2fddd..f3b5d7ac8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,43 @@ literals (canonicalized with RFC 8785) are supported. The official `toRdf` and `fromRdf` test suites pass, and are part of `castor qa:earl`. From the command line: `castor json-ld:to-rdf` and `castor json-ld:from-rdf`. See [docs/json-ld.md](docs/json-ld.md#rdf). +- A document given to an algorithm as a URL may be an HTML page: the JSON-LD of its + ` + + + + + +

text

+ + HTML; + + public function testTheFirstScriptIsExtractedByDefault(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE); + + $this->assertEquals((object) ['name' => 'first'], $extracted['document']); + $this->assertNull($extracted['base']); + } + + public function testEveryScriptIsExtractedWhenAskedAndArraysAreMerged(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE, options: new LoadDocumentOptions(extractAllScripts: true)); + + $this->assertEquals( + [ + (object) ['name' => 'first'], + (object) ['name' => 'second'], + (object) ['name' => 'third'], + (object) ['@context' => (object) ['name' => 'http://example.com/name']], + ], + $extracted['document'], + ); + } + + public function testAFragmentTargetsOneScriptWhateverTheOtherOptions(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE, 'second', new LoadDocumentOptions(extractAllScripts: true)); + + $this->assertEquals([(object) ['name' => 'second'], (object) ['name' => 'third']], $extracted['document']); + } + + public function testAFragmentIsPercentDecoded(): void + { + $page = ''; + + $this->assertEquals((object) ['name' => 'accent'], (new HtmlScriptExtractor())->extract($page, '%C3%A9%20a')['document']); + } + + #[DataProvider('provideFragmentsThatAreNotAJsonLdScript')] + public function testAFragmentThatIsNotAJsonLdScriptIsRefused(string $fragment): void + { + $this->expectExceptionObject(new DocumentLoadingException('loading document failed')); + + (new HtmlScriptExtractor())->extract(self::PAGE, $fragment); + } + + /** + * @return iterable + */ + public static function provideFragmentsThatAreNotAJsonLdScript(): iterable + { + yield 'no such element' => ['missing']; + yield 'not a script' => ['paragraph']; + yield 'a script of another type' => ['other']; + } + + public function testAProfileSelectsTheScriptThatDeclaresIt(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE, options: LoadDocumentOptions::forContext()); + + $this->assertEquals((object) ['@context' => (object) ['name' => 'http://example.com/name']], $extracted['document']); + } + + public function testAProfileNoScriptDeclaresFallsBackToTheFirstScript(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE, options: new LoadDocumentOptions(profile: 'http://example.com/profile')); + + $this->assertEquals((object) ['name' => 'first'], $extracted['document']); + } + + public function testAPageWithoutScriptIsRefusedUnlessEveryScriptIsAskedFor(): void + { + $extractor = new HtmlScriptExtractor(); + + $this->assertSame([], $extractor->extract('', options: new LoadDocumentOptions(extractAllScripts: true))['document']); + + $this->expectExceptionObject(new DocumentLoadingException('loading document failed')); + + $extractor->extract(''); + } + + #[DataProvider('provideInvalidScripts')] + public function testAScriptThatIsNotAJsonDocumentIsRefused(string $content): void + { + $this->expectExceptionObject(new DocumentLoadingException('invalid script element')); + + (new HtmlScriptExtractor())->extract(\sprintf('', $content)); + } + + /** + * @return iterable + */ + public static function provideInvalidScripts(): iterable + { + yield 'not JSON' => ['{"name": }']; + yield 'a comment around the JSON' => ['']; + yield 'a scalar' => ['"just a string"']; + yield 'empty' => ['']; + } + + public function testTheTextOfAScriptIsTakenAsItIsWritten(): void + { + $page = ''; + + $this->assertEquals((object) ['name' => 'café ☕ <&> bold'], (new HtmlScriptExtractor())->extract($page)['document']); + } + + public function testTheBaseElementIsHandedBackAsWritten(): void + { + $page = ''; + + $this->assertSame('../base/', (new HtmlScriptExtractor())->extract($page)['base']); + } +} diff --git a/tests/Algorithms/Http/HttpDocumentLoaderTest.php b/tests/Algorithms/Http/HttpDocumentLoaderTest.php index f560ef998..8c870bc7e 100644 --- a/tests/Algorithms/Http/HttpDocumentLoaderTest.php +++ b/tests/Algorithms/Http/HttpDocumentLoaderTest.php @@ -11,7 +11,7 @@ namespace JoliCode\StructuredData\Tests\Algorithms\Http; -use JoliCode\StructuredData\JsonLd\Algorithms\Exception\ContextProcessingException; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\DocumentLoadingException; use JoliCode\StructuredData\JsonLd\Algorithms\Http\HttpDocumentLoader; use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteContextPolicy; use PHPUnit\Framework\Attributes\DataProvider; @@ -23,12 +23,14 @@ #[Group('security')] class HttpDocumentLoaderTest extends TestCase { + private const JSON_LD = ['response_headers' => ['Content-Type' => 'application/ld+json']]; + public function testTheDefaultPolicyRefusesEveryHostWithoutIssuingARequest(): void { $loader = new HttpDocumentLoader(httpClient: $this->clientThatMustNotBeCalled()); - $this->expectException(ContextProcessingException::class); - $this->expectExceptionMessage('loading remote context failed'); + $this->expectException(DocumentLoadingException::class); + $this->expectExceptionMessage('loading document failed'); $loader->load('https://example.com/context.jsonld'); } @@ -37,12 +39,12 @@ public function testAnAllowedHostIsFetched(): void { $loader = new HttpDocumentLoader( RemoteContextPolicy::allowHosts('example.com'), - new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}')), + new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}', self::JSON_LD)), ); $document = $loader->load('https://example.com/context.jsonld'); - $this->assertSame('https://schema.org/name', $document->{'@context'}->name); + $this->assertEquals((object) ['@context' => (object) ['name' => 'https://schema.org/name']], $document->document); } public function testAHostOutsideTheAllowListIsRefused(): void @@ -52,7 +54,7 @@ public function testAHostOutsideTheAllowListIsRefused(): void $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://other.example/context.jsonld'); } @@ -68,7 +70,7 @@ public function testHostMatchingIsExact(): void $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://evil.schema.org.example/context.jsonld'); } @@ -85,8 +87,8 @@ public function testNonHttpUrlsAreRefused(string $url): void $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); - $this->expectExceptionMessage('loading remote context failed'); + $this->expectException(DocumentLoadingException::class); + $this->expectExceptionMessage('loading document failed'); $loader->load($url); } @@ -111,7 +113,7 @@ public function testPlainHttpIsRefusedUnlessExplicitlyAllowed(): void $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('http://example.com/context.jsonld'); } @@ -130,8 +132,8 @@ public function testAnErrorResponseNeverLeaksItsBody(): void try { $loader->load('https://example.com/internal-service'); $this->fail('The loader should have refused the response.'); - } catch (ContextProcessingException $exception) { - $this->assertSame('loading remote context failed', $exception->getMessage()); + } catch (DocumentLoadingException $exception) { + $this->assertSame('loading document failed', $exception->getMessage()); $this->assertStringNotContainsString('SECRET', $exception->getMessage()); $this->assertStringNotContainsString('404', $exception->getMessage()); $this->assertStringNotContainsString('example.com', $exception->getMessage()); @@ -142,10 +144,10 @@ public function testAnOversizedResponseIsRefused(): void { $loader = new HttpDocumentLoader( RemoteContextPolicy::allowHosts('example.com')->withMaxResponseBytes(1024), - new MockHttpClient(new MockResponse(str_repeat('a', 4096))), + new MockHttpClient(new MockResponse(str_repeat('a', 4096), self::JSON_LD)), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://example.com/huge.jsonld'); } @@ -158,12 +160,12 @@ public function testARedirectOutOfTheAllowListIsRefused(): void { $loader = new HttpDocumentLoader( RemoteContextPolicy::allowHosts('example.com'), - new MockHttpClient(new MockResponse('{"@context":{}}', [ + new MockHttpClient(new MockResponse('{"@context":{}}', self::JSON_LD + [ 'url' => 'https://evil.example/context.jsonld', ])), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://example.com/context.jsonld'); } @@ -178,11 +180,11 @@ public function testARedirectToADisallowedHostIsRefusedAtTheHop(): void RemoteContextPolicy::allowHosts('example.com'), new MockHttpClient([ new MockResponse('', ['http_code' => 302, 'response_headers' => ['Location' => 'https://evil.example/context.jsonld']]), - new MockResponse('{"@context":{}}'), + new MockResponse('{"@context":{}}', self::JSON_LD), ]), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://example.com/context.jsonld'); } @@ -196,13 +198,13 @@ public function testARedirectInsideTheAllowListIsFollowed(): void RemoteContextPolicy::allowHosts('example.com'), new MockHttpClient([ new MockResponse('', ['http_code' => 302, 'response_headers' => ['Location' => 'https://example.com/real.jsonld']]), - new MockResponse('{"@context":{"name":"https://schema.org/name"}}'), + new MockResponse('{"@context":{"name":"https://schema.org/name"}}', self::JSON_LD), ]), ); $document = $loader->load('https://example.com/context.jsonld'); - $this->assertSame('https://schema.org/name', $document->{'@context'}->name); + $this->assertEquals((object) ['@context' => (object) ['name' => 'https://schema.org/name']], $document->document); } #[DataProvider('provideUrlsRefusedByPolicyRefinements')] @@ -213,7 +215,7 @@ public function testUrlsWithUserinfoOrNonDefaultPortsAreRefused(string $url): vo $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load($url); } @@ -240,8 +242,8 @@ public function testATransportFailureIsReportedOpaquely(): void try { $loader->load('https://example.com/context.jsonld'); $this->fail('The loader should have refused the response.'); - } catch (ContextProcessingException $exception) { - $this->assertSame('loading remote context failed', $exception->getMessage()); + } catch (DocumentLoadingException $exception) { + $this->assertSame('loading document failed', $exception->getMessage()); } } diff --git a/tests/Algorithms/Http/RemoteDocumentLoadingTest.php b/tests/Algorithms/Http/RemoteDocumentLoadingTest.php new file mode 100644 index 000000000..9167c1d9b --- /dev/null +++ b/tests/Algorithms/Http/RemoteDocumentLoadingTest.php @@ -0,0 +1,261 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Http; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\ContextProcessingException; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\DocumentLoadingException; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\HttpDocumentLoader; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\LoadDocumentOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteContextPolicy; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\HttpClient\Response\MockResponse; + +/** + * What a document loaded from a URL is, beyond what the W3C remote-doc and html + * suites ask: the answers below are the ones a server may give. + */ +#[Group('algorithms')] +class RemoteDocumentLoadingTest extends TestCase +{ + #[DataProvider('provideAcceptedContentTypes')] + public function testJsonContentTypesAreAccepted(string $contentType, string $expectedContentType, ?string $expectedProfile): void + { + $document = $this->loader(['https://example.com/doc' => ['{"name": "doc"}', $contentType]])->load('https://example.com/doc'); + + $this->assertEquals((object) ['name' => 'doc'], $document->document); + $this->assertSame($expectedContentType, $document->contentType); + $this->assertSame($expectedProfile, $document->profile); + $this->assertSame('https://example.com/doc', $document->documentUrl); + } + + /** + * @return iterable + */ + public static function provideAcceptedContentTypes(): iterable + { + yield 'JSON-LD' => ['application/ld+json', 'application/ld+json', null]; + yield 'JSON' => ['application/json', 'application/json', null]; + yield 'a +json type' => ['application/activity+json', 'application/activity+json', null]; + yield 'parameters and case' => ['Application/LD+JSON; charset=utf-8; profile="http://www.w3.org/ns/json-ld#expanded"', 'application/ld+json', 'http://www.w3.org/ns/json-ld#expanded']; + } + + #[DataProvider('provideRefusedContentTypes')] + public function testAnyOtherContentTypeIsRefusedEvenWhenTheBodyIsJson(?string $contentType): void + { + $this->expectExceptionObject(new DocumentLoadingException('loading document failed')); + + $this->loader(['https://example.com/doc' => ['{"name": "doc"}', $contentType]])->load('https://example.com/doc'); + } + + /** + * @return iterable + */ + public static function provideRefusedContentTypes(): iterable + { + yield 'plain text' => ['text/plain']; + yield 'binary' => ['application/octet-stream']; + yield 'javascript' => ['application/javascript']; + yield 'no content type' => [null]; + } + + public function testAJsonDocumentThatIsAnArrayStaysAnArray(): void + { + $document = $this->loader(['https://example.com/doc' => ['[{"name": "a"}, {"name": "b"}]', 'application/ld+json']])->load('https://example.com/doc'); + + $this->assertEquals([(object) ['name' => 'a'], (object) ['name' => 'b']], $document->document); + } + + public function testAJsonBodyThatIsNotADocumentIsRefused(): void + { + $this->expectExceptionObject(new DocumentLoadingException('loading document failed')); + + $this->loader(['https://example.com/doc' => ['"a string"', 'application/ld+json']])->load('https://example.com/doc'); + } + + public function testTheDocumentUrlIsWhereARedirectionLeads(): void + { + $loader = $this->loader([ + 'https://example.com/old' => ['', null, [], 301, 'https://example.com/new/doc'], + 'https://example.com/new/doc' => ['{"@id": ""}', 'application/ld+json'], + ]); + + $this->assertSame('https://example.com/new/doc', $loader->load('https://example.com/old')->documentUrl); + } + + public function testTheContextOfAJsonDocumentIsResolvedAgainstItsLocation(): void + { + $document = $this->loader(['https://example.com/a/doc' => ['{}', 'application/json', ['<../context.jsonld>; rel="http://www.w3.org/ns/json-ld#context"']]])->load('https://example.com/a/doc'); + + $this->assertSame('https://example.com/context.jsonld', $document->contextUrl); + } + + public function testTheContextLinkOfAJsonLdDocumentIsIgnored(): void + { + $document = $this->loader(['https://example.com/doc' => ['{}', 'application/ld+json', ['; rel="http://www.w3.org/ns/json-ld#context"']]])->load('https://example.com/doc'); + + $this->assertNull($document->contextUrl); + } + + public function testSeveralContextLinksAreRefused(): void + { + $this->expectExceptionObject(new DocumentLoadingException('multiple context link headers')); + + $this->loader(['https://example.com/doc' => ['{}', 'application/json', [ + '; rel="http://www.w3.org/ns/json-ld#context"', + '; rel="http://www.w3.org/ns/json-ld#context"', + ]]])->load('https://example.com/doc'); + } + + public function testAnAlternateLinkIsFollowedFromADocumentThatIsNotJson(): void + { + $loader = $this->loader([ + 'https://example.com/page' => ['', 'text/html', ['; rel="alternate"; type="application/ld+json"']], + 'https://example.com/data/doc.jsonld' => ['{"name": "alternate"}', 'application/ld+json'], + ]); + + $document = $loader->load('https://example.com/page'); + + $this->assertEquals((object) ['name' => 'alternate'], $document->document); + $this->assertSame('https://example.com/data/doc.jsonld', $document->documentUrl); + } + + public function testAnAlternateLinkIsNotFollowedFromAJsonDocument(): void + { + $loader = $this->loader([ + 'https://example.com/doc.json' => ['{"name": "json"}', 'application/json', ['; rel="alternate"; type="application/ld+json"']], + 'https://example.com/doc.jsonld' => ['{"name": "alternate"}', 'application/ld+json'], + ]); + + $this->assertEquals((object) ['name' => 'json'], $loader->load('https://example.com/doc.json')->document); + } + + public function testAnHtmlDocumentHandsItsScriptAndItsBase(): void + { + $page = ''; + $loader = $this->loader(['https://example.com/page' => [$page, 'text/html; charset=utf-8']]); + + $first = $loader->load('https://example.com/page'); + $this->assertEquals((object) ['name' => 'first'], $first->document); + $this->assertSame('text/html', $first->contentType); + $this->assertSame('/base/', $first->htmlBase); + $this->assertSame('https://example.com/page', $first->documentUrl); + + $this->assertEquals((object) ['name' => 'second'], $loader->load('https://example.com/page#two')->document); + $this->assertCount(2, (array) $loader->load('https://example.com/page', new LoadDocumentOptions(extractAllScripts: true))->document); + } + + public function testADocumentIsAskedAsJsonLdThenJsonThenHtml(): void + { + $accept = []; + $loader = $this->loader(['https://example.com/doc' => ['{}', 'application/ld+json']], $accept); + + $loader->load('https://example.com/doc'); + $loader->load('https://example.com/doc', LoadDocumentOptions::forContext()); + + $this->assertSame([ + 'application/ld+json,application/json;q=0.9,text/html;q=0.8,application/xhtml+xml;q=0.8,*/*;q=0.1', + 'application/ld+json;profile="http://www.w3.org/ns/json-ld#context",application/json;q=0.9,*/*;q=0.1', + ], $accept); + } + + public function testTheBaseOptionTakesPrecedenceOverTheLocationOfTheDocument(): void + { + $loader = $this->loader(['https://example.com/dir/doc' => ['{"@id": "relative", "http://example.com/p": "v"}', 'application/ld+json']]); + + $expander = new Expander(documentLoader: $loader); + $expected = static fn (string $identifier): array => [(object) ['@id' => $identifier, 'http://example.com/p' => [(object) ['@value' => 'v']]]]; + + $this->assertEquals($expected('https://example.com/dir/relative'), $expander->expand('https://example.com/dir/doc', encodeResult: false)); + $this->assertEquals($expected('https://other.example/relative'), $expander->expand('https://example.com/dir/doc', new ProcessorOptions(base: 'https://other.example/'), false)); + } + + public function testAUrlIsGivenAsItIsOrAsAJsonString(): void + { + $loader = $this->loader(['https://example.com/doc' => ['{"http://example.com/p": "v"}', 'application/ld+json']]); + $expander = new Expander(documentLoader: $loader); + + $this->assertSame($expander->expand('https://example.com/doc'), $expander->expand('"https://example.com/doc"')); + } + + public function testTheLinkedContextComesBeforeTheOneOfTheDocument(): void + { + $loader = $this->loader([ + 'https://example.com/doc' => ['{"@context": {"b": "http://example.com/own-b"}, "a": "1", "b": "2"}', 'application/json', ['; rel="http://www.w3.org/ns/json-ld#context"']], + 'https://example.com/context' => ['{"@context": {"a": "http://example.com/linked-a", "b": "http://example.com/linked-b"}}', 'application/ld+json'], + ]); + + $expanded = (new Expander(documentLoader: $loader))->expand('https://example.com/doc', encodeResult: false); + + $this->assertEquals([(object) [ + 'http://example.com/linked-a' => [(object) ['@value' => '1']], + 'http://example.com/own-b' => [(object) ['@value' => '2']], + ]], $expanded); + } + + public function testADocumentThatCannotBeLoadedAndAContextThatCannotBeLoadedHaveDifferentNames(): void + { + $loader = $this->loader(['https://example.com/doc' => ['{"@context": "https://example.com/missing"}', 'application/ld+json']]); + $expander = new Expander(documentLoader: $loader); + + try { + $expander->expand('https://example.com/nowhere'); + $this->fail('A missing document was loaded.'); + } catch (JsonLdException $exception) { + $this->assertSame('loading document failed', $exception->getMessage()); + } + + $this->expectExceptionObject(new ContextProcessingException('loading remote context failed')); + + $expander->expand('https://example.com/doc'); + } + + /** + * @param array, 3?: int, 4?: string}> $pages body, content type, Link headers, status and Location per URL + * @param list $accept filled with the Accept header of every request + */ + private function loader(array $pages, array &$accept = []): HttpDocumentLoader + { + $client = new MockHttpClient(static function (string $method, string $url, array $options) use ($pages, &$accept): MockResponse { + $accept[] = $options['normalized_headers']['accept'][0] ?? ''; + $accept[array_key_last($accept)] = (string) preg_replace('/^Accept: /i', '', $accept[array_key_last($accept)]); + + if (!\array_key_exists($url, $pages)) { + return new MockResponse('not here', ['http_code' => 404]); + } + + $page = $pages[$url]; + $headers = []; + + if (null !== $page[1]) { + $headers['Content-Type'] = $page[1]; + } + + if ([] !== ($page[2] ?? [])) { + $headers['Link'] = $page[2]; + } + + if (isset($page[4])) { + $headers['Location'] = $page[4]; + } + + return new MockResponse($page[0], ['http_code' => $page[3] ?? 200, 'response_headers' => $headers]); + }); + + return new HttpDocumentLoader(RemoteContextPolicy::allowHosts('example.com', 'other.example'), $client); + } +} diff --git a/tests/Algorithms/Manifest/AbstractRemoteDocumentTestCase.php b/tests/Algorithms/Manifest/AbstractRemoteDocumentTestCase.php new file mode 100644 index 000000000..409f1431a --- /dev/null +++ b/tests/Algorithms/Manifest/AbstractRemoteDocumentTestCase.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Manifest; + +use JoliCode\StructuredData\JsonLd\Algorithms\Compact\Compactor; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; +use JoliCode\StructuredData\JsonLd\Algorithms\Flatten\Flattener; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use JoliCode\StructuredData\Tests\Algorithms\Rdf\RdfDatasetIsomorphism; +use PHPUnit\Framework\TestCase; + +/** + * Runs the entries of a W3C manifest whose input is the URL of a document: + * the algorithm the entry names is handed that URL, and W3cFixtureServer + * answers it the way the manifest says. + */ +abstract class AbstractRemoteDocumentTestCase extends TestCase +{ + /** + * @param array $server + */ + protected function runManifestEntry(string $algorithm, string $url, ?string $context, ?string $expect, ?string $errorCode, ProcessorOptions $options, array $server): void + { + if (null !== $errorCode) { + try { + $this->process($algorithm, $url, $context, $options, $server); + } catch (JsonLdException $exception) { + $this->assertSame($errorCode, $exception->getMessage()); + + return; + } + + $this->fail(\sprintf('An exception was expected for this test but none were thrown. Expected error message was : %s', $errorCode)); + } + + $actual = $this->process($algorithm, $url, $context, $options, $server); + + $this->assertNotNull($expect, 'A positive evaluation test names its expected output.'); + + if ('toRdf' === $algorithm) { + $this->assertTrue( + RdfDatasetIsomorphism::areIsomorphic((new NQuadsParser())->parse($expect), (new NQuadsParser())->parse($actual)), + \sprintf("The datasets are not isomorphic.\nExpected:\n%s\nActual:\n%s", $expect, $actual), + ); + + return; + } + + $this->assertEquals(json_decode($expect), json_decode($actual), \sprintf("Expected:\n%s\nActual:\n%s", $expect, $actual)); + } + + /** + * @param array $server + */ + private function process(string $algorithm, string $url, ?string $context, ProcessorOptions $options, array $server): string + { + $documentLoader = W3cFixtureServer::documentLoader($url, $server); + + $result = match ($algorithm) { + 'expand' => (new Expander(documentLoader: $documentLoader))->expand($url, $options), + 'compact' => (new Compactor(documentLoader: $documentLoader))->compact($url, $context, $options), + 'flatten' => (new Flattener(documentLoader: $documentLoader))->flatten($url, $context, $options), + 'toRdf' => NQuadsSerializer::serialize((new ToRdfConverter(documentLoader: $documentLoader))->toRdf($url, $options)), + default => throw new \LogicException(\sprintf('The "%s" algorithm does not take a URL.', $algorithm)), + }; + + $this->assertIsString($result); + + return $result; + } +} diff --git a/tests/Algorithms/Manifest/ManifestTestProvider.php b/tests/Algorithms/Manifest/ManifestTestProvider.php new file mode 100644 index 000000000..0ba7e5454 --- /dev/null +++ b/tests/Algorithms/Manifest/ManifestTestProvider.php @@ -0,0 +1,193 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Manifest; + +use JoliCode\StructuredData\JsonLd\Algorithms\ContextProcessing\Context; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\Tests\Algorithms\AbstractJsonLdTestCase; + +/** + * Turns a W3C manifest into PHPUnit data sets, one per entry and named after + * the fragment of its IRI ("#t0001"), which is what the EARL report maps the + * outcomes back with. + * + * The entries written for a JSON-LD 1.0 processor only are left out: they + * describe a behaviour JSON-LD 1.1 changed. + */ +final class ManifestTestProvider +{ + public const BASE_IRI = 'https://w3c.github.io/json-ld-api/tests/'; + + private const OPTIONS = ['base', 'expandContext', 'extractAllScripts', 'processingMode', 'produceGeneralizedRdf', 'rdfDirection', 'useNativeTypes', 'useRdfType']; + + /** + * What a manifest says of how its input is served, which is the business of + * the simulated server and not of the processor. + */ + private const SERVER_OPTIONS = ['contentType', 'httpLink', 'httpStatus', 'redirectTo']; + + private const ALGORITHMS = [ + 'jld:ExpandTest' => 'expand', + 'jld:CompactTest' => 'compact', + 'jld:FlattenTest' => 'flatten', + 'jld:ToRDFTest' => 'toRdf', + 'jld:FromRDFTest' => 'fromRdf', + ]; + + /** + * What a manifest says of a test without it being an option of the + * processor: the version of the specification it was written for, whether + * it is normative, the canonicalization the JSON literals are compared + * under, which is the only one there is, and the optional feature it needs. + */ + private const IGNORED_OPTIONS = ['specVersion', 'normative', 'useJCS', 'processorFeature']; + + /** + * @return iterable + */ + public static function provide(string $suite): iterable + { + foreach (self::entries($suite) as $id => $entry) { + yield $id => [ + 'input' => self::read($entry['input']), + 'expect' => null === $entry['expect'] ? null : self::read($entry['expect']), + 'errorCode' => $entry['errorCode'], + 'options' => self::options($entry['entryOptions'], self::BASE_IRI . $entry['input']), + ]; + } + } + + /** + * The data sets of a suite whose input is a URL, the document being served + * by W3cFixtureServer: the base IRI is then the location of the document, + * unless the manifest sets one. + * + * @return iterable}> + */ + public static function provideDocuments(string $suite): iterable + { + foreach (self::entries($suite) as $id => $entry) { + yield $id => [ + 'algorithm' => $entry['algorithm'], + 'url' => self::BASE_IRI . $entry['input'], + 'context' => null === $entry['context'] ? null : self::read($entry['context']), + 'expect' => null === $entry['expect'] ? null : self::read($entry['expect']), + 'errorCode' => $entry['errorCode'], + 'options' => self::options($entry['entryOptions'], null), + 'server' => array_intersect_key($entry['entryOptions'], array_flip(self::SERVER_OPTIONS)), + ]; + } + } + + /** + * Where a file of the test suite is, given its path in the manifest. The + * RDF suites keep the upstream layout; the few files they borrow from the + * other suites are filed by kind ("expand/er56-in.jsonld" is in + * "expand/input/"). + */ + public static function fixturePath(string $path): string + { + $path = explode('#', $path, 2)[0]; + $file = \sprintf('%s/%s', AbstractJsonLdTestCase::DATA_PATH, $path); + + if (is_file($file)) { + return $file; + } + + foreach (['-in.jsonld' => 'input', '-out.jsonld' => 'output', '-context.jsonld' => 'context'] as $suffix => $directory) { + if (str_ends_with($path, $suffix)) { + return \sprintf('%s/%s/%s/%s', AbstractJsonLdTestCase::DATA_PATH, \dirname($path), $directory, basename($path)); + } + } + + return $file; + } + + /** + * @return iterable}> + */ + private static function entries(string $suite): iterable + { + $manifestFile = \sprintf('%s/%s-manifest.jsonld', AbstractJsonLdTestCase::DATA_PATH, $suite); + + if (!is_file($manifestFile)) { + throw new \RuntimeException(\sprintf('The manifest "%s" does not exist. Did you forget to install the test suite? Please run the following command : `castor qa:phpunit:prepare`', $manifestFile)); + } + + $manifest = json_decode((string) file_get_contents($manifestFile), true); + + if (!\is_array($manifest) || !\is_array($manifest['sequence'] ?? null)) { + throw new \RuntimeException(\sprintf('The manifest "%s" could not be read.', $manifestFile)); + } + + foreach ($manifest['sequence'] as $entry) { + if (!\is_array($entry) || !\is_string($entry['@id'] ?? null) || !\is_string($entry['input'] ?? null)) { + continue; + } + + $entryOptions = \is_array($entry['option'] ?? null) ? $entry['option'] : []; + + if ('json-ld-1.0' === ($entryOptions['specVersion'] ?? null)) { + continue; + } + + $unknownOptions = array_diff(array_keys($entryOptions), self::OPTIONS, self::SERVER_OPTIONS, self::IGNORED_OPTIONS); + + if ([] !== $unknownOptions) { + throw new \RuntimeException(\sprintf('The test "%s" sets options this provider does not know: %s.', $entry['@id'], implode(', ', $unknownOptions))); + } + + $algorithms = array_values(array_intersect_key(self::ALGORITHMS, array_flip(\is_array($entry['@type'] ?? null) ? array_filter($entry['@type'], \is_string(...)) : []))); + + if (1 !== \count($algorithms)) { + throw new \RuntimeException(\sprintf('The test "%s" does not name the algorithm it runs.', $entry['@id'])); + } + + yield $entry['@id'] => [ + 'algorithm' => $algorithms[0], + 'input' => $entry['input'], + 'context' => \is_string($entry['context'] ?? null) ? $entry['context'] : null, + 'expect' => \is_string($entry['expect'] ?? null) ? $entry['expect'] : null, + 'errorCode' => \is_string($entry['expectErrorCode'] ?? null) ? $entry['expectErrorCode'] : null, + 'entryOptions' => $entryOptions, + ]; + } + } + + /** + * @param array $entryOptions + */ + private static function options(array $entryOptions, ?string $defaultBase): ProcessorOptions + { + return new ProcessorOptions( + base: \is_string($entryOptions['base'] ?? null) ? $entryOptions['base'] : $defaultBase, + expandContext: \is_string($entryOptions['expandContext'] ?? null) ? self::BASE_IRI . $entryOptions['expandContext'] : null, + extractAllScripts: \is_bool($entryOptions['extractAllScripts'] ?? null) ? $entryOptions['extractAllScripts'] : null, + processingMode: 'json-ld-1.0' === ($entryOptions['processingMode'] ?? null) ? Context::PROCESSING_MODE_10 : Context::PROCESSING_MODE_11, + produceGeneralizedRdf: true === ($entryOptions['produceGeneralizedRdf'] ?? false), + rdfDirection: \is_string($entryOptions['rdfDirection'] ?? null) ? $entryOptions['rdfDirection'] : null, + useNativeTypes: true === ($entryOptions['useNativeTypes'] ?? false), + useRdfType: true === ($entryOptions['useRdfType'] ?? false), + ); + } + + private static function read(string $path): string + { + $content = @file_get_contents(self::fixturePath($path)); + + if (false === $content) { + throw new \RuntimeException(\sprintf('The fixture "%s" could not be read.', $path)); + } + + return $content; + } +} diff --git a/tests/Algorithms/Manifest/W3cFixtureServer.php b/tests/Algorithms/Manifest/W3cFixtureServer.php new file mode 100644 index 000000000..18e5e1e93 --- /dev/null +++ b/tests/Algorithms/Manifest/W3cFixtureServer.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Manifest; + +use JoliCode\StructuredData\JsonLd\Algorithms\Http\DocumentLoaderInterface; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\HttpDocumentLoader; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteContextPolicy; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\HttpClient\Response\MockResponse; + +/** + * Stands for https://w3c.github.io/json-ld-api/tests/: it serves the copy of + * the test suite downloaded at the pinned commit, with the headers a manifest + * asks for. The tests then run offline, through the real HttpDocumentLoader, + * against the very revision their manifest comes from. + */ +final class W3cFixtureServer +{ + private const CONTENT_TYPES = [ + 'jsonld' => 'application/ld+json', + 'json' => 'application/json', + 'html' => 'text/html', + ]; + + /** + * @param string|null $url the URL the options below apply to: the input of a test + * @param array $server how the manifest wants that URL served: "contentType", "httpLink", "redirectTo" and "httpStatus" + */ + public static function documentLoader(?string $url = null, array $server = []): DocumentLoaderInterface + { + $inputUrl = null === $url ? null : explode('#', $url, 2)[0]; + + $client = new MockHttpClient(static function (string $method, string $requestedUrl) use ($inputUrl, $server): MockResponse { + $requestedUrl = (string) preg_replace('/[?#].*$/', '', $requestedUrl); + $options = $requestedUrl === $inputUrl ? $server : []; + + if (!str_starts_with($requestedUrl, ManifestTestProvider::BASE_IRI) || str_contains($requestedUrl, '..')) { + return new MockResponse('', ['http_code' => 404]); + } + + if (\is_string($options['redirectTo'] ?? null)) { + return new MockResponse('', [ + 'http_code' => \is_int($options['httpStatus'] ?? null) ? $options['httpStatus'] : 302, + 'response_headers' => ['Location' => ManifestTestProvider::BASE_IRI . $options['redirectTo']], + ]); + } + + $file = ManifestTestProvider::fixturePath(substr($requestedUrl, \strlen(ManifestTestProvider::BASE_IRI))); + + if (!is_file($file)) { + return new MockResponse('', ['http_code' => 404]); + } + + $headers = [ + 'Content-Type' => \is_string($options['contentType'] ?? null) + ? $options['contentType'] + : self::CONTENT_TYPES[pathinfo($file, \PATHINFO_EXTENSION)] ?? 'application/octet-stream', + ]; + + if (isset($options['httpLink'])) { + $headers['Link'] = array_values(array_filter((array) $options['httpLink'], \is_string(...))); + } + + return new MockResponse((string) file_get_contents($file), ['response_headers' => $headers]); + }); + + return new HttpDocumentLoader(RemoteContextPolicy::allowHosts('w3c.github.io'), $client); + } +} diff --git a/tests/Algorithms/Rdf/ManifestTestProvider.php b/tests/Algorithms/Rdf/ManifestTestProvider.php deleted file mode 100644 index 6f0a600ee..000000000 --- a/tests/Algorithms/Rdf/ManifestTestProvider.php +++ /dev/null @@ -1,126 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; - -use JoliCode\StructuredData\JsonLd\Algorithms\ContextProcessing\Context; -use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; -use JoliCode\StructuredData\Tests\Algorithms\AbstractJsonLdTestCase; - -/** - * Turns a W3C manifest into PHPUnit data sets, one per entry and named after - * the fragment of its IRI ("#t0001"), which is what the EARL report maps the - * outcomes back with. - * - * The entries written for a JSON-LD 1.0 processor only are left out: they - * describe a behaviour JSON-LD 1.1 changed. - */ -final class ManifestTestProvider -{ - public const BASE_IRI = 'https://w3c.github.io/json-ld-api/tests/'; - - private const OPTIONS = ['base', 'expandContext', 'processingMode', 'produceGeneralizedRdf', 'rdfDirection', 'useNativeTypes', 'useRdfType']; - - /** - * What a manifest says of a test without it being an option of the - * processor: the version of the specification it was written for, whether - * it is normative, and the canonicalization the JSON literals are compared - * under, which is the only one there is. - */ - private const IGNORED_OPTIONS = ['specVersion', 'normative', 'useJCS']; - - /** - * @return iterable - */ - public static function provide(string $suite): iterable - { - $manifestFile = \sprintf('%s/%s-manifest.jsonld', AbstractJsonLdTestCase::DATA_PATH, $suite); - - if (!is_file($manifestFile)) { - throw new \RuntimeException(\sprintf('The manifest "%s" does not exist. Did you forget to install the test suite? Please run the following command : `castor qa:phpunit:prepare`', $manifestFile)); - } - - $manifest = json_decode((string) file_get_contents($manifestFile), true); - - if (!\is_array($manifest) || !\is_array($manifest['sequence'] ?? null)) { - throw new \RuntimeException(\sprintf('The manifest "%s" could not be read.', $manifestFile)); - } - - foreach ($manifest['sequence'] as $entry) { - if (!\is_array($entry) || !\is_string($entry['@id'] ?? null) || !\is_string($entry['input'] ?? null)) { - continue; - } - - $entryOptions = \is_array($entry['option'] ?? null) ? $entry['option'] : []; - - if ('json-ld-1.0' === ($entryOptions['specVersion'] ?? null)) { - continue; - } - - $unknownOptions = array_diff(array_keys($entryOptions), self::OPTIONS, self::IGNORED_OPTIONS); - - if ([] !== $unknownOptions) { - throw new \RuntimeException(\sprintf('The test "%s" sets options this provider does not know: %s.', $entry['@id'], implode(', ', $unknownOptions))); - } - - $options = new ProcessorOptions( - base: \is_string($entryOptions['base'] ?? null) ? $entryOptions['base'] : self::BASE_IRI . $entry['input'], - expandContext: \is_string($entryOptions['expandContext'] ?? null) ? self::BASE_IRI . $entryOptions['expandContext'] : null, - processingMode: 'json-ld-1.0' === ($entryOptions['processingMode'] ?? null) ? Context::PROCESSING_MODE_10 : Context::PROCESSING_MODE_11, - produceGeneralizedRdf: true === ($entryOptions['produceGeneralizedRdf'] ?? false), - rdfDirection: \is_string($entryOptions['rdfDirection'] ?? null) ? $entryOptions['rdfDirection'] : null, - useNativeTypes: true === ($entryOptions['useNativeTypes'] ?? false), - useRdfType: true === ($entryOptions['useRdfType'] ?? false), - ); - - yield $entry['@id'] => [ - 'input' => self::read($entry['input']), - 'expect' => \is_string($entry['expect'] ?? null) ? self::read($entry['expect']) : null, - 'errorCode' => \is_string($entry['expectErrorCode'] ?? null) ? $entry['expectErrorCode'] : null, - 'options' => $options, - ]; - } - } - - /** - * Where a file of the test suite is, given its path in the manifest. The - * RDF suites keep the upstream layout; the few files they borrow from the - * other suites are filed by kind ("expand/er56-in.jsonld" is in - * "expand/input/"). - */ - public static function fixturePath(string $path): string - { - $file = \sprintf('%s/%s', AbstractJsonLdTestCase::DATA_PATH, $path); - - if (is_file($file)) { - return $file; - } - - foreach (['-in.jsonld' => 'input', '-out.jsonld' => 'output', '-context.jsonld' => 'context'] as $suffix => $directory) { - if (str_ends_with($path, $suffix)) { - return \sprintf('%s/%s/%s/%s', AbstractJsonLdTestCase::DATA_PATH, \dirname($path), $directory, basename($path)); - } - } - - return $file; - } - - private static function read(string $path): string - { - $content = @file_get_contents(self::fixturePath($path)); - - if (false === $content) { - throw new \RuntimeException(\sprintf('The fixture "%s" could not be read.', $path)); - } - - return $content; - } -} diff --git a/tests/Algorithms/Rdf/W3cFixtureDocumentLoader.php b/tests/Algorithms/Rdf/W3cFixtureDocumentLoader.php deleted file mode 100644 index a7538e877..000000000 --- a/tests/Algorithms/Rdf/W3cFixtureDocumentLoader.php +++ /dev/null @@ -1,51 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; - -use JoliCode\StructuredData\JsonLd\Algorithms\Exception\ContextProcessingException; -use JoliCode\StructuredData\JsonLd\Algorithms\Http\DocumentLoaderInterface; - -/** - * Serves the documents the W3C test suite hosts from the copy downloaded at - * the pinned commit: the tests then run offline, against the very revision - * their manifest comes from. Anything else is refused. - */ -final class W3cFixtureDocumentLoader implements DocumentLoaderInterface -{ - public function load(string $url): \stdClass - { - $path = (string) preg_replace('/[?#].*$/', '', $url); - - if (!str_starts_with($path, ManifestTestProvider::BASE_IRI) || str_contains($path, '..')) { - throw new ContextProcessingException('loading remote context failed'); - } - - $file = ManifestTestProvider::fixturePath(substr($path, \strlen(ManifestTestProvider::BASE_IRI))); - - if (!is_file($file)) { - throw new ContextProcessingException('loading remote context failed'); - } - - $document = json_decode((string) file_get_contents($file)); - - if (!$document instanceof \stdClass) { - throw new ContextProcessingException('invalid remote context'); - } - - return $document; - } - - public function getCacheNamespace(): string - { - return 'w3c-fixtures'; - } -} diff --git a/tests/Algorithms/RemoteContextPolicyIntegrationTest.php b/tests/Algorithms/RemoteContextPolicyIntegrationTest.php index 45420f8bf..e55148135 100644 --- a/tests/Algorithms/RemoteContextPolicyIntegrationTest.php +++ b/tests/Algorithms/RemoteContextPolicyIntegrationTest.php @@ -86,7 +86,7 @@ public function testExpandAcceptsARemoteContextOnceItsHostIsAllowed(): void { $expander = new Expander(documentLoader: new HttpDocumentLoader( RemoteContextPolicy::allowHosts('evil.example'), - new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}')), + new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}', ['response_headers' => ['Content-Type' => 'application/ld+json']])), )); $expanded = $expander->expand(self::DOCUMENT_WITH_REMOTE_CONTEXT); @@ -115,7 +115,7 @@ public function testTheProcessedContextCacheIsNotSharedAcrossPolicies(): void $permissive = new ContextCache(new HttpDocumentLoader( RemoteContextPolicy::allowHosts('cache-partitioning.example'), - new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}')), + new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}', ['response_headers' => ['Content-Type' => 'application/ld+json']])), )); $remoteContexts = [$url]; diff --git a/tests/Algorithms/RemoteDocTest.php b/tests/Algorithms/RemoteDocTest.php new file mode 100644 index 000000000..279af6232 --- /dev/null +++ b/tests/Algorithms/RemoteDocTest.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms; + +use JoliCode\StructuredData\JsonLd\Algorithms; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\Tests\Algorithms\Manifest\AbstractRemoteDocumentTestCase; +use JoliCode\StructuredData\Tests\Algorithms\Manifest\ManifestTestProvider; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; + +/** + * @see https://w3c.github.io/json-ld-api/tests/remote-doc-manifest.html + */ +#[Group('remote-doc')] +class RemoteDocTest extends AbstractRemoteDocumentTestCase +{ + /** + * @param array $server + */ + #[DataProvider('provideManifestEntries')] + public function testRemoteDoc(string $algorithm, string $url, ?string $context, ?string $expect, ?string $errorCode, ProcessorOptions $options, array $server): void + { + $this->runManifestEntry($algorithm, $url, $context, $expect, $errorCode, $options, $server); + } + + /** + * @return iterable}> + */ + public static function provideManifestEntries(): iterable + { + return ManifestTestProvider::provideDocuments(Algorithms::REMOTE_DOC_SUITE); + } +} diff --git a/tests/Algorithms/ToRdfTest.php b/tests/Algorithms/ToRdfTest.php index 9d502ce6f..aecaca9e1 100644 --- a/tests/Algorithms/ToRdfTest.php +++ b/tests/Algorithms/ToRdfTest.php @@ -17,9 +17,9 @@ use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; -use JoliCode\StructuredData\Tests\Algorithms\Rdf\ManifestTestProvider; +use JoliCode\StructuredData\Tests\Algorithms\Manifest\ManifestTestProvider; +use JoliCode\StructuredData\Tests\Algorithms\Manifest\W3cFixtureServer; use JoliCode\StructuredData\Tests\Algorithms\Rdf\RdfDatasetIsomorphism; -use JoliCode\StructuredData\Tests\Algorithms\Rdf\W3cFixtureDocumentLoader; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\TestCase; @@ -33,7 +33,7 @@ class ToRdfTest extends TestCase #[DataProvider('provideManifestEntries')] public function testToRdf(string $input, ?string $expect, ?string $errorCode, ProcessorOptions $options): void { - $converter = new ToRdfConverter(documentLoader: new W3cFixtureDocumentLoader()); + $converter = new ToRdfConverter(documentLoader: W3cFixtureServer::documentLoader()); if (null !== $errorCode) { try { diff --git a/tests/Validation/SnapshotDocumentLoader.php b/tests/Validation/SnapshotDocumentLoader.php index 4d6774c0b..8edafa372 100644 --- a/tests/Validation/SnapshotDocumentLoader.php +++ b/tests/Validation/SnapshotDocumentLoader.php @@ -12,6 +12,8 @@ namespace JoliCode\StructuredData\Tests\Validation; use JoliCode\StructuredData\JsonLd\Algorithms\Http\DocumentLoaderInterface; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\LoadDocumentOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteDocument; /** * Serves the remote contexts the validation fixtures reference from snapshots @@ -64,7 +66,7 @@ final class SnapshotDocumentLoader implements DocumentLoaderInterface */ private array $documents = []; - public function load(string $url): \stdClass + public function load(string $url, LoadDocumentOptions $options = new LoadDocumentOptions()): RemoteDocument { if (!\array_key_exists($url, self::SNAPSHOTS)) { // Not a ContextProcessingException, and not a RuntimeException either: @@ -74,7 +76,7 @@ public function load(string $url): \stdClass throw new \LogicException(\sprintf('The validation suite runs offline, and no snapshot is registered for the remote context "%s". Download it into "%s" and register it in %s::SNAPSHOTS.', $url, self::SNAPSHOTS_DIRECTORY, self::class)); } - return $this->documents[$url] ??= $this->decode(self::SNAPSHOTS[$url]); + return new RemoteDocument($this->documents[$url] ??= $this->decode(self::SNAPSHOTS[$url]), $url); } public function getCacheNamespace(): string From 86ddc151aedabb313d779075bc689212614c0ee5 Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sun, 22 Nov 2026 18:05:17 +0100 Subject: [PATCH 09/10] Read the unquoted parameters of an HTTP Link header --- CHANGELOG.md | 2 + .../Algorithms/Http/LinkHeaderParser.php | 4 +- .../Algorithms/Http/LinkHeaderParserTest.php | 65 +++++++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 tests/Algorithms/Http/LinkHeaderParserTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index f3b5d7ac8..cedcfa604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -71,6 +71,8 @@ - Expanding an array that holds a map with nothing but `@graph` flattened that graph into the array: it is now kept as a graph object, only the document itself being unwrapped. - A remote document that is a JSON array was turned into an object with numeric keys. +- A parameter of an HTTP `Link` header written without quotes (`rel=alternate`) was + dropped, so the alternate document such a header names was not followed. - Expansion reported `invalid @reverse property value` where the specification names the error `invalid reverse property value` (W3C test `expand#ter34`). - Flattening and framing merged a plain string into a language-tagged string holding the diff --git a/src/JsonLd/Algorithms/Http/LinkHeaderParser.php b/src/JsonLd/Algorithms/Http/LinkHeaderParser.php index 07fa9052f..81dec729a 100644 --- a/src/JsonLd/Algorithms/Http/LinkHeaderParser.php +++ b/src/JsonLd/Algorithms/Http/LinkHeaderParser.php @@ -57,7 +57,9 @@ public static function parse(array $headers): array } foreach ($parameters as $parameter) { - $keyValue = preg_split('/=(?=([^"]*"[^"]*")*$)/', $parameter); + // The first "=" outside quotes: a value is a quoted string + // or a bare token (rel=alternate). + $keyValue = preg_split('/=(?=([^"]*"[^"]*")*[^"]*$)/', $parameter, 2); // Skip valueless parameters (e.g. a bare "rel"); the trim // char-list strips only surrounding whitespace and quotes. diff --git a/tests/Algorithms/Http/LinkHeaderParserTest.php b/tests/Algorithms/Http/LinkHeaderParserTest.php new file mode 100644 index 000000000..4a2083274 --- /dev/null +++ b/tests/Algorithms/Http/LinkHeaderParserTest.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Http; + +use JoliCode\StructuredData\JsonLd\Algorithms\Http\LinkHeaderParser; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +#[Group('algorithms')] +class LinkHeaderParserTest extends TestCase +{ + public function testAHeaderListingSeveralLinksIsSplit(): void + { + $this->assertSame( + [ + ['uri' => 'context.jsonld', 'rel' => 'http://www.w3.org/ns/json-ld#context', 'type' => 'application/ld+json'], + ['uri' => 'other.jsonld', 'rel' => 'alternate'], + ], + LinkHeaderParser::parse([ + '; rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json", ; rel="alternate"', + ]), + ); + } + + public function testACommaInsideAQuotedParameterDoesNotSplitTheLink(): void + { + $this->assertSame( + [['uri' => 'context.jsonld', 'rel' => 'alternate', 'title' => 'one, two']], + LinkHeaderParser::parse(['; rel="alternate"; title="one, two"']), + ); + } + + public function testAParameterValueMayBeABareToken(): void + { + $this->assertSame( + [['uri' => 'document.jsonld', 'rel' => 'alternate', 'type' => 'application/ld+json']], + LinkHeaderParser::parse(['; rel=alternate; type="application/ld+json"']), + ); + } + + public function testAnEqualSignInsideAValueIsKept(): void + { + $this->assertSame( + [['uri' => 'document.jsonld', 'title' => 'a=b', 'anchor' => 'c=d']], + LinkHeaderParser::parse(['; title="a=b"; anchor=c=d']), + ); + } + + public function testAValuelessParameterAndAMalformedLinkAreIgnored(): void + { + $this->assertSame( + [['uri' => 'context.jsonld', 'type' => 'application/ld+json']], + LinkHeaderParser::parse(['; rel; type="application/ld+json"', 'not a link']), + ); + } +} From d69b66c4d1b88c962cadaa36070c5a7c53176f0b Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Sun, 22 Nov 2026 18:05:19 +0100 Subject: [PATCH 10/10] Measure the real code coverage, test the audit options and the fallback parser, drop dead code --- infection.json5 | 9 +- .../Parser/DataStructures/ObjectStructure.php | 11 - src/Mapper/ValidationMapper.php | 13 -- src/Vocabularies/Validators/Google/Stack.php | 15 -- tests/Validation/AuditTest.php | 217 ++++++++++++++++++ .../GoogleValidatorInfrastructureTest.php | 3 - .../Validation/Google/GoogleValidatorTest.php | 4 - tests/Validation/JsonLdParserTest.php | 79 +++++++ .../SchemaOrgValidatorInfrastructureTest.php | 2 - .../SchemaOrg/SchemaOrgValidatorTest.php | 4 - 10 files changed, 301 insertions(+), 56 deletions(-) create mode 100644 tests/Validation/AuditTest.php create mode 100644 tests/Validation/JsonLdParserTest.php diff --git a/infection.json5 b/infection.json5 index 857985444..c7210ead0 100644 --- a/infection.json5 +++ b/infection.json5 @@ -10,10 +10,11 @@ }, "timeout": 30, // Floor for the covered-code mutation score, kept a little below the current - // value (52% in November 2026) so the weekly run flags regressions without - // flapping. The score slipped from ~60% as the validators grew faster than - // their tests: raise this floor again as escaped mutants get killed. - "minCoveredMsi": 50, + // value (72% in November 2026) so the weekly run flags regressions without + // flapping: raise this floor again as escaped mutants get killed. The score + // read 52% while the fixture-driven tests carried #[CoversClass] attributes, + // which kept Infection from running them against most of the mutants. + "minCoveredMsi": 70, "logs": { "text": "var/cache/infection/infection.log", "summary": "var/cache/infection/summary.log" diff --git a/src/JsonLd/Parser/DataStructures/ObjectStructure.php b/src/JsonLd/Parser/DataStructures/ObjectStructure.php index bbc54c7a3..032e9d6d3 100644 --- a/src/JsonLd/Parser/DataStructures/ObjectStructure.php +++ b/src/JsonLd/Parser/DataStructures/ObjectStructure.php @@ -89,17 +89,6 @@ public function getGraphType(int $graphKey): AbstractStructure|string|bool|null return $this->getGraph()->getValue($graphKey)->content; } - public function getGraphProperty(string $name, int $graphKey): Property - { - $graphType = $this->getGraphType($graphKey); - - if (!$graphType instanceof self) { - throw new \InvalidArgumentException('This graph entry is not an object.'); - } - - return $graphType->getProperty($name); - } - // Graphs are ArrayStructures, so they don't have a property key, they only have numeric keys. // We cannot retrieve a Property, so we instead return a Value, which also holds a Range. public function getGraphValue(string $reference): Value diff --git a/src/Mapper/ValidationMapper.php b/src/Mapper/ValidationMapper.php index aa7c55a21..dbf0d9400 100644 --- a/src/Mapper/ValidationMapper.php +++ b/src/Mapper/ValidationMapper.php @@ -33,10 +33,6 @@ public function __construct( * @var array */ private array $mappedTypes = [], - /** - * @var array - */ - private array $mappedErrors = [], /** * @var array */ @@ -53,7 +49,6 @@ public function __construct( public function reset(): void { $this->mappedTypes = []; - $this->mappedErrors = []; $this->flattenedTypeReferences = []; $this->propertiesWithReferences = []; $this->propertyReferenceByObjectId = []; @@ -61,14 +56,6 @@ public function reset(): void $this->nameNormalizer->reset(); } - /** - * @return array - */ - public function getMappedErrors(): array - { - return $this->mappedErrors; - } - /** * @param array $expandedJsonLd the expanded JSON-LD nodes to map * diff --git a/src/Vocabularies/Validators/Google/Stack.php b/src/Vocabularies/Validators/Google/Stack.php index 0ce24b5a6..962d8067a 100644 --- a/src/Vocabularies/Validators/Google/Stack.php +++ b/src/Vocabularies/Validators/Google/Stack.php @@ -11,7 +11,6 @@ namespace JoliCode\StructuredData\Vocabularies\Validators\Google; -use JoliCode\StructuredData\Mapper\MappedProperty; use JoliCode\StructuredData\Mapper\MappedType; use JoliCode\StructuredData\Vocabularies\Generated\GeneratedClassesRegistry; use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrgTypeHierarchy; @@ -64,20 +63,6 @@ public function newType(MappedType $type): self return $this; } - public function newProperty(MappedProperty $property): self - { - $ownerType = $property->getOwnerType(); - - if ($this->currentType && spl_object_id($this->currentType) === spl_object_id($ownerType ?? (object) [])) { - return $this; - } - - $this->currentType = $ownerType; - $this->resetResolutionCache(); - - return $this; - } - /** * The validation class whose rules apply to the current type: the one of the * root, or the one the current type (or one of its ancestors in the document) diff --git a/tests/Validation/AuditTest.php b/tests/Validation/AuditTest.php new file mode 100644 index 000000000..99f6c36b4 --- /dev/null +++ b/tests/Validation/AuditTest.php @@ -0,0 +1,217 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Validation; + +use JoliCode\StructuredData\Audit\Audit; +use JoliCode\StructuredData\Audit\AuditOptions; +use JoliCode\StructuredData\Mapper\MappedError; +use JoliCode\StructuredData\Mapper\MappedProperty; +use JoliCode\StructuredData\Mapper\MappedType; +use JoliCode\StructuredData\Mapper\MappedTypeMerger; +use JoliCode\StructuredData\Vocabularies\Validators\Google\GoogleValidator; +use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrg\SchemaOrgValidator; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +#[Group('validation')] +class AuditTest extends TestCase +{ + public function testWithoutOptionsTheDiagnosticIsTheListOfEveryFormattedMessage(): void + { + $this->assertSame( + [ + '[Google error] Recipe: google error', + '[Google warning] Recipe: google warning', + '[SchemaOrg warning] Recipe: schema.org warning', + '[Merge warning] Recipe: merge warning', + '[Document error] document error', + ], + $this->createAudit()->getDiagnostic(), + ); + } + + /** + * @param list $expectedMessages + */ + #[DataProvider('provideFilters')] + public function testTheDiagnosticIsFilteredBySeverityOrValidator(AuditOptions $options, array $expectedMessages): void + { + $errors = $this->createAudit()->getDiagnostic($options); + + $this->assertIsArray($errors); + $this->assertSame($expectedMessages, array_map( + static fn (mixed $error): string => $error instanceof MappedError ? $error->getMessage() : '', + $errors, + )); + } + + /** + * @return iterable}> + */ + public static function provideFilters(): iterable + { + yield 'errors' => [ + new AuditOptions(severity: AuditOptions::SEVERITY_ERROR, asObject: true), + ['google error', 'document error'], + ]; + yield 'warnings' => [ + new AuditOptions(severity: AuditOptions::SEVERITY_WARNING, asObject: true), + ['google warning', 'schema.org warning', 'merge warning'], + ]; + yield 'document severity' => [ + new AuditOptions(severity: AuditOptions::SEVERITY_DOCUMENT, asObject: true), + ['document error'], + ]; + yield 'google' => [ + new AuditOptions(validator: AuditOptions::VALIDATOR_GOOGLE, asObject: true), + ['google error', 'google warning'], + ]; + yield 'schema.org' => [ + new AuditOptions(validator: AuditOptions::VALIDATOR_SCHEMA_ORG, asObject: true), + ['schema.org warning'], + ]; + yield 'document validator' => [ + new AuditOptions(validator: AuditOptions::VALIDATOR_DOCUMENT, asObject: true), + ['document error'], + ]; + yield 'merge' => [ + new AuditOptions(validator: AuditOptions::VALIDATOR_MERGE, asObject: true), + ['merge warning'], + ]; + } + + public function testTheMessagesAreGroupedByValidator(): void + { + $this->assertSame( + [ + 'Google' => ['[Google error] Recipe: google error', '[Google warning] Recipe: google warning'], + 'SchemaOrg' => ['[SchemaOrg warning] Recipe: schema.org warning'], + 'Merge' => ['[Merge warning] Recipe: merge warning'], + 'Document' => ['[Document error] document error'], + ], + $this->createAudit()->getDiagnostic(new AuditOptions(groupBy: AuditOptions::GROUP_BY_VALIDATOR)), + ); + } + + public function testTheErrorObjectsAreGroupedBySeverity(): void + { + $groups = $this->createAudit()->getDiagnostic(new AuditOptions(groupBy: AuditOptions::GROUP_BY_SEVERITY, asObject: true)); + + $this->assertIsArray($groups); + $this->assertSame(['error', 'warning'], array_keys($groups)); + $this->assertIsArray($groups['error']); + $this->assertIsArray($groups['warning']); + $this->assertContainsOnlyInstancesOf(MappedError::class, $groups['error']); + $this->assertCount(2, $groups['error']); + $this->assertCount(3, $groups['warning']); + } + + public function testTheDiagnosticCanBeEncodedAsJson(): void + { + $json = $this->createAudit()->getDiagnostic(new AuditOptions( + validator: AuditOptions::VALIDATOR_SCHEMA_ORG, + asObject: true, + jsonEncode: true, + )); + + $this->assertIsString($json); + $this->assertSame( + [ + [ + 'message' => 'schema.org warning', + 'property' => 'name', + 'type' => 'Recipe', + 'severity' => 'warning', + 'validatorName' => 'SchemaOrg', + 'ranges' => '1:2 to 1:8', + 'path' => 'Recipe', + 'documentationLink' => 'https://schema.org/Recipe', + ], + ], + json_decode($json, true, flags: \JSON_THROW_ON_ERROR), + ); + } + + public function testAnUnknownSeverityIsRefused(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid severity query option provided: fatal'); + + $this->createAudit()->getDiagnostic(new AuditOptions(severity: 'fatal')); + } + + public function testAnUnknownValidatorIsRefused(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid validator query option provided: bing'); + + $this->createAudit()->getDiagnostic(new AuditOptions(validator: 'bing')); + } + + public function testAWarningKeepsTheAuditValidButNotFullyValid(): void + { + $type = new MappedType(sourceFormat: 'json-ld', type: 'Recipe'); + $audit = new Audit([$type]); + + $this->assertTrue($audit->isValid()); + $this->assertTrue($audit->isFullyValid()); + + $type->addError($this->error('only a warning', MappedError::SEVERITY_WARNING, GoogleValidator::VALIDATOR_NAME, $type)); + $audit = new Audit([$type]); + + $this->assertTrue($audit->isValid()); + $this->assertFalse($audit->isFullyValid()); + + $this->assertFalse($this->createAudit()->isValid()); + $this->assertFalse($this->createAudit()->isFullyValid()); + } + + public function testThePathOfAnErrorFallsBackFromItsParentToItsPropertyThenItsType(): void + { + $type = new MappedType(sourceFormat: 'json-ld', type: 'Recipe'); + $property = new MappedProperty('name', $type); + + $onProperty = new MappedError('message', 'name', 'Recipe', MappedError::SEVERITY_ERROR, 'Google', '', $property); + + $this->assertSame($property, $onProperty->getParent()); + $this->assertSame($property->getPath(), $onProperty->getPath()); + $this->assertSame('name', (new MappedError('message', 'name', 'Recipe', MappedError::SEVERITY_ERROR, 'Google', ''))->getPath()); + $this->assertSame('Recipe', (new MappedError('message', null, 'Recipe', MappedError::SEVERITY_ERROR, 'Google', ''))->getPath()); + $this->assertSame('', (new MappedError('message', null, null, MappedError::SEVERITY_ERROR, 'Google', ''))->getPath()); + } + + private function createAudit(): Audit + { + $type = new MappedType(sourceFormat: 'json-ld', type: 'Recipe'); + $type->addError($this->error('google error', MappedError::SEVERITY_ERROR, GoogleValidator::VALIDATOR_NAME, $type)); + $type->addError($this->error('google warning', MappedError::SEVERITY_WARNING, GoogleValidator::VALIDATOR_NAME, $type)); + $type->addError($this->error('schema.org warning', MappedError::SEVERITY_WARNING, SchemaOrgValidator::VALIDATOR_NAME, $type)); + $type->addError($this->error('merge warning', MappedError::SEVERITY_WARNING, MappedTypeMerger::VALIDATOR_NAME, $type)); + + return new Audit([$type], [$this->error('document error', MappedError::SEVERITY_ERROR, 'Document')]); + } + + private function error(string $message, string $severity, string $validatorName, ?MappedType $parent = null): MappedError + { + return new MappedError( + message: $message, + property: $parent ? 'name' : null, + type: $parent ? 'Recipe' : null, + severity: $severity, + validatorName: $validatorName, + ranges: '1:2 to 1:8', + parent: $parent, + documentationLink: 'https://schema.org/Recipe', + ); + } +} diff --git a/tests/Validation/Google/GoogleValidatorInfrastructureTest.php b/tests/Validation/Google/GoogleValidatorInfrastructureTest.php index c356383b1..26e5ec3ee 100644 --- a/tests/Validation/Google/GoogleValidatorInfrastructureTest.php +++ b/tests/Validation/Google/GoogleValidatorInfrastructureTest.php @@ -17,13 +17,10 @@ use JoliCode\StructuredData\Vocabularies\Validators\Google\GoogleValidator; use JoliCode\StructuredData\Vocabularies\Validators\Google\SpecialRules\SpecialRulesRegistry; use JoliCode\StructuredData\Vocabularies\Validators\Google\Stack; -use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\TestCase; -#[CoversClass(Stack::class)] -#[CoversClass(SpecialRulesRegistry::class)] #[Group('validation')] #[Group('google')] class GoogleValidatorInfrastructureTest extends TestCase diff --git a/tests/Validation/Google/GoogleValidatorTest.php b/tests/Validation/Google/GoogleValidatorTest.php index 26566ff21..575d73288 100644 --- a/tests/Validation/Google/GoogleValidatorTest.php +++ b/tests/Validation/Google/GoogleValidatorTest.php @@ -13,16 +13,12 @@ use JoliCode\StructuredData\Audit\AuditOptions; use JoliCode\StructuredData\Mapper\MappedError; -use JoliCode\StructuredData\Validator; use JoliCode\StructuredData\Vocabularies\Generated\Google\BookWork; use JoliCode\StructuredData\Vocabularies\Generated\Google\NewsArticle; use JoliCode\StructuredData\Vocabularies\Validators\Google\GoogleValidator; -use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; -#[CoversClass(Validator::class)] -#[CoversClass(GoogleValidator::class)] #[Group('validation')] #[Group('google')] class GoogleValidatorTest extends AbstractValidatorTestCase diff --git a/tests/Validation/JsonLdParserTest.php b/tests/Validation/JsonLdParserTest.php new file mode 100644 index 000000000..eb699668a --- /dev/null +++ b/tests/Validation/JsonLdParserTest.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Validation; + +use JoliCode\StructuredData\Extraction\ExtractorFormat; +use JoliCode\StructuredData\Extraction\JsonLdElement; +use JoliCode\StructuredData\JsonLd\Parser\DataStructures\AbstractStructure; +use JoliCode\StructuredData\JsonLd\Parser\DataStructures\ArrayStructure; +use JoliCode\StructuredData\JsonLd\Parser\DataStructures\ObjectStructure; +use JoliCode\StructuredData\JsonLd\Parser\JsonLdParser; +use JsonStreamingParser\Exception\ParsingException; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * Documents json_decode() refuses go through the streaming parser, which either + * reports where the document breaks or builds what it could read of it. + */ +#[Group('validation')] +class JsonLdParserTest extends TestCase +{ + public function testAMalformedDocumentReportsWhereItBreaks(): void + { + $this->expectException(ParsingException::class); + $this->expectExceptionMessage('Parsing error in [4:3]. Start of string expected for object key. Instead got: o'); + + $this->parse("{\n \"a\": {\"b\": 1},\n \"c\": [1, [2]],\n oops\n}"); + } + + public function testADocumentWithATrailingCommaIsStillRead(): void + { + $structure = $this->parse("{\n \"a\": {\"b\": 1},\n \"c\": [1, [2]],\n}"); + + $this->assertInstanceOf(ObjectStructure::class, $structure); + $this->assertTrue($structure->hasProperty('a')); + $this->assertTrue($structure->hasProperty('c')); + + $nested = $structure->getProperty('a')->value?->content; + $this->assertInstanceOf(ObjectStructure::class, $nested); + $this->assertTrue($nested->hasProperty('b')); + + $list = $structure->getProperty('c')->value?->content; + $this->assertInstanceOf(ArrayStructure::class, $list); + $this->assertCount(2, $list->getValues()); + $this->assertInstanceOf(ArrayStructure::class, $list->getValue(1)->content); + + // The positions are the ones the well-formed document gets from the fast parser. + $wellFormed = $this->parse("{\n \"a\": {\"b\": 1},\n \"c\": [1, [2]]\n}"); + $this->assertInstanceOf(ObjectStructure::class, $wellFormed); + + $this->assertSame('11:5 to 14:2', $this->range($structure)); + $this->assertSame('12:8 to 12:16', $this->range($nested)); + $this->assertSame('13:8 to 13:16', $this->range($list)); + $this->assertSame($this->range($wellFormed), $this->range($structure)); + $this->assertSame($this->range($wellFormed->getProperty('a')->value?->content), $this->range($nested)); + $this->assertSame($this->range($wellFormed->getProperty('c')->value?->content), $this->range($list)); + } + + private function range(mixed $structure): string + { + $this->assertInstanceOf(AbstractStructure::class, $structure); + + return $structure->range?->start . ' to ' . $structure->range?->end; + } + + private function parse(string $content): mixed + { + return (new JsonLdParser())->parse(new JsonLdElement(10, 4, $content, ExtractorFormat::JSONLD)); + } +} diff --git a/tests/Validation/SchemaOrg/SchemaOrgValidatorInfrastructureTest.php b/tests/Validation/SchemaOrg/SchemaOrgValidatorInfrastructureTest.php index a735eb920..a5b85c9d0 100644 --- a/tests/Validation/SchemaOrg/SchemaOrgValidatorInfrastructureTest.php +++ b/tests/Validation/SchemaOrg/SchemaOrgValidatorInfrastructureTest.php @@ -15,11 +15,9 @@ use JoliCode\StructuredData\Validator; use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrg\SchemaOrgValidator; use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrg\TypeGuesser; -use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\TestCase; -#[CoversClass(SchemaOrgValidator::class)] #[Group('validation')] #[Group('schemaorg')] #[Group('schema-org')] diff --git a/tests/Validation/SchemaOrg/SchemaOrgValidatorTest.php b/tests/Validation/SchemaOrg/SchemaOrgValidatorTest.php index 41e1a5c6c..9a73d512f 100644 --- a/tests/Validation/SchemaOrg/SchemaOrgValidatorTest.php +++ b/tests/Validation/SchemaOrg/SchemaOrgValidatorTest.php @@ -12,14 +12,10 @@ namespace JoliCode\StructuredData\Tests\Validation; use JoliCode\StructuredData\Audit\AuditOptions; -use JoliCode\StructuredData\Validator; use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrg\SchemaOrgValidator; -use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; -#[CoversClass(Validator::class)] -#[CoversClass(SchemaOrgValidator::class)] #[Group('validation')] #[Group('schemaorg')] #[Group('schema-org')]