From 9603e3baf516d01b52346282775a37a3f7e96250 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADtor=20de=20Oliveira?= Date: Wed, 25 Nov 2026 03:05:55 -0400 Subject: [PATCH] Replace ml/json-ld with a built-in JSON-LD reader JSON-LD is expanded without the unmaintained library, so PHP 8.4 and 8.5 no longer emit deprecations. Remote contexts are still never fetched; schema.org contexts stay bundled. LinkedData's public API is unchanged. --- CHANGELOG.md | 7 + composer.json | 3 +- src/JsonLd/DocumentLoader.php | 44 +-- src/JsonLd/Expander.php | 494 ++++++++++++++++++++++++++++++ src/JsonLd/JsonLdException.php | 10 + src/JsonLd/RemoteDocument.php | 24 ++ src/LinkedData.php | 85 +++-- tests/JsonLdRemoteContextTest.php | 2 +- 8 files changed, 601 insertions(+), 68 deletions(-) create mode 100644 src/JsonLd/Expander.php create mode 100644 src/JsonLd/JsonLdException.php create mode 100644 src/JsonLd/RemoteDocument.php diff --git a/CHANGELOG.md b/CHANGELOG.md index ecdff35d..13941ac3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [4.8.0] - 2026-11-25 +### Changed +- JSON-LD is read by a small built-in expander. The unmaintained `ml/json-ld` dependency is no longer used. Remote `@context` URLs are still never fetched; schema.org contexts stay bundled. `$info->getLinkedData()` (`get`, `getAll`, `all`) is unchanged [#554] [#582] + +### Fixed +- PHP 8.4 and 8.5 no longer emit deprecations while reading JSON-LD [#554] [#582] + ## [4.7.0] - 2026-11-23 ### Added - YouTube: `$info->image` is `maxresdefault.jpg` when the video page links it in `og:image`, instead of the oEmbed `hqdefault.jpg` with black bars [#535] diff --git a/composer.json b/composer.json index c727aa98..1fa130a1 100644 --- a/composer.json +++ b/composer.json @@ -34,8 +34,7 @@ "oscarotero/html-parser": "^0.1.6", "psr/http-message": "^1.0|^2.0", "psr/http-client": "^1.0", - "psr/http-factory": "^1.0", - "ml/json-ld": "^1.1" + "psr/http-factory": "^1.0" }, "require-dev": { "phpunit/phpunit": "^9.0", diff --git a/src/JsonLd/DocumentLoader.php b/src/JsonLd/DocumentLoader.php index df995881..52f33522 100644 --- a/src/JsonLd/DocumentLoader.php +++ b/src/JsonLd/DocumentLoader.php @@ -3,23 +3,15 @@ namespace Embed\JsonLd; -use ML\JsonLD\DocumentLoaderInterface; -use ML\JsonLD\Exception\JsonLdException; -use ML\JsonLD\Processor; -use ML\JsonLD\RemoteDocument; - /** * JSON-LD document loader that never touches the network or the filesystem. * - * LinkedData passes this as the documentLoader option. The global - * JsonLD::setDefaultDocumentLoader() is not used, so a host application - * keeps its own loader. - * - * schema.org context URLs are answered with a bundled vocabulary of - * {"@context":{"@vocab":"http://schema.org/"}}. Every other remote URL or - * path raises JsonLdException, which LinkedData already catches. + * The expander uses this when a document names a remote `@context`. schema.org + * context URLs are answered with a bundled vocabulary of + * {"@context":{"@vocab":"http://schema.org/"}}. Every other remote URL or path + * raises JsonLdException, which LinkedData already catches. */ -final class DocumentLoader implements DocumentLoaderInterface +final class DocumentLoader { private const SCHEMA_CONTEXT = '{"@context":{"@vocab":"http://schema.org/"}}'; @@ -34,24 +26,32 @@ final class DocumentLoader implements DocumentLoaderInterface * @param string $url * * @throws JsonLdException - * - * @return RemoteDocument */ - public function loadDocument($url) + public function loadDocument(string $url): RemoteDocument { $trimmed = trim($url); if (isset($trimmed[0]) && ($trimmed[0] === '{' || $trimmed[0] === '[')) { - return new RemoteDocument($url, Processor::parse($trimmed)); + return new RemoteDocument($url, self::parseJson($trimmed)); } if ($this->isSchemaOrgContext($trimmed)) { - return new RemoteDocument($url, Processor::parse(self::SCHEMA_CONTEXT), 'application/ld+json'); + return new RemoteDocument($url, self::parseJson(self::SCHEMA_CONTEXT)); + } + + throw new JsonLdException('Remote JSON-LD documents are not loaded.'); + } + + /** + * @return mixed + */ + private static function parseJson(string $json) + { + $document = json_decode($json); + if (json_last_error() !== JSON_ERROR_NONE) { + throw new JsonLdException('Invalid JSON-LD document: '.json_last_error_msg()); } - throw new JsonLdException( - JsonLdException::LOADING_REMOTE_CONTEXT_FAILED, - 'Remote JSON-LD documents are not loaded.' - ); + return $document; } private function isSchemaOrgContext(string $url): bool diff --git a/src/JsonLd/Expander.php b/src/JsonLd/Expander.php new file mode 100644 index 00000000..7fc61df5 --- /dev/null +++ b/src/JsonLd/Expander.php @@ -0,0 +1,494 @@ + */ + private const KEYWORDS = [ + '@base' => true, + '@container' => true, + '@context' => true, + '@direction' => true, + '@graph' => true, + '@id' => true, + '@import' => true, + '@included' => true, + '@index' => true, + '@json' => true, + '@language' => true, + '@list' => true, + '@nest' => true, + '@none' => true, + '@prefix' => true, + '@propagate' => true, + '@protected' => true, + '@reverse' => true, + '@set' => true, + '@type' => true, + '@value' => true, + '@version' => true, + '@vocab' => true, + ]; + + /** + * Expand compact JSON-LD into a flat list of nodes. + * + * @param array $data + * + * @return array> + */ + public static function expand(array $data): array + { + $expanded = self::expandElement($data, self::emptyContext()); + + return self::collectNodes($expanded); + } + + /** + * @return array{vocab:?string, language:?string, terms:array} + */ + private static function emptyContext(): array + { + return [ + 'vocab' => null, + 'language' => null, + 'terms' => [], + ]; + } + + /** + * @param mixed $element + * @param array{vocab:?string, language:?string, terms:array} $ctx + * + * @return mixed + */ + private static function expandElement($element, array $ctx) + { + if ($element === null) { + return null; + } + + if (is_string($element) || is_int($element) || is_float($element) || is_bool($element)) { + return self::valueObject($element, $ctx); + } + + if (!is_array($element)) { + throw new JsonLdException('Invalid JSON-LD value.'); + } + + if (self::isList($element)) { + $out = []; + foreach ($element as $item) { + $expanded = self::expandElement($item, $ctx); + if ($expanded === null) { + continue; + } + $out[] = $expanded; + } + + return $out; + } + + if (array_key_exists('@context', $element)) { + $ctx = self::processContext($element['@context'], $ctx); + } + + if (array_key_exists('@value', $element)) { + return self::expandValueObject(self::stringKeyed($element), $ctx); + } + + if (array_key_exists('@list', $element)) { + return self::expandElement($element['@list'], $ctx); + } + + if (array_key_exists('@set', $element)) { + return self::expandElement($element['@set'], $ctx); + } + + $node = []; + + if (isset($element['@id']) && is_string($element['@id']) && $element['@id'] !== '') { + $node['@id'] = self::expandIri($element['@id'], $ctx, false); + } + + if (isset($element['@type'])) { + $types = is_array($element['@type']) ? $element['@type'] : [$element['@type']]; + $expandedTypes = []; + foreach ($types as $type) { + if (is_string($type) && $type !== '') { + $expandedTypes[] = self::expandIri($type, $ctx, true); + } + } + if ($expandedTypes !== []) { + $node['@type'] = $expandedTypes; + } + } + + if (isset($element['@graph']) && is_array($element['@graph'])) { + $graph = self::expandElement($element['@graph'], $ctx); + $node['@graph'] = self::asList($graph); + } + + foreach ($element as $key => $value) { + if (!is_string($key) || $key === '' || isset(self::KEYWORDS[$key])) { + continue; + } + + $property = self::expandIri($key, $ctx, true); + if ($property === '' || isset(self::KEYWORDS[$property])) { + continue; + } + + $termType = $ctx['terms'][$key]['type'] ?? null; + $expandedValues = self::expandPropertyValue($value, $ctx, $termType); + if ($expandedValues === []) { + continue; + } + + $node[$property] = $expandedValues; + } + + return $node; + } + + /** + * @param mixed $value + * @param array{vocab:?string, language:?string, terms:array} $ctx + * + * @return array + */ + private static function expandPropertyValue($value, array $ctx, ?string $termType): array + { + if ($value === null) { + return []; + } + + $items = (is_array($value) && self::isList($value)) ? $value : [$value]; + $out = []; + + foreach ($items as $item) { + if ($termType === '@id' && is_string($item) && $item !== '') { + $out[] = ['@id' => self::expandIri($item, $ctx, false)]; + continue; + } + + $expanded = self::expandElement($item, $ctx); + if ($expanded === null) { + continue; + } + + if (is_array($expanded) && self::isList($expanded)) { + foreach ($expanded as $entry) { + $out[] = $entry; + } + continue; + } + + $out[] = $expanded; + } + + return $out; + } + + /** + * @param array $element + * @param array{vocab:?string, language:?string, terms:array} $ctx + * + * @return array + */ + private static function expandValueObject(array $element, array $ctx): array + { + $value = ['@value' => $element['@value']]; + if (isset($element['@language']) && is_string($element['@language'])) { + $value['@language'] = $element['@language']; + } elseif (is_string($element['@value']) && is_string($ctx['language']) && $ctx['language'] !== '') { + $value['@language'] = $ctx['language']; + } + if (isset($element['@type']) && is_string($element['@type'])) { + $value['@type'] = self::expandIri($element['@type'], $ctx, true); + } + + return $value; + } + + /** + * @param mixed $value + * @param array{vocab:?string, language:?string, terms:array} $ctx + * + * @return array + */ + private static function valueObject($value, array $ctx): array + { + $result = ['@value' => $value]; + if (is_string($value) && is_string($ctx['language']) && $ctx['language'] !== '') { + $result['@language'] = $ctx['language']; + } + + return $result; + } + + /** + * @param mixed $context + * @param array{vocab:?string, language:?string, terms:array} $ctx + * + * @return array{vocab:?string, language:?string, terms:array} + */ + private static function processContext($context, array $ctx): array + { + if ($context === null) { + return self::emptyContext(); + } + + if (is_string($context)) { + $document = (new DocumentLoader())->loadDocument($context)->document; + $decoded = self::toArray($document); + if (is_array($decoded) && array_key_exists('@context', $decoded)) { + return self::processContext($decoded['@context'], $ctx); + } + + return self::processContext($decoded, $ctx); + } + + if (!is_array($context)) { + throw new JsonLdException('Invalid JSON-LD context.'); + } + + if (self::isList($context)) { + foreach ($context as $item) { + $ctx = self::processContext($item, $ctx); + } + + return $ctx; + } + + if (array_key_exists('@vocab', $context)) { + $vocab = $context['@vocab']; + if ($vocab === null || $vocab === '') { + $ctx['vocab'] = null; + } elseif (is_string($vocab)) { + $ctx['vocab'] = $vocab; + } else { + throw new JsonLdException('Invalid JSON-LD @vocab.'); + } + } + + if (array_key_exists('@language', $context)) { + $language = $context['@language']; + $ctx['language'] = is_string($language) ? $language : null; + } + + foreach ($context as $term => $definition) { + if (!is_string($term) || $term === '' || isset(self::KEYWORDS[$term])) { + continue; + } + + if (is_string($definition) && $definition !== '') { + $ctx['terms'][$term] = [ + 'id' => self::expandIri($definition, $ctx, true), + 'type' => null, + ]; + continue; + } + + if (!is_array($definition)) { + continue; + } + + $id = $definition['@id'] ?? $term; + if (!is_string($id) || $id === '') { + continue; + } + + $type = $definition['@type'] ?? null; + $ctx['terms'][$term] = [ + 'id' => self::expandIri($id, $ctx, true), + 'type' => is_string($type) ? $type : null, + ]; + } + + return $ctx; + } + + /** + * @param array{vocab:?string, language:?string, terms:array} $ctx + */ + private static function expandIri(string $value, array $ctx, bool $relativeToVocab): string + { + if ($value === '' || isset(self::KEYWORDS[$value])) { + return $value; + } + + if (isset($ctx['terms'][$value])) { + return $ctx['terms'][$value]['id']; + } + + if (preg_match('#^[a-zA-Z][a-zA-Z0-9+.-]*://#', $value) === 1) { + return $value; + } + + $colon = strpos($value, ':'); + if ($colon !== false) { + $prefix = substr($value, 0, $colon); + $suffix = substr($value, $colon + 1); + if (isset($ctx['terms'][$prefix]) && strpos($suffix, '//') !== 0) { + return $ctx['terms'][$prefix]['id'].$suffix; + } + if (preg_match('/^[a-zA-Z][a-zA-Z0-9+.-]*$/', $prefix) === 1) { + return $value; + } + } + + if ($relativeToVocab && is_string($ctx['vocab']) && $ctx['vocab'] !== '') { + return $ctx['vocab'].$value; + } + + return $value; + } + + /** + * @param mixed $expanded + * + * @return array> + */ + private static function collectNodes($expanded): array + { + $nodes = []; + self::walkNodes($expanded, $nodes); + + return $nodes; + } + + /** + * @param mixed $expanded + * @param array> $nodes + */ + private static function walkNodes($expanded, array &$nodes): void + { + if (!is_array($expanded)) { + return; + } + + if (self::isList($expanded)) { + foreach ($expanded as $item) { + self::walkNodes($item, $nodes); + } + + return; + } + + if (array_key_exists('@value', $expanded)) { + return; + } + + if (isset($expanded['@graph']) && is_array($expanded['@graph'])) { + $hasOtherProperties = false; + foreach ($expanded as $key => $_) { + if ($key !== '@graph' && $key !== '@id' && $key !== '@type') { + $hasOtherProperties = true; + break; + } + } + if ($hasOtherProperties) { + $nodes[] = self::stringKeyed($expanded); + } + self::walkNodes($expanded['@graph'], $nodes); + + return; + } + + $nodes[] = self::stringKeyed($expanded); + + foreach ($expanded as $key => $value) { + if ($key === '@id' || $key === '@type') { + continue; + } + self::walkNodes($value, $nodes); + } + } + + /** + * JSON lists are 0-indexed arrays. LinkedData lives in namespace Embed, + * so it can see the array_is_list polyfill in functions.php; this class + * cannot, and PHP 7.4 / 8.0 have no global array_is_list. + * + * @param array $value + */ + private static function isList(array $value): bool + { + $i = 0; + foreach ($value as $key => $_) { + if ($key !== $i) { + return false; + } + ++$i; + } + + return true; + } + + /** + * @param array $value + * + * @return array + */ + private static function stringKeyed(array $value): array + { + $result = []; + foreach ($value as $key => $item) { + if (is_string($key)) { + $result[$key] = $item; + } + } + + return $result; + } + + /** + * @param mixed $value + * + * @return array + */ + private static function asList($value): array + { + if ($value === null) { + return []; + } + if (is_array($value) && self::isList($value)) { + return array_values($value); + } + + return [$value]; + } + + /** + * @param mixed $value + * + * @return mixed + */ + private static function toArray($value) + { + if (is_object($value)) { + $value = get_object_vars($value); + } + if (!is_array($value)) { + return $value; + } + + $result = []; + foreach ($value as $key => $item) { + $result[$key] = self::toArray($item); + } + + return $result; + } +} diff --git a/src/JsonLd/JsonLdException.php b/src/JsonLd/JsonLdException.php new file mode 100644 index 00000000..17985a61 --- /dev/null +++ b/src/JsonLd/JsonLdException.php @@ -0,0 +1,10 @@ +documentUrl = $documentUrl; + $this->document = $document; + } +} diff --git a/src/LinkedData.php b/src/LinkedData.php index b71eab6e..ed7646f2 100644 --- a/src/LinkedData.php +++ b/src/LinkedData.php @@ -3,19 +3,18 @@ namespace Embed; -use Embed\JsonLd\DocumentLoader; +use Embed\JsonLd\Expander; use Exception; -use ML\JsonLD\Document as LdDocument; -use ML\JsonLD\DocumentInterface; -use ML\JsonLD\GraphInterface; -use ML\JsonLD\Node; use Throwable; class LinkedData { use ApiTrait; - private ?DocumentInterface $document = null; + /** @var array>|null */ + private ?array $graph = null; + + private bool $graphLoaded = false; /** @var array */ private array $allData = []; @@ -34,7 +33,7 @@ public function get(string ...$keys) foreach ($keys as $key) { $subkeys = explode('.', $key); - foreach ($graph->getNodes() as $node) { + foreach ($graph as $node) { $value = self::getValue($node, ...$subkeys); if ($value !== null && $value !== '' && $value !== false && $value !== []) { @@ -58,34 +57,24 @@ public function getAll(): array return $this->allData; } - private function getGraph(?string $name = null): ?GraphInterface + /** + * @return array>|null + */ + private function getGraph(): ?array { - if (!isset($this->document)) { - try { - $encoded = json_encode($this->all()); - if ($encoded === false) { - $encoded = '{}'; - } - $this->document = self::loadJsonLd($encoded); - } catch (Throwable $throwable) { - try { - $this->document = self::loadJsonLd('{}'); - } catch (Throwable $ignored) { - $this->document = new LdDocument(); - } - - return null; - } + if ($this->graphLoaded) { + return $this->graph; } - return $this->document->getGraph($name); - } + $this->graphLoaded = true; - private static function loadJsonLd(string $json): DocumentInterface - { - return LdDocument::load($json, [ - 'documentLoader' => new DocumentLoader(), - ]); + try { + $this->graph = Expander::expand($this->all()); + } catch (Throwable $throwable) { + $this->graph = null; + } + + return $this->graph; } /** @@ -153,23 +142,28 @@ protected function fetchData(): array } /** + * @param mixed $node * @return mixed */ - private static function getValue(Node $node, string ...$keys) + private static function getValue($node, string ...$keys) { foreach ($keys as $key) { - if (is_array($node)) { + if (is_array($node) && array_is_list($node)) { $node = array_shift($node); } - if (!$node instanceof Node) { + if (!is_array($node) || array_key_exists('@value', $node)) { return null; } - $node = $node->getProperty("http://schema.org/{$key}"); - - if ($node === null) { + $property = 'http://schema.org/'.$key; + if (!array_key_exists($property, $node)) { return null; } + + $node = $node[$property]; + if (is_array($node) && array_is_list($node) && count($node) === 1) { + $node = $node[0]; + } } return self::detectValue($node); @@ -181,9 +175,9 @@ private static function getValue(Node $node, string ...$keys) */ private static function detectValue($value) { - if (is_array($value)) { + if (is_array($value) && array_is_list($value)) { return array_map( - fn ($val) => self::detectValue($val), + static fn ($val) => self::detectValue($val), array_values($value) ); } @@ -192,12 +186,17 @@ private static function detectValue($value) return $value; } - if ($value instanceof Node) { - return $value->getId(); + if (!is_array($value)) { + return null; + } + + if (array_key_exists('@value', $value)) { + $inner = $value['@value']; + return is_scalar($inner) ? $inner : null; } - if (is_object($value) && method_exists($value, 'getValue')) { - return $value->getValue(); + if (isset($value['@id']) && is_string($value['@id'])) { + return $value['@id']; } return null; diff --git a/tests/JsonLdRemoteContextTest.php b/tests/JsonLdRemoteContextTest.php index bc6ebdb7..d16cc575 100644 --- a/tests/JsonLdRemoteContextTest.php +++ b/tests/JsonLdRemoteContextTest.php @@ -8,7 +8,7 @@ use Embed\Http\Crawler; use Embed\Http\UrlPolicy; use Embed\JsonLd\DocumentLoader; -use ML\JsonLD\Exception\JsonLdException; +use Embed\JsonLd\JsonLdException; use Nyholm\Psr7\Factory\Psr17Factory; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface;