Skip to content

Commit

Permalink
Merge pull request #102 from spatie/ft-ld-json-id
Browse files Browse the repository at this point in the history
serialize identifier to ld+json @id
  • Loading branch information
Gummibeer authored Sep 26, 2019
2 parents e7f5288 + 01dc3ac commit 5ede7ed
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
9 changes: 9 additions & 0 deletions generator/templates/static/BaseType.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public function offsetUnset($offset)

public function toArray(): array
{
$this->serializeIdentifier();
$properties = $this->serializeProperty($this->getProperties());

return [
Expand Down Expand Up @@ -115,6 +116,14 @@ protected function serializeProperty($property)
return $property;
}

protected function serializeIdentifier()
{
if (isset($this['identifier'])) {
$this->setProperty('@id', $this['identifier']);
unset($this['identifier']);
}
}

public function toScript(): string
{
return '<script type="application/ld+json">'.json_encode($this->toArray(), JSON_UNESCAPED_UNICODE).'</script>';
Expand Down
9 changes: 9 additions & 0 deletions src/BaseType.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public function offsetUnset($offset)

public function toArray(): array
{
$this->serializeIdentifier();
$properties = $this->serializeProperty($this->getProperties());

return [
Expand Down Expand Up @@ -115,6 +116,14 @@ protected function serializeProperty($property)
return $property;
}

protected function serializeIdentifier()
{
if (isset($this['identifier'])) {
$this->setProperty('@id', $this['identifier']);
unset($this['identifier']);
}
}

public function toScript(): string
{
return '<script type="application/ld+json">'.json_encode($this->toArray(), JSON_UNESCAPED_UNICODE).'</script>';
Expand Down
16 changes: 16 additions & 0 deletions tests/BaseTypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,22 @@ public function it_can_be_casted_to_string()

$this->assertEquals($expected, (string) $type);
}

/** @test */
public function it_replaces_identifier_with_at_id_property()
{
$type = new DummyType();

$type->setProperty('identifier', 'object#1');

$expected = [
'@context' => 'https://schema.org',
'@type' => 'DummyType',
'@id' => 'object#1',
];

$this->assertEquals($expected, $type->toArray());
}
}

class DummyType extends BaseType
Expand Down

0 comments on commit 5ede7ed

Please sign in to comment.