Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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