Skip to content

Commit

Permalink
Fix parsing objects with non-string type
Browse files Browse the repository at this point in the history
If a schema.org object has a non string @type, it is ignored and a
warning is logged, if the class has a logger.
  • Loading branch information
otsch committed May 25, 2023
1 parent 6f0185a commit 05d4a9e
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.2.0] - 2022-05-17
## [0.2.1] - 2023-05-25
### Fixed
* If a schema.org object has a non string @type, it is ignored and a warning is logged, if the class has a logger.

## [0.2.0] - 2023-05-17
### Added
* You can now optionally pass a PSR-3 LoggerInterface to the `SchemaOrg` class, so it'll log decoding errors.

Expand Down
6 changes: 6 additions & 0 deletions src/SchemaOrg.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,12 @@ private function convertJsonDataToSchemaOrgObject(array $json, bool $isChild = f
return null;
}

if (!is_string($json['@type'])) {
$this->logger?->warning('Can\'t convert schema.org object with non-string type.');

return null;
}

$className = $this->types->getClassName($json['@type']);

if (!$className) {
Expand Down
25 changes: 25 additions & 0 deletions tests/SchemaOrgTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,31 @@
expect($schemaOrgObjects)->toBeEmpty();
});

it('returns null if the schema.org object doesn\'t have a distinct type', function () {
$html = <<<HTML
<!DOCTYPE html>
<html lang="de-AT">
<head>
<title>Hello world</title>
</head>
<body>
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": ["CreativeWork", "Product"],
"name" : "something",
"productID": "123abc"
}
</script>
</body>
</html>
HTML;

$schemaOrgObjects = SchemaOrg::fromHtml($html);

expect($schemaOrgObjects)->toBeEmpty();
});

test('you can pass it a PSR-3 LoggerInterface and it will log an error message for invalid JSON string', function () {
$scriptBlockContent = <<<INVALIDJSON
{
Expand Down

0 comments on commit 05d4a9e

Please sign in to comment.