diff --git a/src/SEOTools/JsonLd.php b/src/SEOTools/JsonLd.php index df2be50..b5b39e0 100644 --- a/src/SEOTools/JsonLd.php +++ b/src/SEOTools/JsonLd.php @@ -85,21 +85,34 @@ public function isEmpty() /** * {@inheritdoc} */ - public function generate($minify = false) + public function generate($minify = false): string { - $generated = [ - '@context' => 'https://schema.org', - ]; + $generated = array_merge( + [ + '@context' => 'https://schema.org', + ], + $this->convertToArray() + ); - if (! empty($this->type)) { + return ''; + } + + /** + * @return string[]|string[][] + */ + public function convertToArray(): array + { + $generated = []; + + if (!empty($this->type)) { $generated['@type'] = $this->type; } - if (! empty($this->title)) { + if (!empty($this->title)) { $generated['name'] = $this->title; } - if (! empty($this->description)) { + if (!empty($this->description)) { $generated['description'] = $this->description; } @@ -107,13 +120,33 @@ public function generate($minify = false) $generated['url'] = $this->url ?? app('url')->full(); } - if (! empty($this->images)) { + if (!empty($this->images)) { $generated['image'] = count($this->images) === 1 ? reset($this->images) : $this->images; } - $generated = array_merge($generated, $this->values); + return self::convertSelfObjectInArray(array_merge($generated, $this->values)); + } - return ''; + /** + * @param mixed[] $values + * + * @return string[]|string[][] + */ + private static function convertSelfObjectInArray(array $values): array + { + foreach ($values as $key => $value) { + if (is_array($value)) { + $values[$key] = self::convertSelfObjectInArray($value); + + continue; + } + + if ($value instanceof self) { + $values[$key] = $value->convertToArray(); + } + } + + return $values; } /** diff --git a/tests/SEOTools/JsonLdTest.php b/tests/SEOTools/JsonLdTest.php index bc5f868..d05583d 100644 --- a/tests/SEOTools/JsonLdTest.php +++ b/tests/SEOTools/JsonLdTest.php @@ -134,6 +134,32 @@ public function test_array_add_value() $this->setRightAssertion($expected); } + public function test_self_add_value() + { + $this->jsonLd->addValue('author', new JsonLd([ + 'type' => 'Organization', + 'name' => 'SeoTools', + 'url' => 'https://github.com/artesaos/seotools', + ])); + + $expected = ''; + + $this->setRightAssertion($expected); + } + + public function test_self_array_add_value() + { + $this->jsonLd->addValue('author', [new JsonLd([ + 'type' => 'Organization', + 'name' => 'SeoTools', + 'url' => 'https://github.com/artesaos/seotools', + ])]); + + $expected = ''; + + $this->setRightAssertion($expected); + } + public function test_add_values() { $this->jsonLd->addValues([