diff --git a/.gitignore b/.gitignore index 9b0a638..6e6169a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,8 @@ /composer.lock /.env.test /.phpunit.result.cache +.php-cs-fixer.dist.php +rector.php +Makefile +phpstan-dev.neon +.ddev \ No newline at end of file diff --git a/composer.json b/composer.json index 2a67453..ce71ca2 100644 --- a/composer.json +++ b/composer.json @@ -11,26 +11,26 @@ ], "require": { "php": "^8.2", - "symfony/dependency-injection": "^6.0 || ^7.0 || ^8.0", - "symfony/config": "^6.0 || ^7.0 || ^8.0" , + "symfony/dependency-injection": "^6.4 || ^7.0 || ^8.0", + "symfony/config": "^6.4 || ^7.0 || ^8.0" , "twig/twig": "^2.0 || ^3.0", - "symfony/cache": "^6.0 || ^7.0 || ^8.0", - "symfony/http-kernel": "^6.0 | ^7.0 || ^8.0", - "symfony/routing": "^6.0 || ^7.0 || ^8.0", + "symfony/cache": "^6.4 || ^7.0 || ^8.0", + "symfony/http-kernel": "^6.4 | ^7.0 || ^8.0", + "symfony/routing": "^6.4 || ^7.0 || ^8.0", "doctrine/persistence": "^3.4 || ^4.0", - "symfony/messenger": "^6.0 || ^7.0 || ^8.0", + "symfony/messenger": "^6.4 || ^7.0 || ^8.0", "ext-dom": "*", - "symfony/console": "^6.0 || ^7.0 || ^8.0", - "symfony/event-dispatcher": "^6.0 || ^7.0 || ^8.0" + "symfony/console": "^6.4 || ^7.0 || ^8.0", + "symfony/event-dispatcher": "^6.4 || ^7.0 || ^8.0" }, "require-dev": { "phpstan/phpstan": "^2.1", "phpunit/phpunit": "^11 || ^12.1", "symfony/test-pack": "^1.0", - "symfony/framework-bundle": "^6.0 || ^7.0 || ^8.0", - "symfony/yaml": "^6.0 || ^7.0 || ^8.0", + "symfony/framework-bundle": "^6.4 || ^7.0 || ^8.0", + "symfony/yaml": "^6.4 || ^7.0 || ^8.0", "symfony/profiler-pack": "^1.0", - "symfony/serializer": "^6.0 || ^7.0 || ^8.0" + "symfony/serializer": "^6.4 || ^7.0 || ^8.0" }, "license": "MIT", "autoload": { diff --git a/config/definition.php b/config/definition.php index e173c61..311619d 100644 --- a/config/definition.php +++ b/config/definition.php @@ -18,6 +18,11 @@ ->addDefaultsIfNotSet() ->children() ->booleanNode('enabled')->defaultFalse()->end() + ->integerNode('cache_ttl') + ->info('Cache TTL in seconds') + ->defaultValue(604800) + ->min(0) + ->end() ->end() ->end() ->arrayNode('meta_tags') diff --git a/config/services.php b/config/services.php index 5defa88..ac5ba91 100644 --- a/config/services.php +++ b/config/services.php @@ -66,8 +66,7 @@ $services->set('seo.meta.tags', MetaTagsManager::class)->tag('kernel.reset', ['method' => 'reset']); $services->alias(MetaTagsManagerInterface::class, 'seo.meta.tags'); $services->set(MetaTagsExtension::class, MetaTagsExtension::class) - ->autowire() - ->tag('twig.extension'); + ->autowire(); $services->set('seo.sitemap', Sitemap::class); $services->alias(SitemapInterface::class, 'seo.sitemap')->public(); @@ -76,8 +75,7 @@ $services->set('open.graph.bundle', OpenGraphManager::class); $services->alias(OpenGraphManagerInterface::class, 'open.graph.bundle')->public(); - $services->set('open.graph.bundle.twig.extension', OpenGraphExtension::class) - ->tag('twig.extension'); + $services->set('open.graph.bundle.twig.extension', OpenGraphExtension::class); $services->set('open.graph', OpenGraphManager::class)->tag('kernel.reset', ['method' => 'reset']); @@ -144,6 +142,5 @@ ->alias(BreadcrumbManagerInterface::class, 'seo.breadcrumb')->public(); $services ->set(BreadcrumbExtension::class, BreadcrumbExtension::class) - ->autowire() - ->tag('twig.extension'); + ->autowire(); }; \ No newline at end of file diff --git a/src/Breadcrumb/BreadcrumbManager.php b/src/Breadcrumb/BreadcrumbManager.php index 3d7a882..a10b531 100644 --- a/src/Breadcrumb/BreadcrumbManager.php +++ b/src/Breadcrumb/BreadcrumbManager.php @@ -1,4 +1,7 @@ $items + * @param array $options + */ public function __construct( public array $items = [], public array $options = [], @@ -24,7 +31,6 @@ public function __construct( $this->options['active_item'] = 'active'; } - public function addItem(string $label, ?string $url = null): static { $this->items[] = [ @@ -35,27 +41,34 @@ public function addItem(string $label, ?string $url = null): static return $this; } - /** - * @inheritDoc - */ public function reset(): void { $this->items = []; } + /** + * @return array + */ public function getItems(): array { - return $this->items; + return $this->items; } + /** + * @return array + */ public function getOptions(): array { return $this->options; } + /** + * @param array $options + */ public function setOptions(array $options): static { $this->options = $options; + return $this; } -} \ No newline at end of file +} diff --git a/src/Breadcrumb/BreadcrumbManagerInterface.php b/src/Breadcrumb/BreadcrumbManagerInterface.php index a683a9e..df979a1 100644 --- a/src/Breadcrumb/BreadcrumbManagerInterface.php +++ b/src/Breadcrumb/BreadcrumbManagerInterface.php @@ -1,4 +1,7 @@ + */ public function getItems(): array; + /** + * @return array + */ public function getOptions(): array; + /** + * @param array $options + */ public function setOptions(array $options): static; -} \ No newline at end of file +} diff --git a/src/Command/GenerateSitemapCommand.php b/src/Command/GenerateSitemapCommand.php index 4a4a194..5a293c6 100644 --- a/src/Command/GenerateSitemapCommand.php +++ b/src/Command/GenerateSitemapCommand.php @@ -1,4 +1,5 @@ addArgument('baseUrl', InputArgument::REQUIRED, 'The base url to generate sitemap'); - } + public function __invoke( + #[Argument(description: 'The base url to generate sitemap', name: 'Base Url')] + string $baseUrl, + SymfonyStyle $symfonyStyle + ): int { + $this->messageBus->dispatch(new GenerateSitemapMessage($baseUrl)); + $symfonyStyle->success('Generating Sitemap'); - protected function execute(InputInterface $input, OutputInterface $output): int - { - $this->messageBus->dispatch(new GenerateSitemapMessage($input->getArgument('baseUrl'))); - $output->writeln("Generating Sitemap"); return Command::SUCCESS; } } diff --git a/src/DataCollector/SeoCollector.php b/src/DataCollector/SeoCollector.php index 9ad99ea..686f8b7 100644 --- a/src/DataCollector/SeoCollector.php +++ b/src/DataCollector/SeoCollector.php @@ -1,4 +1,7 @@ data['seo_metas'] = $this->normalizer->normalize( $this->metaTagsManager->getSeoMeta(), @@ -53,22 +60,36 @@ public function collect(Request $request, Response $response, ?\Throwable $excep ); } - /** @return [] */ + /** + * @return array + */ public function getSeoMetas(): array { - return $this->data['seo_metas']; + $data = $this->data['seo_metas'] ?? []; + assert(is_array($data)); + + /** @var array $returnData */ + $returnData = $data; + + return $returnData; } - /** @return [] */ + /** + * @return array + */ public function getOpenGraph(): array { - return $this->data['open_graph']; - } + $data = $this->data['open_graph'] ?? []; + assert(is_array($data)); + + /** @var array $returnData */ + $returnData = $data; + return $returnData; + } public function reset(): void { $this->data = []; } - -} \ No newline at end of file +} diff --git a/src/DependencyInjection/CompilerPasses/GoogleTagCompilerPass.php b/src/DependencyInjection/CompilerPasses/GoogleTagCompilerPass.php index c33ae10..5cac435 100644 --- a/src/DependencyInjection/CompilerPasses/GoogleTagCompilerPass.php +++ b/src/DependencyInjection/CompilerPasses/GoogleTagCompilerPass.php @@ -1,4 +1,5 @@ findTaggedServiceIds('seo.google_tag_manager') as $id => $tags) { - $definition->addMethodCall('enableGoogleTagManager',[ - $container->getParameter('seo.google_tag_manager')['tag_manager_id'], + foreach ($container->findTaggedServiceIds('seo.google_tag_manager') as $tags) { + $config = $container->getParameter('seo.google_tag_manager'); + assert(is_array($config)); + + $definition->addMethodCall('enableGoogleTagManager', [ + $config['tag_manager_id'], ]); } } diff --git a/src/DependencyInjection/CompilerPasses/MetaPixelCompilerPass.php b/src/DependencyInjection/CompilerPasses/MetaPixelCompilerPass.php index 794060d..82e2930 100644 --- a/src/DependencyInjection/CompilerPasses/MetaPixelCompilerPass.php +++ b/src/DependencyInjection/CompilerPasses/MetaPixelCompilerPass.php @@ -1,4 +1,7 @@ hasDefinition('seo.meta_pixel')) { @@ -32,10 +34,13 @@ public function process(ContainerBuilder $container): void return; } - foreach ($container->findTaggedServiceIds('seo.meta_pixel') as $id => $tags) { + foreach ($container->findTaggedServiceIds('seo.meta_pixel') as $tags) { + $config = $container->getParameter('seo.meta_pixel'); + assert(is_array($config)); + $definition->addMethodCall('enableMetaPixel', [ - $container->getParameter('seo.meta_pixel')['pixel_id'], + $config['pixel_id'], ]); } } -} \ No newline at end of file +} diff --git a/src/EventSubscriber/GoogleTagInjectorSubscriber.php b/src/EventSubscriber/GoogleTagInjectorSubscriber.php index e961087..bbb5e0c 100644 --- a/src/EventSubscriber/GoogleTagInjectorSubscriber.php +++ b/src/EventSubscriber/GoogleTagInjectorSubscriber.php @@ -1,4 +1,7 @@ > */ public static function getSubscribedEvents(): array { @@ -32,30 +38,24 @@ public static function getSubscribedEvents(): array ]; } - public function onKernelResponse(ResponseEvent $event): void + public function onKernelResponse(ResponseEvent $responseEvent): void { - $response = $event->getResponse(); - $request = $event->getRequest(); - - if (!str_contains($request->headers->get('accept', ''), 'text/html' )) return; - - $body = $response->getContent(); - - if (!$event->isMainRequest() || $request->isXmlHttpRequest()) { + $body = $this->getProcessableHtmlBody($responseEvent); + if (null === $body) { return; } $headerTag = $this->tagManager->renderHeadTag(); $bodyTag = $this->tagManager->renderBodyTag(); - if ($headerTag) { - $body = str_replace('', $headerTag . PHP_EOL . '', $body); + if ('' !== $headerTag && '0' !== $headerTag) { + $body = str_replace('', $headerTag.\PHP_EOL.'', $body); } - if ($bodyTag) { - $body = str_replace('', $bodyTag . "\n", $body); + if ('' !== $bodyTag && '0' !== $bodyTag) { + $body = str_replace('', $bodyTag."\n", $body); } - $response->setContent($body); + $responseEvent->getResponse()->setContent($body); } -} \ No newline at end of file +} diff --git a/src/EventSubscriber/HtmlResponseValidationTrait.php b/src/EventSubscriber/HtmlResponseValidationTrait.php new file mode 100644 index 0000000..9edad83 --- /dev/null +++ b/src/EventSubscriber/HtmlResponseValidationTrait.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, + * please view the LICENSE file that was distributed with this source code. + */ + +namespace Rami\SeoBundle\EventSubscriber; + +use Symfony\Component\HttpKernel\Event\ResponseEvent; + +use function is_string; + +trait HtmlResponseValidationTrait +{ + /** + * Validates if the response should be processed for HTML content injection. + * + * Checks: + * - Accept header contains 'text/html' + * - Response body is not empty + * - Is main request (not sub-request) + * - Is not AJAX request + * + * @return string|null Returns the response body if valid, null otherwise + */ + private function getProcessableHtmlBody(ResponseEvent $responseEvent): ?string + { + $response = $responseEvent->getResponse(); + $request = $responseEvent->getRequest(); + + $acceptHeader = $request->headers->get('accept', ''); + if (!is_string($acceptHeader) || !str_contains($acceptHeader, 'text/html')) { + return null; + } + + $body = $response->getContent(); + if (false === $body) { + return null; + } + + if (!$responseEvent->isMainRequest() || $request->isXmlHttpRequest()) { + return null; + } + + return $body; + } +} diff --git a/src/EventSubscriber/MetaPixelInjectorSubscriber.php b/src/EventSubscriber/MetaPixelInjectorSubscriber.php index e66903c..8726244 100644 --- a/src/EventSubscriber/MetaPixelInjectorSubscriber.php +++ b/src/EventSubscriber/MetaPixelInjectorSubscriber.php @@ -1,4 +1,7 @@ getResponse(); - $request = $event->getRequest(); - - if (!str_contains($request->headers->get('accept', ''), 'text/html' )) return; - - $body = $response->getContent(); - - if (!$event->isMainRequest() || $request->isXmlHttpRequest()) { + $body = $this->getProcessableHtmlBody($responseEvent); + if (null === $body) { return; } $headerContent = $this->metaPixel->renderPixel(); - if ($headerContent) { - $body = str_replace('', $headerContent . PHP_EOL . '', $body); + if ('' !== $headerContent && '0' !== $headerContent) { + $body = str_replace('', $headerContent.\PHP_EOL.'', $body); } - $response->setContent($body); + $responseEvent->getResponse()->setContent($body); } -} \ No newline at end of file +} diff --git a/src/EventSubscriber/SchemaTwigInjectorSubscriber.php b/src/EventSubscriber/SchemaTwigInjectorSubscriber.php index 64484ce..cd67108 100644 --- a/src/EventSubscriber/SchemaTwigInjectorSubscriber.php +++ b/src/EventSubscriber/SchemaTwigInjectorSubscriber.php @@ -1,4 +1,7 @@ > */ public static function getSubscribedEvents(): array { @@ -34,36 +52,51 @@ public static function getSubscribedEvents(): array ]; } - public function onKernelResponse(ResponseEvent $event): void + public function onKernelResponse(ResponseEvent $responseEvent): void { if (!$this->parameterBag->has('seo.schema')) { return; } - if (!$this->parameterBag->get('seo.schema')['enabled']) { + $config = $this->parameterBag->get('seo.schema'); + assert(is_array($config)); + + if (!$config['enabled']) { return; } - $response = $event->getResponse(); - $request = $event->getRequest(); - - if (!str_contains($request->headers->get('accept', ''), 'text/html' )) return; - - $body = $response->getContent(); + $body = $this->getProcessableHtmlBody($responseEvent); + if (null === $body) { + return; + } - if (!$event->isMainRequest() || $request->isXmlHttpRequest()) { + $type = $this->schema->getType(); + if (!$type instanceof BaseType) { return; } - $content = $this->schema->getType() ? $this->schema->getType()->render() : null; + $route = $responseEvent->getRequest()->attributes->get('_route', 'unknown'); + assert(is_string($route)); + + $properties = $type->getProperties(); + $cacheKey = sprintf( + 'schema_render_%s_%s', + $route, + md5(serialize($properties)) + ); - if (null === $content) { + // default ttl 1 week + $ttl = $config['cache_ttl'] ?? 604800; + assert(is_int($ttl) || is_float($ttl)); + + $content = $this->cache->get($cacheKey, fn (): string => $type->render() ?? '', (float) $ttl); + + if ('' === $content) { return; } - $body = str_replace('', $content . PHP_EOL . '', $body); - - $response->setContent($body); + $body = str_replace('', $content.\PHP_EOL.'', $body); + $responseEvent->getResponse()->setContent($body); } -} \ No newline at end of file +} diff --git a/src/Metas/Attributes/Title.php b/src/Metas/Attributes/Title.php index 648c8ff..95c4c73 100644 --- a/src/Metas/Attributes/Title.php +++ b/src/Metas/Attributes/Title.php @@ -1,11 +1,15 @@ + */ + private array $metaTags = []; + + public function __construct() + { $this->seoMeta = new SeoMeta(); } - private array $metaTags = []; + /** + * @return array + */ public function getMetaTags(): array { return $this->metaTags; @@ -26,88 +36,93 @@ public function getSeoMeta(): SeoMeta public function setCharacterEncoding(string $charset = 'UTF-8'): static { - $this->seoMeta->setCharset($charset); - return $this; + $this->seoMeta->setCharset($charset); + + return $this; } /** - * @param string $title * @return $this */ public function setTitle(string $title): static { $this->seoMeta->setTitle($title); + return $this; } /** - * @param string $description * @return $this */ public function setDescription(string $description): static { $this->seoMeta->setDescription($description); + return $this; } /** - * @param array $keywords + * @param array $keywords + * * @return $this */ public function setKeywords(array $keywords): static { $this->seoMeta->setKeywords($keywords); + return $this; } /** - * @param string $keyword * @return $this */ public function setSubject(string $keyword): static { - $this->seoMeta->setSubject($keyword); - return $this; + $this->seoMeta->setSubject($keyword); + + return $this; } /** - * @param string $copyright * @return $this */ public function setCopyright(string $copyright): static { $this->seoMeta->setCopyright($copyright); + return $this; } /** - * @param array $robots + * @param array $robots + * * @return $this */ public function setRobots(array $robots): static { $this->seoMeta->setRobots($robots); + return $this; } /** - * @param string $viewport * @return $this */ public function setViewPort(string $viewport): static { $this->seoMeta->setViewPort($viewport); + return $this; } /** - * @param string $href * @return $this */ public function setCanonical(string $href): static { - $this->seoMeta->setCanonical($href); - return $this; + $this->seoMeta->setCanonical($href); + + return $this; } public function setAlternate(string $href, string $media = ''): static @@ -116,18 +131,21 @@ public function setAlternate(string $href, string $media = ''): static $canonical['href'] = $href; $canonical['media'] = $media; $this->metaTags['rel'] = $canonical; + return $this; } public function setContentSecurityPolicy(string $contentSecurityPolicy): static { $this->seoMeta->setContentSecurityPolicy($contentSecurityPolicy); + return $this; } public function setContentType(string $contentType): static { $this->seoMeta->setContentType($contentType); + return $this; } @@ -136,21 +154,23 @@ public function setDefaultStyle(string $style): static $tags['http-equiv'] = 'Default-Style'; $tags['value'] = $style; $this->metaTags['default-style'] = $tags; + return $this; } public function setXUACompatible(): static { $tags['http-equiv'] = 'X-UA-Compatible'; - $tags['value'] = "IE=edge"; + $tags['value'] = 'IE=edge'; $this->metaTags['x-ua-compatible'] = $tags; + return $this; } - public function setCustomMetaTag(string $name, string $content): static { $this->metaTags[$name] = $content; + return $this; } @@ -163,6 +183,7 @@ public function reset(): void public function setAuthor(string $author): static { $this->seoMeta->setAuthor($author); + return $this; } -} \ No newline at end of file +} diff --git a/src/Metas/MetaTagsManagerInterface.php b/src/Metas/MetaTagsManagerInterface.php index d28a3b9..a2cb93d 100644 --- a/src/Metas/MetaTagsManagerInterface.php +++ b/src/Metas/MetaTagsManagerInterface.php @@ -1,23 +1,34 @@ + */ public function getMetaTags(): array; public function setTitle(string $title): static; public function setDescription(string $description): static; + /** + * @param array $keywords + */ public function setKeywords(array $keywords): static; public function setSubject(string $keyword): static; public function setCopyright(string $copyright): static; + /** + * @param array $robots + */ public function setRobots(array $robots): static; public function setCharacterEncoding(string $charset): static; @@ -41,4 +52,4 @@ public function setCustomMetaTag(string $name, string $content): static; public function setAuthor(string $author): static; public function getSeoMeta(): SeoMeta; -} \ No newline at end of file +} diff --git a/src/Metas/Model/SeoMeta.php b/src/Metas/Model/SeoMeta.php index d9469db..dc2f28c 100644 --- a/src/Metas/Model/SeoMeta.php +++ b/src/Metas/Model/SeoMeta.php @@ -1,4 +1,7 @@ + */ + protected array $keywords = []; protected string $subject = ''; - protected ?array $robots = []; + /** + * @var array + */ + protected array $robots = []; protected string $canonical = ''; @@ -35,227 +44,161 @@ class SeoMeta protected string $contentType = ''; - /** - * @return string|null - */ - public function getContentType(): ?string + protected string $contentSecurityPolicy = ''; + + public function getContentType(): string { return $this->contentType; } - /** - * @param string $contentType - * @return $this - */ - public function setContentType(string $contentType): SeoMeta + public function setContentType(string $contentType): self { $this->contentType = $contentType; + return $this; } - protected ?string $contentSecurityPolicy = null; - - /** - * @return string|null - */ - public function getContentSecurityPolicy(): ?string + public function getContentSecurityPolicy(): string { return $this->contentSecurityPolicy; } - /** - * @param string|null $contentSecurityPolicy - * @return SeoMeta - */ - public function setContentSecurityPolicy(?string $contentSecurityPolicy): SeoMeta + public function setContentSecurityPolicy(string $contentSecurityPolicy): self { $this->contentSecurityPolicy = $contentSecurityPolicy; + return $this; } - /** - * @return string|null - */ - public function getCharset(): ?string + public function getCharset(): string { return $this->charset; } - /** - * @param string|null $charset - * @return SeoMeta - */ - public function setCharset(?string $charset): SeoMeta + public function setCharset(string $charset): self { $this->charset = $charset; + return $this; } - - /** - * @return string|null - */ - public function getTitle(): ?string + public function getTitle(): string { return $this->title; } - /** - * @param string $title - * @return SeoMeta - */ - public function setTitle(string $title): SeoMeta + public function setTitle(string $title): self { $this->title = $title; + return $this; } - /** - * @return string|null - */ - public function getDescription(): ?string + public function getDescription(): string { return $this->description; } - /** - * @param string $description - * @return SeoMeta - */ - public function setDescription(string $description): SeoMeta + public function setDescription(string $description): self { $this->description = $description; + return $this; } /** - * @return array|null + * @return array */ - public function getKeywords(): ?array + public function getKeywords(): array { return $this->keywords; } /** - * @param array $keywords - * @return SeoMeta + * @param array $keywords */ - public function setKeywords(array $keywords): SeoMeta + public function setKeywords(array $keywords): self { $this->keywords = $keywords; + return $this; } - /** - * @return string|null - */ - public function getSubject(): ?string + public function getSubject(): string { return $this->subject; } - /** - * @param string $subject - * @return SeoMeta - */ - public function setSubject(string $subject): SeoMeta + public function setSubject(string $subject): self { $this->subject = $subject; + return $this; } /** - * @return array|null + * @return array */ - public function getRobots(): ?array + public function getRobots(): array { return $this->robots; } /** - * @param array|null $robots - * @return SeoMeta + * @param array $robots */ - public function setRobots(?array $robots): SeoMeta + public function setRobots(array $robots): self { $this->robots = $robots; + return $this; } - /** - * @return string|null - */ - public function getCanonical(): ?string + public function getCanonical(): string { return $this->canonical; } - /** - * @param string|null $canonical - * @return SeoMeta - */ - public function setCanonical(?string $canonical): SeoMeta + public function setCanonical(string $canonical): self { $this->canonical = $canonical; + return $this; } - /** - * @return string|null - */ - public function getCopyright(): ?string + public function getCopyright(): string { return $this->copyright; } - /** - * @param string|null $copyright - * @return SeoMeta - */ - public function setCopyright(?string $copyright): SeoMeta + public function setCopyright(string $copyright): self { $this->copyright = $copyright; + return $this; } - /** - * @return string|null - */ - public function getViewport(): ?string + public function getViewport(): string { return $this->viewport; } - /** - * @param string $viewport - * @return $this - */ - public function setViewport(string $viewport): SeoMeta + public function setViewport(string $viewport): self { $this->viewport = $viewport; + return $this; } - /** - * @return string|null - */ - public function getAuthor(): ?string + public function getAuthor(): string { return $this->author; } - /** - * @param string|null $author - * @return SeoMeta - */ - public function setAuthor(?string $author): SeoMeta + public function setAuthor(string $author): self { $this->author = $author; + return $this; } - - - - - -} \ No newline at end of file +} diff --git a/src/OpenGraph/Model/Article.php b/src/OpenGraph/Model/Article.php index f05e99a..484fcb7 100644 --- a/src/OpenGraph/Model/Article.php +++ b/src/OpenGraph/Model/Article.php @@ -1,4 +1,7 @@ */ + protected array $tags = []; + public function getPublishedTime(): ?DateTime { return $this->publishedTime; } - /** - * @param DateTime|null $publishedTime - * @return Article - */ - public function setPublishedTime(?DateTime $publishedTime): Article + public function setPublishedTime(?DateTime $publishedTime): self { $this->publishedTime = $publishedTime; + return $this; } - /** - * @return DateTime|null - */ public function getModifiedTime(): ?DateTime { return $this->modifiedTime; } - /** - * @param DateTime|null $modifiedTime - * @return Article - */ - public function setModifiedTime(?DateTime $modifiedTime): Article + public function setModifiedTime(?DateTime $modifiedTime): self { $this->modifiedTime = $modifiedTime; + return $this; } - /** - * @return string - */ public function getAuthor(): string { return $this->author; } - /** - * @param string $author - * @return Article - */ - public function setAuthor(string $author): Article + public function setAuthor(string $author): self { $this->author = $author; + return $this; } - /** - * @return string - */ public function getSection(): string { return $this->section; } - /** - * @param string $section - * @return Article - */ - public function setSection(string $section): Article + public function setSection(string $section): self { $this->section = $section; + return $this; } /** - * @return array + * @return array */ public function getTags(): array { @@ -106,12 +88,12 @@ public function getTags(): array } /** - * @param array $tags - * @return Article + * @param array $tags */ - public function setTags(array $tags): Article + public function setTags(array $tags): self { $this->tags = $tags; + return $this; } -} \ No newline at end of file +} diff --git a/src/OpenGraph/Model/Audio.php b/src/OpenGraph/Model/Audio.php index 9f8ee1c..e8aac22 100644 --- a/src/OpenGraph/Model/Audio.php +++ b/src/OpenGraph/Model/Audio.php @@ -1,4 +1,7 @@ url; } - /** - * @param string $url - * @return Audio - */ - public function setUrl(string $url): Audio + public function setUrl(string $url): self { $this->url = $url; + return $this; } - /** - * @return string - */ public function getSecureUrl(): string { return $this->secureUrl; } - /** - * @param string $secureUrl - * @return Audio - */ - public function setSecureUrl(string $secureUrl): Audio + public function setSecureUrl(string $secureUrl): self { $this->secureUrl = $secureUrl; + return $this; } - /** - * @return string - */ public function getType(): string { return $this->type; } - /** - * @param string $type - * @return Audio - */ - public function setType(string $type): Audio + public function setType(string $type): self { $this->type = $type; + return $this; } - -} \ No newline at end of file +} diff --git a/src/OpenGraph/Model/Book.php b/src/OpenGraph/Model/Book.php index ca0d459..c53c6e8 100644 --- a/src/OpenGraph/Model/Book.php +++ b/src/OpenGraph/Model/Book.php @@ -1,4 +1,7 @@ */ + protected array $tags = []; + public function getAuthor(): string { return $this->author; } - /** - * @param string $author - * @return Book - */ - public function setAuthor(string $author): Book + public function setAuthor(string $author): self { $this->author = $author; + return $this; } - /** - * @return string - */ public function getIsbn(): string { return $this->isbn; } - /** - * @param string $isbn - * @return Book - */ - public function setIsbn(string $isbn): Book + public function setIsbn(string $isbn): self { $this->isbn = $isbn; + return $this; } - /** - * @return string - */ public function getReleaseDate(): string { return $this->releaseDate; } - /** - * @param string $releaseDate - * @return Book - */ - public function setReleaseDate(string $releaseDate): Book + public function setReleaseDate(string $releaseDate): self { $this->releaseDate = $releaseDate; + return $this; } /** - * @return array + * @return array */ public function getTags(): array { @@ -84,12 +72,12 @@ public function getTags(): array } /** - * @param array $tags - * @return Book + * @param array $tags */ - public function setTags(array $tags): Book + public function setTags(array $tags): self { $this->tags = $tags; + return $this; } -} \ No newline at end of file +} diff --git a/src/OpenGraph/Model/Image.php b/src/OpenGraph/Model/Image.php index 3d0cdc4..3ddc28c 100644 --- a/src/OpenGraph/Model/Image.php +++ b/src/OpenGraph/Model/Image.php @@ -1,4 +1,7 @@ url; } - /** - * @param string $url - * @return Image - */ - public function setUrl(string $url): Image + public function setUrl(string $url): self { $this->url = $url; + return $this; } - /** - * @return string - */ public function getSecureUrl(): string { return $this->secureUrl; } - /** - * @param string $secureUrl - * @return Image - */ - public function setSecureUrl(string $secureUrl): Image + public function setSecureUrl(string $secureUrl): self { $this->secureUrl = $secureUrl; + return $this; } - /** - * @return string - */ public function getType(): string { return $this->type; } - /** - * @param string $type - * @return Image - */ - public function setType(string $type): Image + public function setType(string $type): self { $this->type = $type; + return $this; } - /** - * @return string - */ public function getWidth(): string { return $this->width; } - /** - * @param string $width - * @return Image - */ - public function setWidth(string $width): Image + public function setWidth(string $width): self { $this->width = $width; + return $this; } - /** - * @return string - */ public function getHeight(): string { return $this->height; } - /** - * @param string $height - * @return Image - */ - public function setHeight(string $height): Image + public function setHeight(string $height): self { $this->height = $height; + return $this; } - /** - * @return string - */ public function getAlt(): string { return $this->alt; } - /** - * @param string $alt - * @return Image - */ - public function setAlt(string $alt): Image + public function setAlt(string $alt): self { $this->alt = $alt; + return $this; } -} \ No newline at end of file +} diff --git a/src/OpenGraph/Model/OpenGraph.php b/src/OpenGraph/Model/OpenGraph.php index 414d288..3e92b4a 100644 --- a/src/OpenGraph/Model/OpenGraph.php +++ b/src/OpenGraph/Model/OpenGraph.php @@ -1,4 +1,7 @@ + */ protected array $structuredProperty = [ 'type' => null, 'property' => null, 'content' => null, ]; + /** + * @var array + */ protected array $structuredProperties = []; + /** + * @var array + */ protected array $musicProperties = []; - protected array $twitterCardProperties = []; - /** - * @return string + * @var array> */ + protected array $twitterCardProperties = []; + public function getTitle(): string { return $this->title; } - /** - * @param string $title - * @return OpenGraph - */ - public function setTitle(string $title): OpenGraph + public function setTitle(string $title): self { $this->title = $title; + return $this; } - /** - * @return string - */ public function getDescription(): string { return $this->description; } - /** - * @param string $description - * @return OpenGraph - */ - public function setDescription(string $description): OpenGraph + public function setDescription(string $description): self { $this->description = $description; + return $this; } - /** - * @return string - */ public function getImageUrl(): string { return $this->imageUrl; } - /** - * @param string $imageUrl - * @return OpenGraph - */ - public function setImageUrl(string $imageUrl): OpenGraph + public function setImageUrl(string $imageUrl): self { $this->imageUrl = $imageUrl; + return $this; } - /** - * @return string - */ public function getUrl(): string { return $this->url; } - /** - * @param string $url - * @return OpenGraph - */ - public function setUrl(string $url): OpenGraph + public function setUrl(string $url): self { $this->url = $url; + return $this; } - /** - * @return string - */ public function getType(): string { return $this->type; } - /** - * @param string $type - * @return OpenGraph - */ - public function setType(string $type): OpenGraph + public function setType(string $type): self { $this->type = $type; + return $this; } - /** - * @return string - */ public function getLocale(): string { return $this->locale; } - /** - * @param string $locale - * @return OpenGraph - */ - public function setLocale(string $locale): OpenGraph + public function setLocale(string $locale): self { $this->locale = $locale; + return $this; } - /** - * @return string - */ public function getAlternateLocale(): string { return $this->alternateLocale; } - /** - * @param string $alternateLocale - * @return OpenGraph - */ - public function setAlternateLocale(string $alternateLocale): OpenGraph + public function setAlternateLocale(string $alternateLocale): self { $this->alternateLocale = $alternateLocale; + return $this; } - /** - * @return string - */ public function getSiteName(): string { return $this->siteName; } - /** - * @param string $siteName - * @return OpenGraph - */ - public function setSiteName(string $siteName): OpenGraph + public function setSiteName(string $siteName): self { $this->siteName = $siteName; + return $this; } /** - * @return array + * @return array */ public function getStructuredProperty(): array { @@ -199,17 +167,17 @@ public function getStructuredProperty(): array } /** - * @param array $structuredProperty - * @return OpenGraph + * @param array $structuredProperty */ - public function setStructuredProperty(array $structuredProperty): OpenGraph + public function setStructuredProperty(array $structuredProperty): self { $this->structuredProperty = $structuredProperty; + return $this; } /** - * @return array + * @return array */ public function getStructuredProperties(): array { @@ -217,17 +185,17 @@ public function getStructuredProperties(): array } /** - * @param array $structuredProperties - * @return OpenGraph + * @param array $structuredProperties */ - public function setStructuredProperties(array $structuredProperties): OpenGraph + public function setStructuredProperties(array $structuredProperties): self { $this->structuredProperties = $structuredProperties; + return $this; } /** - * @return array + * @return array */ public function getMusicProperties(): array { @@ -235,17 +203,17 @@ public function getMusicProperties(): array } /** - * @param array $musicProperties - * @return OpenGraph + * @param array $musicProperties */ - public function setMusicProperties(array $musicProperties): OpenGraph + public function setMusicProperties(array $musicProperties): self { $this->musicProperties = $musicProperties; + return $this; } /** - * @return array + * @return array> */ public function getTwitterCardProperties(): array { @@ -253,66 +221,48 @@ public function getTwitterCardProperties(): array } /** - * @param array $twitterCardProperties - * @return OpenGraph + * @param array $twitterCardProperties */ - public function setTwitterCardProperties(array $twitterCardProperties): OpenGraph + public function setTwitterCardProperties(array $twitterCardProperties): self { $this->twitterCardProperties[] = $twitterCardProperties; + return $this; } - /** - * @return string - */ public function getImageAlt(): string { return $this->imageAlt; } - /** - * @param string $imageAlt - * @return OpenGraph - */ - public function setImageAlt(string $imageAlt): OpenGraph + public function setImageAlt(string $imageAlt): self { $this->imageAlt = $imageAlt; + return $this; } - /** - * @return string - */ public function getAudio(): string { return $this->audio; } - /** - * @param string $audio - * @return OpenGraph - */ - public function setAudio(string $audio): OpenGraph + public function setAudio(string $audio): self { $this->audio = $audio; + return $this; } - /** - * @return string - */ public function getVideo(): string { return $this->video; } - /** - * @param string $video - * @return OpenGraph - */ - public function setVideo(string $video): OpenGraph + public function setVideo(string $video): self { $this->video = $video; + return $this; } -} \ No newline at end of file +} diff --git a/src/OpenGraph/Model/Profile.php b/src/OpenGraph/Model/Profile.php index c7b0d52..2c79d5a 100644 --- a/src/OpenGraph/Model/Profile.php +++ b/src/OpenGraph/Model/Profile.php @@ -1,4 +1,7 @@ firstName; } - /** - * @param string $firstName - * @return Profile - */ - public function setFirstName(string $firstName): Profile + public function setFirstName(string $firstName): self { $this->firstName = $firstName; + return $this; } - /** - * @return string - */ public function getLastName(): string { return $this->lastName; } - /** - * @param string $lastName - * @return Profile - */ - public function setLastName(string $lastName): Profile + public function setLastName(string $lastName): self { $this->lastName = $lastName; + return $this; } - /** - * @return string - */ public function getUserName(): string { return $this->userName; } - /** - * @param string $userName - * @return Profile - */ - public function setUserName(string $userName): Profile + public function setUserName(string $userName): self { $this->userName = $userName; + return $this; } - /** - * @return string - */ public function getGender(): string { return $this->gender; } - /** - * @param string $gender - * @return Profile - */ - public function setGender(string $gender): Profile + public function setGender(string $gender): self { $this->gender = $gender; + return $this; } -} \ No newline at end of file +} diff --git a/src/OpenGraph/Model/Video.php b/src/OpenGraph/Model/Video.php index 68168ab..f13b1e3 100644 --- a/src/OpenGraph/Model/Video.php +++ b/src/OpenGraph/Model/Video.php @@ -1,4 +1,7 @@ url; } - /** - * @param string $url - * @return Video - */ - public function setUrl(string $url): Video + public function setUrl(string $url): self { $this->url = $url; + return $this; } - /** - * @return string - */ public function getSecureUrl(): string { return $this->secureUrl; } - /** - * @param string $secureUrl - * @return Video - */ - public function setSecureUrl(string $secureUrl): Video + public function setSecureUrl(string $secureUrl): self { $this->secureUrl = $secureUrl; + return $this; } - /** - * @return string - */ public function getType(): string { return $this->type; } - /** - * @param string $type - * @return Video - */ - public function setType(string $type): Video + public function setType(string $type): self { $this->type = $type; + return $this; } - /** - * @return string - */ public function getWidth(): string { return $this->width; } - /** - * @param string $width - * @return Video - */ - public function setWidth(string $width): Video + public function setWidth(string $width): self { $this->width = $width; + return $this; } - /** - * @return string - */ public function getHeight(): string { return $this->height; } - /** - * @param string $height - * @return $this - */ - public function setHeight(string $height): Video + public function setHeight(string $height): self { $this->height = $height; + return $this; } - -} \ No newline at end of file +} diff --git a/src/OpenGraph/OGArticleManager.php b/src/OpenGraph/OGArticleManager.php index 346dd47..685699a 100644 --- a/src/OpenGraph/OGArticleManager.php +++ b/src/OpenGraph/OGArticleManager.php @@ -1,4 +1,7 @@ article = new Article(); } - /** - * @return \DateTime - */ - public function getPublishedTime(): \DateTime + public function getPublishedTime(): ?DateTime { return $this->article->getPublishedTime(); } /** - * @param \DateTime $publishedTime * @return $this */ - public function setPublishedTime(\DateTime $publishedTime): static + public function setPublishedTime(DateTime $publishedTime): static { $this->article->setPublishedTime($publishedTime); + return $this; } - /** - * @return \DateTime - */ - public function getModifiedTime(): \DateTime + public function getModifiedTime(): ?DateTime { return $this->article->getModifiedTime(); } /** - * @param \DateTime $modifiedTime * @return $this */ - public function setModifiedTime(\DateTime $modifiedTime): static + public function setModifiedTime(DateTime $modifiedTime): static { $this->article->setModifiedTime($modifiedTime); + return $this; } - /** - * @return string - */ public function getAuthor(): string { return $this->article->getAuthor(); } /** - * @param string $author * @return $this */ public function setAuthor(string $author): static { $this->article->setAuthor($author); + return $this; } - /** - * @return string - */ public function getSection(): string { return $this->article->getSection(); } /** - * @param string $section * @return $this */ public function setSection(string $section): static { $this->article->setSection($section); + return $this; } /** - * @return array + * @return array */ public function getTags(): array { @@ -102,12 +95,14 @@ public function getTags(): array } /** - * @param array $tags + * @param array $tags + * * @return $this */ public function setTags(array $tags): static { $this->article->setTags($tags); + return $this; } @@ -115,4 +110,4 @@ public function getArticle(): Article { return $this->article; } -} \ No newline at end of file +} diff --git a/src/OpenGraph/OGArticleManagerInterface.php b/src/OpenGraph/OGArticleManagerInterface.php index 96585cd..98ee1b9 100644 --- a/src/OpenGraph/OGArticleManagerInterface.php +++ b/src/OpenGraph/OGArticleManagerInterface.php @@ -1,4 +1,7 @@ + */ public function getTags(): array; + + /** + * @param array $tags + */ public function setTags(array $tags): static; -} \ No newline at end of file +} diff --git a/src/OpenGraph/OGAudioManager.php b/src/OpenGraph/OGAudioManager.php index ccb5b36..cd995d9 100644 --- a/src/OpenGraph/OGAudioManager.php +++ b/src/OpenGraph/OGAudioManager.php @@ -1,4 +1,7 @@ audio = new Audio(); @@ -28,65 +31,53 @@ public function getAudio(): Audio return $this->audio; } - /** - * @return string - */ public function getUrl(): string { return $this->audio->getUrl(); } /** - * @param string $url * @return $this */ public function setUrl(string $url): static { $this->audio->setUrl($url); + return $this; } - /** - * @return string - */ public function getSecureUrl(): string { return $this->audio->getSecureUrl(); } /** - * @param string $secureUrl * @return $this */ public function setSecureUrl(string $secureUrl): static { $this->audio->setSecureUrl($secureUrl); + return $this; } - /** - * @return string - */ public function getType(): string { return $this->audio->getType(); } /** - * @param string $type * @return $this */ public function setType(string $type): static { $this->audio->setType($type); + return $this; } - /** - * @return void - */ public function reset(): void { $this->audio = new Audio(); } -} \ No newline at end of file +} diff --git a/src/OpenGraph/OGAudioManagerInterface.php b/src/OpenGraph/OGAudioManagerInterface.php index 922d106..8ac6547 100644 --- a/src/OpenGraph/OGAudioManagerInterface.php +++ b/src/OpenGraph/OGAudioManagerInterface.php @@ -1,4 +1,7 @@ image = new Image(); @@ -27,119 +31,98 @@ public function getImage(): Image return $this->image; } - /** - * @return string - */ public function getUrl(): string { return $this->image->getUrl(); } /** - * @param string $url * @return $this */ public function setUrl(string $url): static { $this->image->setUrl($url); + return $this; } - /** - * @return string - */ public function getSecureUrl(): string { return $this->image->getSecureUrl(); } /** - * @param string $secureUrl * @return $this */ public function setSecureUrl(string $secureUrl): static { $this->image->setSecureUrl($secureUrl); + return $this; } - /** - * @return string - */ public function getType(): string { return $this->image->getType(); } /** - * @param string $type * @return $this */ public function setType(string $type): static { $this->image->setType($type); + return $this; } - /** - * @return string - */ public function getWidth(): string { return $this->image->getWidth(); } /** - * @param string $width * @return $this */ public function setWidth(string $width): static { $this->image->setWidth($width); + return $this; } - /** - * @return string - */ public function getHeight(): string { return $this->image->getHeight(); } /** - * @param string $height * @return $this */ public function setHeight(string $height): static { $this->image->setHeight($height); + return $this; } - /** - * @return string - */ public function getAlt(): string { return $this->image->getAlt(); } /** - * @param string $alt * @return $this */ public function setAlt(string $alt): static { $this->image->setAlt($alt); + return $this; } - /** - * @return void - */ public function reset(): void { $this->image = new Image(); } -} \ No newline at end of file +} diff --git a/src/OpenGraph/OGImageManagerInterface.php b/src/OpenGraph/OGImageManagerInterface.php index 4572b71..9e4bd3d 100644 --- a/src/OpenGraph/OGImageManagerInterface.php +++ b/src/OpenGraph/OGImageManagerInterface.php @@ -1,4 +1,7 @@ video = new Video(); @@ -27,102 +31,83 @@ public function getVideo(): Video return $this->video; } - /** - * @return string - */ public function getUrl(): string { return $this->video->getUrl(); } /** - * @param string $url * @return $this */ public function setUrl(string $url): static { $this->video->setUrl($url); + return $this; } - /** - * @return string - */ public function getSecureUrl(): string { return $this->video->getSecureUrl(); } /** - * @param string $secureUrl * @return $this */ public function setSecureUrl(string $secureUrl): static { $this->video->setSecureUrl($secureUrl); + return $this; } - /** - * @return string - */ public function getType(): string { return $this->video->getType(); } /** - * @param string $type * @return $this */ public function setType(string $type): static { $this->video->setType($type); + return $this; } - /** - * @return string - */ public function getWidth(): string { return $this->video->getWidth(); } /** - * @param string $width * @return $this */ public function setWidth(string $width): static { $this->video->setWidth($width); + return $this; } - /** - * @return string - */ public function getHeight(): string { return $this->video->getHeight(); } /** - * @param string $height * @return $this */ public function setHeight(string $height): static { $this->video->setHeight($height); + return $this; } - - /** - * @return void - */ public function reset(): void { $this->video = new Video(); } -} \ No newline at end of file +} diff --git a/src/OpenGraph/OGVideoManagerInterface.php b/src/OpenGraph/OGVideoManagerInterface.php index 8e711cd..2345f73 100644 --- a/src/OpenGraph/OGVideoManagerInterface.php +++ b/src/OpenGraph/OGVideoManagerInterface.php @@ -1,4 +1,7 @@ openGraph = new OpenGraph(); } @@ -17,9 +23,6 @@ public function getOpenGraph(): OpenGraph return $this->openGraph; } - /** - * @return string - */ public function getLocale(): string { return $this->openGraph->getLocale(); @@ -32,6 +35,7 @@ public function getLocale(): string public function setLocale(string $locale): static { $this->openGraph->setLocale($locale); + return $this; } @@ -41,12 +45,14 @@ public function getAlternateLocale(): string } /** - * @param string $alternateLocale An array of other locales this page is available in. + * @param string $alternateLocale an array of other locales this page is available in + * * @return $this */ public function setAlternateLocale(string $alternateLocale): static { $this->openGraph->setAlternateLocale($alternateLocale); + return $this; } @@ -56,22 +62,26 @@ public function getSiteName(): string } /** - * @param string $siteName If your object is part of a larger web site, the name which should be displayed for the overall site. + * @param string $siteName if your object is part of a larger web site, the name which should be displayed for the overall site + * * @return $this */ public function setSiteName(string $siteName): static { $this->openGraph->setSiteName($siteName); + return $this; } /** * @param string $title The title of your object as it should appear within the graph, e.g., "The Open Graph". + * * @return $this */ public function setTitle(string $title): static { $this->openGraph->setTitle($title); + return $this; } @@ -86,22 +96,24 @@ public function getDescription(): string } /** - * @param string $description A one to two sentence description of your object. + * @param string $description a one to two sentence description of your object + * * @return $this */ public function setDescription(string $description): static { $this->openGraph->setDescription($description); + return $this; } /** - * @param string $image * @return $this */ public function setImage(string $image): static { $this->openGraph->setImageUrl($image); + return $this; } @@ -117,17 +129,16 @@ public function getUrl(): string /** * @param string $url The canonical URL of your object that will be used as its permanent ID in the graph, e.g., "https://www.imdb.com/title/tt0117500/" + * * @return $this */ public function setUrl(string $url): static { $this->openGraph->setUrl($url); + return $this; } - /** - * @return string - */ public function getType(): string { return $this->openGraph->getType(); @@ -135,23 +146,25 @@ public function getType(): string /** * @param string $type The type of your object, e.g., "video.movie". Depending on the type you specify, other properties may also be required. + * * @return $this */ public function setType(string $type): static { $this->openGraph->setType($type); + return $this; } + /** + * @return array + */ public function getStructuredProperties(): array { return $this->openGraph->getStructuredProperties(); } /** - * @param string $type - * @param string $property - * @param string $content * @return $this */ public function addStructuredProperty(string $type, string $property, string $content): static @@ -160,48 +173,52 @@ public function addStructuredProperty(string $type, string $property, string $co return $this; } - $structuredProperty['type'] = $type; - $structuredProperty['property'] = $property; - $structuredProperty['content'] = $content ; + $structuredProperty = [ + 'type' => $type, + 'property' => $property, + 'content' => $content, + ]; -// if (!isset($structuredProperty[$type])) { -// $structuredProperty[$type] = []; -// } + $properties = $this->openGraph->getStructuredProperties(); + $properties[] = $structuredProperty; + $this->openGraph->setStructuredProperties($properties); - $structuredProperty['property'][] = $structuredProperty; - $this->openGraph->setStructuredProperties($structuredProperty); return $this; } /** - * @param string $property - * @param string $content * @return $this */ public function addMusicProperty(string $property, string $content): static { $this->openGraph->setMusicProperties(['property' => $property, 'content' => $content]); + return $this; } + /** + * @return array + */ public function getMusicProperties(): array { return $this->openGraph->getMusicProperties(); } /** - * @param string $name The name of the property E.g description and + * @param string $name The name of the property E.g description and * @param string $content The content of the property name + * * @return $this */ public function addTwitterCardProperty(string $name, string $content): static { $this->openGraph->setTwitterCardProperties([$name => $content]); + return $this; } /** - * @return array + * @return array> */ public function getTwitterCardProperties(): array { @@ -213,57 +230,48 @@ public function reset(): void $this->openGraph = new OpenGraph(); } - /** - * @return string - */ public function getAudio(): string { return $this->openGraph->getAudio(); } /** - * @param string $audio * @return $this */ public function setAudio(string $audio): static { $this->openGraph->setAudio($audio); + return $this; } - /** - * @return string - */ public function getVideo(): string { return $this->openGraph->getVideo(); } /** - * @param string $video * @return $this */ public function setVideo(string $video): static { $this->openGraph->setVideo($video); + return $this; } - /** - * @return string - */ public function getImageAltText(): string { return $this->openGraph->getImageAlt(); } /** - * @param string $imageAltText * @return $this */ public function setImageAltText(string $imageAltText): static { $this->openGraph->setImageAlt($imageAltText); + return $this; } -} \ No newline at end of file +} diff --git a/src/OpenGraph/OpenGraphManagerInterface.php b/src/OpenGraph/OpenGraphManagerInterface.php index 67019e2..8b1ab1e 100644 --- a/src/OpenGraph/OpenGraphManagerInterface.php +++ b/src/OpenGraph/OpenGraphManagerInterface.php @@ -1,5 +1,7 @@ + */ public function getStructuredProperties(): array; + public function setSiteName(string $siteName): static; + public function getSiteName(): string; + public function setLocale(string $locale): static; + public function getLocale(): string; + public function setAlternateLocale(string $alternateLocale): static; + public function getAlternateLocale(): string; public function addMusicProperty(string $property, string $content): static; + + /** + * @return array + */ public function getMusicProperties(): array; public function addTwitterCardProperty(string $name, string $content): static; + /** + * @return array> + */ public function getTwitterCardProperties(): array; public function getAudio(): string; + public function setAudio(string $audio): static; + public function getVideo(): string; + public function setVideo(string $video): static; public function getImageAltText(): string; + public function setImageAltText(string $imageAltText): static; public function getOpenGraph(): OpenGraph; -} \ No newline at end of file +} diff --git a/src/Schema/BaseType.php b/src/Schema/BaseType.php index 514366a..e33a92e 100644 --- a/src/Schema/BaseType.php +++ b/src/Schema/BaseType.php @@ -1,28 +1,36 @@ + */ + private array $properties = []; + public function __toString(): string { - return get_class($this); + return static::class; } public function getType(): string { - return (new \ReflectionClass($this))->getShortName(); - } - protected function setProperty(string $name, string|array|object|int|bool $value): void - { - $this->properties[$name] = $value; + return (new ReflectionClass($this))->getShortName(); } + /** + * @return array + */ public function getProperties(): array { return $this->properties; @@ -36,91 +44,107 @@ public function getProperty(string $name): mixed public function name(string $value): static { $this->setProperty('name', $value); + return $this; } public function id(string $value): static { $this->setProperty('id', $value); + return $this; } public function alternateName(string $value): static { $this->setProperty('alternateName', $value); + return $this; } - public function url(string $value): BaseType + public function url(string $value): self { $this->setProperty('url', $value); + return $this; } public function inLanguage(string $isLanguage): static { $this->setProperty('inLanguage', $isLanguage); + return $this; } public function setDescription(string $value): static { $this->setProperty('description', $value); + return $this; } - public function subjectOf(Event|CreativeWork|BaseType $subjectOf): static + public function subjectOf(Event|CreativeWork|self $subjectOf): static { $this->setProperty('subjectOf', $this->parseChild($subjectOf)); + return $this; } - public function render(): string|null + public function render(): ?string { return ''; } - private function parse(): array + /** + * @param string|array|object|int|bool|float $value + */ + protected function setProperty(string $name, string|array|object|int|bool|float $value): void { - return [ - "@context" => stripslashes("https://schema.org"), - "@type" => $this->getType(),]+ - $this->getProperties() - ; + $this->properties[$name] = $value; } - protected function parseChild(BaseType $child): array + /** + * @return array + */ + protected function parseChild(self $baseType): array { - $properties = get_class_vars($child); return [ - "@type" => $child->getType(),]+ - $child->getProperties() - ; + '@type' => $baseType->getType(), ] + + $baseType->getProperties() + ; } - protected function parseChildWithId(BaseType $child): array + /** + * @return array + */ + protected function parseChildWithId(self $baseType): array { - $properties = $child->getProperties(); + $properties = $baseType->getProperties(); // Replace "id" with "@id" if present and non-empty - if (isset($properties['id']) && \is_string($properties['id']) && '' !== $properties['id']) { + if (isset($properties['id']) && is_string($properties['id']) && '' !== $properties['id']) { $properties['@id'] = $properties['id']; unset($properties['id']); } return [ - '@type' => $child->getType(), - ] + $properties; + '@type' => $baseType->getType(), + ] + $properties; } + /** + * @param array $children + * + * @return array> + */ protected function parseArray(array $children): array { $properties = []; foreach ($children as $child) { - if (!$child instanceof BaseType) { + if (!$child instanceof self) { continue; } @@ -133,4 +157,16 @@ protected function parseArray(array $children): array return $properties; } -} \ No newline at end of file + + /** + * @return array + */ + private function parse(): array + { + return [ + '@context' => stripslashes('https://schema.org'), + '@type' => $this->getType(), ] + + $this->getProperties() + ; + } +} diff --git a/src/Schema/CommonType.php b/src/Schema/CommonType.php index f864699..17b4c20 100644 --- a/src/Schema/CommonType.php +++ b/src/Schema/CommonType.php @@ -1,8 +1,9 @@ setProperty('audienceType', $audienceType); + return $this; } @@ -20,4 +22,4 @@ public function geographicArea(AdministrativeArea $administrativeArea): static return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Intangible/Brand.php b/src/Schema/Intangible/Brand.php index 053bd6a..ff7ab70 100644 --- a/src/Schema/Intangible/Brand.php +++ b/src/Schema/Intangible/Brand.php @@ -1,21 +1,27 @@ setProperty('slogan', $slogan); + return $this; } public function logo(ImageObject|string $logo): static { $this->setProperty('logo', is_string($logo) ? $logo : $this->parseChild($logo)); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Intangible/ItemList.php b/src/Schema/Intangible/ItemList.php index 19152f0..af37d0b 100644 --- a/src/Schema/Intangible/ItemList.php +++ b/src/Schema/Intangible/ItemList.php @@ -1,11 +1,16 @@ $listitems + */ public function itemListElement(array $listitems): static { $this->setProperty('itemListElement', $this->parseArray($listitems)); @@ -19,4 +24,4 @@ public function numberOfItems(int $number): static return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Intangible/Offer.php b/src/Schema/Intangible/Offer.php index 2e8cfd5..3c8a955 100644 --- a/src/Schema/Intangible/Offer.php +++ b/src/Schema/Intangible/Offer.php @@ -1,27 +1,34 @@ setProperty('asin', is_string($asin) ? $asin : $this->parseChild($asin)); + return $this; } public function price(float|string $price): static { $this->setProperty('price', $price); + return $this; } public function priceCurrency(string $currency): static { $this->setProperty('priceCurrency', $currency); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Intangible/Service.php b/src/Schema/Intangible/Service.php index a74708f..7e750f1 100644 --- a/src/Schema/Intangible/Service.php +++ b/src/Schema/Intangible/Service.php @@ -1,49 +1,58 @@ getShortName(); + return (new ReflectionClass($this))->getShortName(); } public function areaServed(string $areaServed): static { $this->setProperty('areaServed', $areaServed); + return $this; } public function award(string $award): static { $this->setProperty('award', $award); + return $this; } public function termsOfService(string $termsOfService): static { $this->setProperty('termsOfService', $termsOfService); + return $this; } public function slogan(string $slogan): static { $this->setProperty('slogan', $slogan); + return $this; } public function providerMobility(string $providerMobility): static { $this->setProperty('providerMobility', $providerMobility); + return $this; } public function serviceType(string $serviceType): static { $this->setProperty('serviceType', $serviceType); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Intangible/StructuredValue/ContactPoint.php b/src/Schema/Intangible/StructuredValue/ContactPoint.php index f9bc07b..b86f7cf 100644 --- a/src/Schema/Intangible/StructuredValue/ContactPoint.php +++ b/src/Schema/Intangible/StructuredValue/ContactPoint.php @@ -1,47 +1,55 @@ setProperty('areaServed', $areaServed); + return $this; } $this->setProperty('areaServed', $this->parseChild($areaServed)); + return $this; } public function contactType(string $contactType): static { $this->setProperty('contactType', $contactType); + return $this; } public function email(string $email): static { $this->setProperty('email', $email); + return $this; } public function faxNumber(string $faxNumber): static { $this->setProperty('faxNumber', $faxNumber); + return $this; } public function telephone(string $telephone): static { $this->setProperty('telephone', $telephone); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Intangible/StructuredValue/ContactPoint/PostalAddress.php b/src/Schema/Intangible/StructuredValue/ContactPoint/PostalAddress.php index 2fc2a6a..78c981c 100644 --- a/src/Schema/Intangible/StructuredValue/ContactPoint/PostalAddress.php +++ b/src/Schema/Intangible/StructuredValue/ContactPoint/PostalAddress.php @@ -1,50 +1,61 @@ setProperty('addressCountry', $addressCountry); + return $this; } $this->setProperty('addressCountry', $this->parseChild($addressCountry)); + return $this; } public function addressLocality(string $addressLocality): static { $this->setProperty('addressLocality', $addressLocality); + return $this; } public function addressRegion(string $addressRegion): static { $this->setProperty('addressRegion', $addressRegion); + return $this; } public function postalCode(string $postalCode): static { $this->setProperty('postalCode', $postalCode); + return $this; } public function postOfficeBoxNumber(string $postalOfficeBoxNumber): static { $this->setProperty('postalOfficeBoxNumber', $postalOfficeBoxNumber); + return $this; } public function streetAddress(string $streetAddress): static { $this->setProperty('streetAddress', $streetAddress); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Intangible/StructuredValue/GeoShape.php b/src/Schema/Intangible/StructuredValue/GeoShape.php index dfc1c93..7338db3 100644 --- a/src/Schema/Intangible/StructuredValue/GeoShape.php +++ b/src/Schema/Intangible/StructuredValue/GeoShape.php @@ -1,5 +1,7 @@ setProperty('box', $box); + return $this; } public function polygon(string $polygon): static { $this->setProperty('polygon', $polygon); + return $this; } public function line(string $line): static { $this->setProperty('line', $line); + return $this; } public function elevation(string $elevation): static { $this->setProperty('elevation', $elevation); + return $this; } public function postalCode(string $postalCode): static { $this->setProperty('postalCode', $postalCode); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Place/AdministrativeArea.php b/src/Schema/Place/AdministrativeArea.php index ae53356..57d491a 100644 --- a/src/Schema/Place/AdministrativeArea.php +++ b/src/Schema/Place/AdministrativeArea.php @@ -1,5 +1,7 @@ */ public array $properties = []; /** - * @param string $branchCode * @return $this */ public function branchCode(string $branchCode): static { $this->setProperty('branchCode', $branchCode); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Place/CivicStructure/EducationalOrganization.php b/src/Schema/Place/CivicStructure/EducationalOrganization.php index 9d2eb14..6860bf7 100644 --- a/src/Schema/Place/CivicStructure/EducationalOrganization.php +++ b/src/Schema/Place/CivicStructure/EducationalOrganization.php @@ -1,10 +1,11 @@ baseType = new Thing(); } - public function getType(): BaseType|null + + public function getType(): ?BaseType { return $this->baseType ?? null; } - /** - * @param BaseType $type - * @return void - */ - public function render(BaseType $type): void + public function render(BaseType $baseType): void { - $this->baseType = $type; + $this->baseType = $baseType; } public function thing(): Thing @@ -200,14 +208,14 @@ public function collectionPage(): CollectionPage return new CollectionPage(); } - public function mediaGallery(): CollectionPage\MediaGallery + public function mediaGallery(): MediaGallery { - return new CollectionPage\MediaGallery(); + return new MediaGallery(); } - public function imageGallery(): CollectionPage\MediaGallery\ImageGallery + public function imageGallery(): ImageGallery { - return new CollectionPage\MediaGallery\ImageGallery; + return new ImageGallery(); } public function aboutPage(): AboutPage @@ -215,34 +223,34 @@ public function aboutPage(): AboutPage return new AboutPage(); } - public function faqPage(): WebPage\FAQPage + public function faqPage(): FAQPage { - return new WebPage\FAQPage(); + return new FAQPage(); } - public function itemPage(): WebPage\ItemPage + public function itemPage(): ItemPage { - return new WebPage\ItemPage(); + return new ItemPage(); } - public function checkoutPage(): WebPage\CheckoutPage + public function checkoutPage(): CheckoutPage { - return new WebPage\CheckoutPage(); + return new CheckoutPage(); } - public function profilePage(): WebPage\ProfilePage + public function profilePage(): ProfilePage { - return new WebPage\ProfilePage(); + return new ProfilePage(); } - public function searchResultPage(): WebPage\SearchResultsPage + public function searchResultPage(): SearchResultsPage { - return new WebPage\SearchResultsPage(); + return new SearchResultsPage(); } - public function mediaObject(): CreativeWork\MediaObject + public function mediaObject(): MediaObject { - return new CreativeWork\MediaObject(); + return new MediaObject(); } public function offer(): Offer @@ -314,5 +322,4 @@ public function textObject(): TextObject { return new TextObject(); } - -} \ No newline at end of file +} diff --git a/src/Schema/SchemaInterface.php b/src/Schema/SchemaInterface.php index 53fdacb..dcdb6df 100644 --- a/src/Schema/SchemaInterface.php +++ b/src/Schema/SchemaInterface.php @@ -1,5 +1,7 @@ setProperty('agent', $this->parseChild($agent)); + return $this; } - public function object(BaseType $object): static + public function object(BaseType $baseType): static { - $this->setProperty('object', $this->parseChild($object)); + $this->setProperty('object', $this->parseChild($baseType)); + return $this; } @@ -26,30 +31,35 @@ public function target(string|BaseType $target): static } else { $this->setProperty('target', $target); } + return $this; } - public function result(BaseType $result): static + public function result(BaseType $baseType): static { - $this->setProperty('result', $this->parseChild($result)); + $this->setProperty('result', $this->parseChild($baseType)); + return $this; } - public function startTime(\DateTime $startTime): static + public function startTime(DateTime $startTime): static { $this->setProperty('startTime', $startTime->format('Y-m-d\TH:i:s')); + return $this; } - public function endTime(\DateTime $endTime): static + public function endTime(DateTime $endTime): static { $this->setProperty('endTime', $endTime->format('Y-m-d\TH:i:s')); + return $this; } public function actionStatus(string $status): static { $this->setProperty('actionStatus', $status); + return $this; } } diff --git a/src/Schema/Thing/CreativeWork.php b/src/Schema/Thing/CreativeWork.php index 20e86e0..14d9b72 100644 --- a/src/Schema/Thing/CreativeWork.php +++ b/src/Schema/Thing/CreativeWork.php @@ -1,12 +1,13 @@ + */ public array $properties = []; } diff --git a/src/Schema/Thing/CreativeWork/Article/SocialMediaPosting/BlogPosting.php b/src/Schema/Thing/CreativeWork/Article/SocialMediaPosting/BlogPosting.php index bb5b53b..24c7d84 100644 --- a/src/Schema/Thing/CreativeWork/Article/SocialMediaPosting/BlogPosting.php +++ b/src/Schema/Thing/CreativeWork/Article/SocialMediaPosting/BlogPosting.php @@ -1,5 +1,7 @@ setProperty('blogPost', $this->parseChild($blogPosting)); + return $this; } /** - * @param string $issn * @return $this */ public function issn(string $issn): static { $this->setProperty('issn', $issn); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/CreativeWork/Chapter.php b/src/Schema/Thing/CreativeWork/Chapter.php index c27e66e..a228b46 100644 --- a/src/Schema/Thing/CreativeWork/Chapter.php +++ b/src/Schema/Thing/CreativeWork/Chapter.php @@ -1,5 +1,7 @@ setProperty('pageEnd', $pageEnd); + return $this; } public function pageStart(string|int $pageStart): static { $this->setProperty('pageStart', $pageStart); + return $this; } public function pagination(string $pagination): static { $this->setProperty('pagination', $pagination); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/CreativeWork/Course.php b/src/Schema/Thing/CreativeWork/Course.php index 292c3be..77a7ed2 100644 --- a/src/Schema/Thing/CreativeWork/Course.php +++ b/src/Schema/Thing/CreativeWork/Course.php @@ -1,5 +1,7 @@ setProperty('courseCode', $courseCode); + return $this; } public function totalHistoricalEnrollment(string $totalHistoricalEnrollment): static { $this->setProperty('totalHistoricalEnrollment', $totalHistoricalEnrollment); + return $this; } @@ -23,8 +27,9 @@ public function financialAidEligible(DefinedTerm|string $financialAidEligible): { if ($financialAidEligible instanceof DefinedTerm) { $this->setProperty('financialAidEligible', $this->parseChild($financialAidEligible)); - } else { + } else { $this->setProperty('financialAidEligible', $financialAidEligible); + return $this; } @@ -34,6 +39,7 @@ public function financialAidEligible(DefinedTerm|string $financialAidEligible): public function availableLanguage(string $availableLanguage): static { $this->setProperty('availableLanguage', $availableLanguage); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/CreativeWork/EducationalOccupationalCredential.php b/src/Schema/Thing/CreativeWork/EducationalOccupationalCredential.php index 3960797..8512881 100644 --- a/src/Schema/Thing/CreativeWork/EducationalOccupationalCredential.php +++ b/src/Schema/Thing/CreativeWork/EducationalOccupationalCredential.php @@ -1,5 +1,7 @@ setProperty('competencyRequired', is_string($competency) ? $competency : $this->parseChild($competency)); + return $this; } public function credentialCategory(DefinedTerm|string|Url $category): static { $this->setProperty('credentialCategory', is_string($category) ? $category : $this->parseChild($category)); + return $this; } - public function educationalLevel(Organization $educationalLevel): static + public function educationalLevel(Organization $organization): static { - $this->setProperty('educationalLevel', $this->parseChild($educationalLevel)); + $this->setProperty('educationalLevel', $this->parseChild($organization)); + return $this; } - public function recognizedBy(Organization $recognizedBy): static + public function recognizedBy(Organization $organization): static { - $this->setProperty('recognizedBy', $this->parseChild($recognizedBy)); + $this->setProperty('recognizedBy', $this->parseChild($organization)); + return $this; } - public function validIn(AdministrativeArea $validIn): static + public function validIn(AdministrativeArea $administrativeArea): static { - $this->setProperty('validIn', $this->parseChild($validIn)); + $this->setProperty('validIn', $this->parseChild($administrativeArea)); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/CreativeWork/MediaObject.php b/src/Schema/Thing/CreativeWork/MediaObject.php index 2456fd1..94e4784 100644 --- a/src/Schema/Thing/CreativeWork/MediaObject.php +++ b/src/Schema/Thing/CreativeWork/MediaObject.php @@ -1,7 +1,11 @@ setProperty('bitrate', $bitrate); + return $this; } public function contentSize(string $contentSize): static { $this->setProperty('contentSize', $contentSize); + return $this; } public function contentUrl(string $contentUrl): static { $this->setProperty('contentUrl', $contentUrl); + return $this; } public function duration(string $duration): static { $this->setProperty('duration', $duration); + return $this; } public function embedUrl(Url $url): static { $this->setProperty('embedUrl', $url); + return $this; } public function encodingFormat(string $encodingFormat): static { $this->setProperty('encodingFormat', $encodingFormat); + return $this; } - public function endTime(\DateTimeInterface $endTime): static + public function endTime(DateTimeInterface $endTime): static { - $this->setProperty('endTime', $endTime->format(\DateTime::ATOM)); + $this->setProperty('endTime', $endTime->format(DateTime::ATOM)); + return $this; } public function playerType(string $playerType): static { $this->setProperty('playerType', $playerType); + return $this; } - public function productionCompany(Organization $company): static + public function productionCompany(Organization $organization): static { - $this->setProperty('productionCompany', $this->parseChild($company)); + $this->setProperty('productionCompany', $this->parseChild($organization)); + return $this; } - public function regionsAllowed(Place $regionsAllowed): static + public function regionsAllowed(Place $place): static { - $this->setProperty('regionsAllowed', $this->parseChild($regionsAllowed)); + $this->setProperty('regionsAllowed', $this->parseChild($place)); + return $this; } public function sha256(string $sha256): static { $this->setProperty('sha256', $sha256); + return $this; } - public function startTime(\DateTimeInterface $startTime): static + public function startTime(DateTimeInterface $startTime): static { - $this->setProperty('startTime', $startTime->format(\DateTime::ATOM)); + $this->setProperty('startTime', $startTime->format(DateTime::ATOM)); + return $this; } - public function uploadDate(\DateTimeInterface $uploadDate): static + public function uploadDate(DateTimeInterface $uploadDate): static { $this->setProperty('uploadDate', $uploadDate->format('Y-m-d')); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/CreativeWork/MediaObject/ImageObject.php b/src/Schema/Thing/CreativeWork/MediaObject/ImageObject.php index 72deffd..e8c0720 100644 --- a/src/Schema/Thing/CreativeWork/MediaObject/ImageObject.php +++ b/src/Schema/Thing/CreativeWork/MediaObject/ImageObject.php @@ -1,50 +1,52 @@ setProperty('caption', $caption); + return $this; } public function exifData(string $exifData): static { $this->setProperty('exifData', $exifData); + return $this; } public function representativeOfPage(bool $value): static { $this->setProperty('representativeOfPage', $value); - return $this; - } - public function thumbnail(ImageObject $thumbnail): static - { - $this->setProperty('thumbnail', $this->parseChild($thumbnail)); return $this; } - public function contentUrl(string $url): static + public function thumbnail(self $imageObject): static { - $this->setProperty('contentUrl', $url); + $this->setProperty('thumbnail', $this->parseChild($imageObject)); + return $this; } public function width(int|string $width): static { $this->setProperty('width', $width); + return $this; } public function height(int|string $height): static { $this->setProperty('height', $height); + return $this; } } diff --git a/src/Schema/Thing/CreativeWork/MediaObject/TextObject.php b/src/Schema/Thing/CreativeWork/MediaObject/TextObject.php index 9abf1ce..cb756bd 100644 --- a/src/Schema/Thing/CreativeWork/MediaObject/TextObject.php +++ b/src/Schema/Thing/CreativeWork/MediaObject/TextObject.php @@ -1,5 +1,7 @@ setProperty('isSupportOf', $isSupportOf); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/CreativeWork/WebPage.php b/src/Schema/Thing/CreativeWork/WebPage.php index 9c627d3..7d43b4b 100644 --- a/src/Schema/Thing/CreativeWork/WebPage.php +++ b/src/Schema/Thing/CreativeWork/WebPage.php @@ -1,5 +1,7 @@ setProperty('cssSelector', $selector); + return $this; } public function xpath(string $xpath): static { $this->setProperty('xpath', $xpath); + return $this; } } diff --git a/src/Schema/Thing/CreativeWork/WebSite.php b/src/Schema/Thing/CreativeWork/WebSite.php index ba1ff5c..832e8e9 100644 --- a/src/Schema/Thing/CreativeWork/WebSite.php +++ b/src/Schema/Thing/CreativeWork/WebSite.php @@ -1,5 +1,7 @@ setProperty('issn', $ssn); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Event.php b/src/Schema/Thing/Event.php index 42a2208..5165612 100644 --- a/src/Schema/Thing/Event.php +++ b/src/Schema/Thing/Event.php @@ -1,58 +1,74 @@ + */ public array $properties = []; - public function startDate(\DateTime $startDate, \DateTimeZone $dateTimeZone = null): static + public function startDate(DateTime $startDate, ?DateTimeZone $dateTimeZone = null): static { - if ($dateTimeZone instanceof \DateTimeZone) { + if ($dateTimeZone instanceof DateTimeZone) { $startDate->setTimezone($dateTimeZone); } - $this->setProperty('startDate', $startDate->format(DATE_ATOM)); + $this->setProperty('startDate', $startDate->format(\DATE_ATOM)); + return $this; } - public function endDate(\DateTime $endDate, \DateTimeZone $dateTimeZone = null): static + public function endDate(DateTime $endDate, ?DateTimeZone $dateTimeZone = null): static { - if ($dateTimeZone instanceof \DateTimeZone) { + if ($dateTimeZone instanceof DateTimeZone) { $endDate->setTimezone($dateTimeZone); } - $this->setProperty('endDate', $endDate->format(DATE_ATOM)); + $this->setProperty('endDate', $endDate->format(\DATE_ATOM)); + return $this; } public function funder(Person|Organization $funder): static { $this->setProperty('funder', $this->parseChild($funder)); + return $this; } public function organizer(Person|Organization $organizer): static { $this->setProperty('organizer', $this->parseChild($organizer)); + return $this; } public function performer(Person|Organization $performer): static { $this->setProperty('performer', $this->parseChild($performer)); + return $this; } public function offers(Offer $offer): static { $this->setProperty('offers', $this->parseChild($offer)); + return $this; } @@ -66,53 +82,62 @@ public function location(Place|PostalAddress|VirtualLocation|string $location): public function sponsor(Person|Organization $sponsor): static { $this->setProperty('sponsor', $this->parseChild($sponsor)); + return $this; } - public function director(Person $director): static + public function director(Person $person): static { - $this->setProperty('director', $this->parseChild($director)); + $this->setProperty('director', $this->parseChild($person)); + return $this; } public function attendee(Person|Organization $attendee): static { $this->setProperty('attendee', $this->parseChild($attendee)); + return $this; } - public function composer(Person $composer): static + public function composer(Person $person): static { - $this->setProperty('composer', $this->parseChild($composer)); + $this->setProperty('composer', $this->parseChild($person)); + return $this; } - public function audience(Audience $audience):static + public function audience(Audience $audience): static { $this->setProperty('audience', $this->parseChild($audience)); + return $this; } - public function eventAttendanceMode(string $eventAttendanceMode):static + public function eventAttendanceMode(string $eventAttendanceMode): static { $this->setProperty('eventAttendanceMode', $eventAttendanceMode); + return $this; } - public function eventStatus(string $eventStatus):static + public function eventStatus(string $eventStatus): static { $this->setProperty('eventStatus', $eventStatus); + return $this; } - public function image(string|Thing\CreativeWork\MediaObject\ImageObject $image):static + public function image(string|ImageObject $image): static { - if ($image instanceof Thing\CreativeWork\MediaObject\ImageObject) { + if ($image instanceof ImageObject) { $this->setProperty('image', $this->parseChild($image)); + return $this; } $this->setProperty('image', $image); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Intangible/Audience.php b/src/Schema/Thing/Intangible/Audience.php index fc1e4ed..a8cb136 100644 --- a/src/Schema/Thing/Intangible/Audience.php +++ b/src/Schema/Thing/Intangible/Audience.php @@ -1,10 +1,11 @@ $items + */ public function itemListElement(array $items): static { $this->setProperty('itemListElement', $this->parseArray($items)); + return $this; } public function numberOfItems(int $count): static { $this->setProperty('numberOfItems', $count); + return $this; } } diff --git a/src/Schema/Thing/Intangible/DefinedTerm.php b/src/Schema/Thing/Intangible/DefinedTerm.php index a4d9a8c..0b06472 100644 --- a/src/Schema/Thing/Intangible/DefinedTerm.php +++ b/src/Schema/Thing/Intangible/DefinedTerm.php @@ -1,5 +1,7 @@ setProperty('termCode', $code); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Intangible/Grant.php b/src/Schema/Thing/Intangible/Grant.php index cbb3797..c3f50c6 100644 --- a/src/Schema/Thing/Intangible/Grant.php +++ b/src/Schema/Thing/Intangible/Grant.php @@ -1,5 +1,7 @@ setProperty('funder', $this->parseChild($funder)); + return $this; } public function sponsor(Person|Organization $sponsor): static { $this->setProperty('sponsor', $this->parseChild($sponsor)); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Intangible/JobPosting.php b/src/Schema/Thing/Intangible/JobPosting.php index 3877764..63701e2 100644 --- a/src/Schema/Thing/Intangible/JobPosting.php +++ b/src/Schema/Thing/Intangible/JobPosting.php @@ -1,5 +1,7 @@ setProperty('title', $title); + return $this; } - public function totalJobsOpening(int $totalJobsOpening): string + public function totalJobsOpening(int $totalJobsOpening): self { $this->setProperty('totalJobsOpening', $totalJobsOpening); + return $this; } - public function salaryCurrency(string $salaryCurrency): string + public function salaryCurrency(string $salaryCurrency): self { $this->setProperty('salaryCurrency', $salaryCurrency); + return $this; } - public function responsibilities(string $responsibilities): string + public function responsibilities(string $responsibilities): self { $this->setProperty('responsibilities', $responsibilities); + return $this; } - public function skills(DefinedTerm|string $skills): string + public function skills(DefinedTerm|string $skills): self { if (is_string($skills)) { $this->setProperty('skills', $skills); + return $this; } $this->setProperty('skills', $this->parseChild($skills)); + return $this; } - public function qualifications(EducationalOccupationalCredential|string $qualifications): string + public function qualifications(EducationalOccupationalCredential|string $qualifications): self { if (is_string($qualifications)) { $this->setProperty('qualifications', $qualifications); + return $this; } $this->setProperty('qualifications', $this->parseChild($qualifications)); + return $this; } - public function relevantOccupation(Occupation $occupation): string + public function relevantOccupation(Occupation $occupation): self { $this->setProperty('relevantOccupation', $this->parseChild($occupation)); + return $this; } - public function hiringOrganization(Organization|Person $hiringOrganization): string + public function hiringOrganization(Organization|Person $hiringOrganization): self { $this->setProperty('hiringOrganization', $this->parseChild($hiringOrganization)); + return $this; } - public function incentiveCompensation(string $incentiveCompensation): string + public function incentiveCompensation(string $incentiveCompensation): self { $this->setProperty('incentiveCompensation', $incentiveCompensation); + return $this; } - public function jobBenefits(string $jobBenefits): string + public function jobBenefits(string $jobBenefits): self { $this->setProperty('jobBenefits', $jobBenefits); + return $this; } - public function jobImmediateStart(bool $jobImmediateStart): string + public function jobImmediateStart(bool $jobImmediateStart): self { $this->setProperty('jobImmediateStart', $jobImmediateStart); + return $this; } @@ -93,72 +111,87 @@ public function estimatedSalary(int|MonetaryValue|MonetaryAmountDistribution $es { if (is_int($estimated)) { $this->setProperty('estimatedSalary', $estimated); + return $this; } + $this->setProperty('estimatedSalary', $this->parseChild($estimated)); + return $this; } - public function directApply(bool $directApply): string + public function directApply(bool $directApply): self { $this->setProperty('directApply', $directApply); + return $this; } - public function baseSalary(MonetaryAmount|int $baseSalary): string + public function baseSalary(MonetaryAmount|int $baseSalary): self { if (is_int($baseSalary)) { $this->setProperty('baseSalary', $baseSalary); + return $this; } + $this->setProperty('baseSalary', $this->parseChild($baseSalary)); + return $this; } public function applicationContact(ContactPoint $contactPoint): static { $this->setProperty('applicationContact', $this->parseChild($contactPoint)); + return $this; } - public function employerOverview(string $employerOverview): string + public function employerOverview(string $employerOverview): self { $this->setProperty('employerOverview', $employerOverview); + return $this; } - public function employmentType(string $employmentType): string + public function employmentType(string $employmentType): self { $this->setProperty('employmentType', $employmentType); + return $this; } - public function employmentUnit(Organization $employmentUnit): string + public function employmentUnit(Organization $organization): self { - $this->setProperty('employmentUnit', $this->parseChild($employmentUnit)); + $this->setProperty('employmentUnit', $this->parseChild($organization)); + return $this; } - public function experienceInPlaceOfEducation(bool $experienceInPlaceOfEducation): string + public function experienceInPlaceOfEducation(bool $experienceInPlaceOfEducation): self { $this->setProperty('experienceInPlaceOfEducation', $experienceInPlaceOfEducation); + return $this; } - public function industry(DefinedTerm|string $industry): string + public function industry(DefinedTerm|string $industry): self { if (is_string($industry)) { $this->setProperty('industry', $industry); + return $this; } $this->setProperty('industry', $this->parseChild($industry)); + return $this; } - public function workHours(string $workHours): string + public function workHours(string $workHours): self { $this->setProperty('workHours', $workHours); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Intangible/ListItem.php b/src/Schema/Thing/Intangible/ListItem.php index 80f2e6d..55da8df 100644 --- a/src/Schema/Thing/Intangible/ListItem.php +++ b/src/Schema/Thing/Intangible/ListItem.php @@ -1,5 +1,7 @@ setProperty('item', $item); } + return $this; } - public function nextItem(ListItem $nextItem): static + public function nextItem(self $listItem): static { - $this->setProperty('nextItem', $this->parseChild($nextItem)); + $this->setProperty('nextItem', $this->parseChild($listItem)); + return $this; } public function position(int|string $position): static { $this->setProperty('position', $position); + return $this; } - public function previousItem(ListItem $previousItem): static + public function previousItem(self $listItem): static { - $this->setProperty('previousItem', $this->parseChild($previousItem)); + $this->setProperty('previousItem', $this->parseChild($listItem)); + return $this; } } diff --git a/src/Schema/Thing/Intangible/Occupation.php b/src/Schema/Thing/Intangible/Occupation.php index bb895fa..3da5159 100644 --- a/src/Schema/Thing/Intangible/Occupation.php +++ b/src/Schema/Thing/Intangible/Occupation.php @@ -1,62 +1,73 @@ setProperty('educationRequirements', $this->parseChild($educationRequirements)); } else { $this->setProperty('educationRequirements', $educationRequirements); } + return $this; } - public function estimatedSalary(Thing\Intangible\StructuredValue\MonetaryAmount|Thing\Intangible\StructuredValue\QuantitativeValueDistribution\MonetaryAmountDistribution|int $estimatedSalary): static + public function estimatedSalary(MonetaryAmount|MonetaryAmountDistribution|int $estimatedSalary): static { if ($estimatedSalary instanceof BaseType) { $this->setProperty('estimatedSalary', $this->parseChild($estimatedSalary)); } else { $this->setProperty('estimatedSalary', $estimatedSalary); } + return $this; } - public function occupationLocation(AdministrativeArea $occupationLocation): static + public function occupationLocation(AdministrativeArea $administrativeArea): static { - $this->setProperty('occupationLocation', $this->parseChild($occupationLocation)); + $this->setProperty('occupationLocation', $this->parseChild($administrativeArea)); + return $this; } - public function qualifications(Thing\CreativeWork\EducationalOccupationalCredential|string $qualifications): static + public function qualifications(EducationalOccupationalCredential|string $qualifications): static { if ($qualifications instanceof BaseType) { $this->setProperty('qualifications', $this->parseChild($qualifications)); } else { $this->setProperty('qualifications', $qualifications); } + return $this; } public function responsibilities(string $responsibilities): static { $this->setProperty('responsibilities', $responsibilities); + return $this; } - public function skills(Thing\Intangible\DefinedTerm|string $skills): static + public function skills(DefinedTerm|string $skills): static { if ($skills instanceof BaseType) { $this->setProperty('skills', $this->parseChild($skills)); } else { $this->setProperty('skills', $skills); } + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Intangible/Specialty.php b/src/Schema/Thing/Intangible/Specialty.php index 242a889..d948fdf 100644 --- a/src/Schema/Thing/Intangible/Specialty.php +++ b/src/Schema/Thing/Intangible/Specialty.php @@ -1,5 +1,7 @@ setProperty('value', $value); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Intangible/StructuredValue/MonetaryValue.php b/src/Schema/Thing/Intangible/StructuredValue/MonetaryValue.php index 32af3bd..8950cc3 100644 --- a/src/Schema/Thing/Intangible/StructuredValue/MonetaryValue.php +++ b/src/Schema/Thing/Intangible/StructuredValue/MonetaryValue.php @@ -1,5 +1,7 @@ setProperty('maxValue', $maxValue); + return $this; } public function minValue(int $minValue): static { $this->setProperty('minValue', $minValue); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Intangible/StructuredValue/PropertyValue.php b/src/Schema/Thing/Intangible/StructuredValue/PropertyValue.php index 5774e11..3bd68a6 100644 --- a/src/Schema/Thing/Intangible/StructuredValue/PropertyValue.php +++ b/src/Schema/Thing/Intangible/StructuredValue/PropertyValue.php @@ -1,5 +1,7 @@ setProperty('propertyID', $propertyID); + return $this; } public function value(string|int|float|bool $value): static { $this->setProperty('value', $value); + return $this; } - public function valueReference(BaseType $valueReference): static + public function valueReference(BaseType $baseType): static { - $this->setProperty('valueReference', $this->parseChild($valueReference)); + $this->setProperty('valueReference', $this->parseChild($baseType)); + return $this; } public function minValue(int|float $minValue): static { $this->setProperty('minValue', $minValue); + return $this; } public function maxValue(int|float $maxValue): static { $this->setProperty('maxValue', $maxValue); + return $this; } public function unitCode(string $unitCode): static { $this->setProperty('unitCode', $unitCode); + return $this; } public function unitText(string $unitText): static { $this->setProperty('unitText', $unitText); + return $this; } } diff --git a/src/Schema/Thing/Intangible/StructuredValue/QuantitativeValueDistribution/MonetaryAmountDistribution.php b/src/Schema/Thing/Intangible/StructuredValue/QuantitativeValueDistribution/MonetaryAmountDistribution.php index f0363db..e1775f6 100644 --- a/src/Schema/Thing/Intangible/StructuredValue/QuantitativeValueDistribution/MonetaryAmountDistribution.php +++ b/src/Schema/Thing/Intangible/StructuredValue/QuantitativeValueDistribution/MonetaryAmountDistribution.php @@ -1,5 +1,7 @@ |string $selector + */ public function cssSelector(array|string $selector): static { $this->setProperty('cssSelector', $selector); + return $this; } + /** + * @param array|string $xpath + */ public function xpath(array|string $xpath): static { $this->setProperty('xpath', $xpath); + return $this; } } diff --git a/src/Schema/Thing/Intangible/VirtualLocation.php b/src/Schema/Thing/Intangible/VirtualLocation.php index 105384c..cfb91ac 100644 --- a/src/Schema/Thing/Intangible/VirtualLocation.php +++ b/src/Schema/Thing/Intangible/VirtualLocation.php @@ -1,10 +1,11 @@ setProperty('iataCode', $iataCode); + return $this; } public function boardingPolicy(): static { - return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Organization/LocalBusiness.php b/src/Schema/Thing/Organization/LocalBusiness.php index d1675c8..7d8c895 100644 --- a/src/Schema/Thing/Organization/LocalBusiness.php +++ b/src/Schema/Thing/Organization/LocalBusiness.php @@ -1,5 +1,7 @@ setProperty('additionalName', $additionalName); + return $this; } public function award(string $award): static { $this->setProperty('award', $award); + return $this; } public function jobTitle(string $jobTitle): static { $this->setProperty('jobTitle', $jobTitle); + return $this; } - public function birthDate(\DateTime $birthDate): static + public function birthDate(DateTime $birthDate): static { $this->setProperty('birthDate', $birthDate->format('Y-m-d')); + return $this; } public function birthPlace(string $birthPlace): static { $this->setProperty('birthPlace', $birthPlace); + return $this; } public function email(string $email): static { $this->setProperty('email', $email); + return $this; } public function familyName(string $familyName): static { $this->setProperty('familyName', $familyName); + return $this; } public function givenName(string $givenName): static { $this->setProperty('givenName', $givenName); + return $this; } public function telephone(string $telephone): static { $this->setProperty('telephone', $telephone); + return $this; } @@ -70,74 +84,90 @@ public function address(string|PostalAddress $address): static { if (is_string($address)) { $this->setProperty('address', $address); + return $this; } $this->setProperty('address', $this->parseChild($address)); + return $this; } - public function relatedTo(string|Person $relatedTo): static + public function relatedTo(string|self $relatedTo): static { if (is_string($relatedTo)) { $this->setProperty('relatedTo', $relatedTo); + return $this; } $this->setProperty('relatedTo', $this->parseChild($relatedTo)); + return $this; } public function alumniOf(EducationalOrganization|Organization $alumniOf): static { $this->setProperty('alumniOf', $this->parseChild($alumniOf)); + return $this; } public function brand(Organization|Brand $brand): static { $this->setProperty('brand', $this->parseChild($brand)); + return $this; } public function callSign(string $callSign): static { $this->setProperty('callSign', $callSign); + return $this; } - public function children(array|Person $children): static + /** + * @param array|self $children + */ + public function children(array|self $children): static { if (is_array($children)) { $this->setProperty('children', $this->parseArray($children)); + return $this; } $this->setProperty('children', $this->parseChild($children)); + return $this; } - public function colleague(Person|Url $colleague): static + public function colleague(self|Url $colleague): static { $this->setProperty('colleague', $this->parseChild($colleague)); + return $this; } - public function spouse(Person $person): static + public function spouse(self $person): static { $this->setProperty('spouse', $this->parseChild($person)); + return $this; } public function worksFor(Organization $organization): static { $this->setProperty('worksFor', $this->parseChild($organization)); + return $this; } public function nationality(Country $country): static { $this->setProperty('nationality', $this->parseChild($country)); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Place.php b/src/Schema/Thing/Place.php index 5ccc1c7..0da525a 100644 --- a/src/Schema/Thing/Place.php +++ b/src/Schema/Thing/Place.php @@ -1,90 +1,105 @@ setProperty('address', $this->parseChild($address)); + $this->setProperty('address', $this->parseChild($postalAddress)); + return $this; } public function branchCode(string $branchCode): static { $this->setProperty('branchCode', $branchCode); + return $this; } - public function containedInPlace(Place $place): static + public function containedInPlace(self $place): static { $this->setProperty('containedInPlace', $this->parseChild($place)); + return $this; } - public function containsPlace(Place $place): static + public function containsPlace(self $place): static { $this->setProperty('containsPlace', $this->parseChild($place)); + return $this; } public function event(Event $event): static { $this->setProperty('event', $this->parseChild($event)); + return $this; } public function faxNumber(string $faxNumber): static { $this->setProperty('faxNumber', $faxNumber); + return $this; } - public function geo(GeoShape $geo): static + public function geo(GeoShape $geoShape): static { - $this->setProperty('geo', $this->parseChild($geo)); + $this->setProperty('geo', $this->parseChild($geoShape)); + return $this; } public function keywords(string $keywords): static { $this->setProperty('keywords', $keywords); + return $this; } public function latitude(float|string $latitude): static { $this->setProperty('latitude', $latitude); + return $this; } - public function logo(Thing\CreativeWork\MediaObject\ImageObject|Url $logo): static + public function logo(ImageObject|Url $logo): static { $this->setProperty('logo', $this->parseChild($logo)); + return $this; } public function longitude(float|string $longitude): static { $this->setProperty('longitude', $longitude); + return $this; } public function slogan(string $slogan): static { $this->setProperty('slogan', $slogan); + return $this; } public function telephone(string $telephone): static { $this->setProperty('telephone', $telephone); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Thing/Place/AdministrativeArea/Country.php b/src/Schema/Thing/Place/AdministrativeArea/Country.php index 3044178..1934121 100644 --- a/src/Schema/Thing/Place/AdministrativeArea/Country.php +++ b/src/Schema/Thing/Place/AdministrativeArea/Country.php @@ -1,11 +1,11 @@ setProperty('serialNumber', $serialNumber); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Traits/ArticleTrait.php b/src/Schema/Traits/ArticleTrait.php index d6325b1..e980710 100644 --- a/src/Schema/Traits/ArticleTrait.php +++ b/src/Schema/Traits/ArticleTrait.php @@ -1,5 +1,7 @@ setProperty('articleBody', $body); + return $this; } public function articleSection(string $section): static { $this->setProperty('articleSection', $section); + return $this; } @@ -25,30 +29,35 @@ public function backstory(string|CreativeWork $backstory): static } else { $this->setProperty('backstory', $backstory); } + return $this; } public function pageEnd(string|int $pageEnd): static { $this->setProperty('pageEnd', $pageEnd); + return $this; } public function pageStart(string|int $pageStart): static { $this->setProperty('pageStart', $pageStart); + return $this; } public function pagination(string $pagination): static { $this->setProperty('pagination', $pagination); + return $this; } public function wordCount(int $count): static { $this->setProperty('wordCount', $count); + return $this; } } diff --git a/src/Schema/Traits/CreativeWorkTrait.php b/src/Schema/Traits/CreativeWorkTrait.php index 506b8c5..1db3af1 100644 --- a/src/Schema/Traits/CreativeWorkTrait.php +++ b/src/Schema/Traits/CreativeWorkTrait.php @@ -1,63 +1,77 @@ setProperty('abstract', $abstract); + return $this; } public function accessMode(string $accessMode): static { $this->setProperty('accessMode', $accessMode); + return $this; } public function accessibilityAPI(string $accessibilityAPI): static { $this->setProperty('accessibilityAPI', $accessibilityAPI); + return $this; } public function accessibilityControl(string $accessibilityControl): static { $this->setProperty('accessibilityControl', $accessibilityControl); + return $this; } public function accessibilityFeature(string $accessibilityFeature): static { $this->setProperty('accessibilityFeature', $accessibilityFeature); + return $this; } public function accessibilityHazard(string $accessibilityHazard): static { $this->setProperty('accessibilityHazard', $accessibilityHazard); + return $this; } public function accessibilitySummary(string $accessibilitySummary): static { $this->setProperty('accessibilitySummary', $accessibilitySummary); + return $this; } public function accountablePerson(Person $person): static { $this->setProperty('accountablePerson', $this->parseChild($person)); + return $this; } @@ -65,45 +79,53 @@ public function acquireLicensePage(string|CreativeWork $acquireLicensePage): sta { if (is_string($acquireLicensePage)) { $this->setProperty('acquireLicensePage', $acquireLicensePage); + return $this; } $this->setProperty('acquireLicensePage', $this->parseChild($acquireLicensePage)); + return $this; } public function alternativeHeadline(string $alternativeHeadline): static { $this->setProperty('alternativeHeadline', $alternativeHeadline); + return $this; } - public function archivedAt(Url|CreativeWork\WebPage $archivedAt): static + public function archivedAt(Url|WebPage $archivedAt): static { if ($archivedAt instanceof Url) { $this->setProperty('archivedAt', $this->parseChild($archivedAt)); + return $this; } $this->setProperty('archivedAt', $this->parseChild($archivedAt)); + return $this; } public function author(Person|Organization $author): static { $this->setProperty('author', $this->parseChild($author)); + return $this; } public function award(string $award): static { $this->setProperty('award', $award); + return $this; } - public function character(Person $character): static + public function character(Person $person): static { - $this->setProperty('character', $this->parseChild($character)); + $this->setProperty('character', $this->parseChild($person)); + return $this; } @@ -111,181 +133,208 @@ public function citation(string|CreativeWork $citation): static { if (is_string($citation)) { $this->setProperty('citation', $citation); + return $this; } $this->setProperty('citation', $this->parseChild($citation)); + return $this; } public function contributor(Person|Organization $contributor): static { $this->setProperty('contributor', $this->parseChild($contributor)); + return $this; } public function creator(Person|Organization $creator): static { $this->setProperty('creator', $this->parseChild($creator)); + return $this; } - public function countryOfOrigin(Country $countryOfOrigin): static + public function countryOfOrigin(Country $country): static { - $this->setProperty('countryOfOrigin', $this->parseChild($countryOfOrigin)); + $this->setProperty('countryOfOrigin', $this->parseChild($country)); + return $this; } - public function expires(\DateTime $dateTime): static + public function expires(DateTime $dateTime): static { $this->setProperty('expires', $dateTime); + return $this; } public function copyrightHolder(Person|Organization $copyrightHolder): static { $this->setProperty('copyrightHolder', $this->parseChild($copyrightHolder)); + return $this; } public function copyrightNotice(string $copyrightNotice): static { $this->setProperty('copyrightNotice', $copyrightNotice); + return $this; } public function copyrightYear(int $copyrightYear): static { $this->setProperty('copyrightYear', $copyrightYear); + return $this; } public function headline(string $headline): static { $this->setProperty('headline', $headline); + return $this; } public function keywords(string $keywords): static { $this->setProperty('keywords', $keywords); + return $this; } public function maintainer(Person|Organization $maintainer): static { $this->setProperty('maintainer', $this->parseChild($maintainer)); + return $this; } public function isFamilyFriendly(bool $isFamilyFriendly): static { $this->setProperty('isFamilyFriendly', $isFamilyFriendly); + return $this; } public function creditText(string $creditText): static { $this->setProperty('creditText', $creditText); + return $this; } - public function editor(Person $editor): static + public function editor(Person $person): static { - $this->setProperty('editor', $this->parseChild($editor)); + $this->setProperty('editor', $this->parseChild($person)); + return $this; } public function funder(Person|Organization $funder): static { $this->setProperty('funder', $this->parseChild($funder)); + return $this; } public function publisher(Person|Organization $publisher): static { $this->setProperty('publisher', $this->parseChild($publisher)); + return $this; } public function sponsor(Person|Organization $sponsor): static { $this->setProperty('sponsor', $this->parseChild($sponsor)); + return $this; } public function text(string $text): static { $this->setProperty('text', $text); + return $this; } public function conditionsOfAccess(string $conditions): static { $this->setProperty('conditionsOfAccess', $conditions); + return $this; } - public function mainEntity(Thing $entity): static + public function mainEntity(Thing $thing): static { - $this->setProperty('mainEntity', $this->parseChild($entity)); + $this->setProperty('mainEntity', $this->parseChild($thing)); + return $this; } - public function thumbnail(CreativeWork\MediaObject\ImageObject $thumbnail): static + public function thumbnail(ImageObject $imageObject): static { - $this->setProperty('thumbnail', $this->parseChild($thumbnail)); + $this->setProperty('thumbnail', $this->parseChild($imageObject)); + return $this; } public function thumbnailUrl(Url $thumbnailUrl): static { $this->setProperty('thumbnailUrl', $this->parseChild($thumbnailUrl)); + return $this; } public function version(string $version): static { $this->setProperty('version', $version); + return $this; } - public function dateCreated(\DateTime $date, \DateTimeZone $dateTimeZone = null): static + public function dateCreated(DateTime $date, ?DateTimeZone $dateTimeZone = null): static { $this->setDateTimeProperty( name: 'dateCreated', date: $date, dateTimeZone: $dateTimeZone ); + return $this; } - public function dateModified(\DateTime $date, \DateTimeZone $dateTimeZone = null): static + public function dateModified(DateTime $date, ?DateTimeZone $dateTimeZone = null): static { $this->setDateTimeProperty( name: 'dateModified', date: $date, dateTimeZone: $dateTimeZone ); + return $this; } - public function datePublished(\DateTime $date, \DateTimeZone $dateTimeZone = null): static + public function datePublished(DateTime $date, ?DateTimeZone $dateTimeZone = null): static { $this->setDateTimeProperty( name: 'datePublished', date: $date, dateTimeZone: $dateTimeZone ); + return $this; } - private function setDateTimeProperty(string $name, \DateTime $date, \DateTimeZone $dateTimeZone = null): void + private function setDateTimeProperty(string $name, DateTime $date, ?DateTimeZone $dateTimeZone = null): void { - if ($dateTimeZone instanceof \DateTimeZone) { + if ($dateTimeZone instanceof DateTimeZone) { $date->setTimezone($dateTimeZone); } - $this->setProperty($name, $date->format(DATE_ATOM)); + $this->setProperty($name, $date->format(\DATE_ATOM)); } -} \ No newline at end of file +} diff --git a/src/Schema/Traits/CurrencyPropertiesTrait.php b/src/Schema/Traits/CurrencyPropertiesTrait.php index 94e1225..8d92ca6 100644 --- a/src/Schema/Traits/CurrencyPropertiesTrait.php +++ b/src/Schema/Traits/CurrencyPropertiesTrait.php @@ -1,5 +1,7 @@ setProperty('currency', $currency); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Traits/LocalBusinessServiceTrait.php b/src/Schema/Traits/LocalBusinessServiceTrait.php index 3654087..45922ad 100644 --- a/src/Schema/Traits/LocalBusinessServiceTrait.php +++ b/src/Schema/Traits/LocalBusinessServiceTrait.php @@ -1,30 +1,34 @@ setProperty('currenciesAccepted', $currenciesAccepted); -// return $this; -// } - - public function openingHours(string $openingHours): static - { - $this->setProperty('openingHours', $openingHours); - return $this; - } - -// public function paymentAccepted(string $paymentAccepted): static -// { -// $this->setProperty('paymentAccepted', $paymentAccepted); -// return $this; -// } - - public function priceRange(string $priceRange): static - { - $this->setProperty('priceRange', $priceRange); - return $this; - } -} \ No newline at end of file + // public function currenciesAccepted(string $currenciesAccepted): static + // { + // $this->setProperty('currenciesAccepted', $currenciesAccepted); + // return $this; + // } + + public function openingHours(string $openingHours): static + { + $this->setProperty('openingHours', $openingHours); + + return $this; + } + + // public function paymentAccepted(string $paymentAccepted): static + // { + // $this->setProperty('paymentAccepted', $paymentAccepted); + // return $this; + // } + + public function priceRange(string $priceRange): static + { + $this->setProperty('priceRange', $priceRange); + + return $this; + } +} diff --git a/src/Schema/Traits/OrganizationTrait.php b/src/Schema/Traits/OrganizationTrait.php index c488710..503f045 100644 --- a/src/Schema/Traits/OrganizationTrait.php +++ b/src/Schema/Traits/OrganizationTrait.php @@ -1,9 +1,14 @@ setProperty('duns', $duns); + return $this; } /** - * @param string $currenciesAccepted * @return $this */ public function currenciesAccepted(string $currenciesAccepted): static { $this->setProperty('currenciesAccepted', $currenciesAccepted); + return $this; } /** - * @param string $paymentAccepted * @return $this */ public function paymentAccepted(string $paymentAccepted): static { $this->setProperty('paymentAccepted', $paymentAccepted); + return $this; } /** - * @param CreativeWork|string $creativeWork * @return $this */ public function actionableFeedbackPolicy(CreativeWork|string $creativeWork): static { if (is_string($creativeWork)) { $this->setProperty('actionableFeedbackPolicy', $creativeWork); + return $this; } $this->setProperty('actionableFeedbackPolicy', $this->parseChild($creativeWork)); + return $this; } /** - * @param PostalAddress|string $address * @return $this */ public function address(PostalAddress|string $address): static { if (is_string($address)) { $this->setProperty('address', $address); + return $this; } $this->setProperty('address', $this->parseChild($address)); + return $this; } /** - * @param array $alumni Person[] + * @param array $alumni Person[] + * * @return $this */ public function alumni(array $alumni): static { $this->setProperty('alumni', $this->parseArray($alumni)); + return $this; } /** - * @param array $employee Person[] + * @param array $employee Person[] + * * @return $this */ public function employee(array $employee): static { $this->setProperty('employee', $this->parseArray($employee)); + return $this; } /** - * @param array $member Person[] + * @param array $member Person[] + * * @return $this */ public function member(array $member): static { $this->setProperty('member', $this->parseArray($member)); + return $this; } public function faxNumber(string $faxNumber): static { $this->setProperty('faxNumber', $faxNumber); + return $this; } /** - * @param array $founders Person[] | Organization[] + * @param array $founders Person[] | Organization[] + * * @return $this */ public function founders(array $founders): static { $this->setProperty('founders', $this->parseArray($founders)); + return $this; } /** - * @param \DateTime $foundingDate * @return $this - * @throws \DateMalformedStringException + * + * @throws DateMalformedStringException */ - public function foundingDate(\DateTime $foundingDate): static + public function foundingDate(DateTime $foundingDate): static { $this->setProperty('foundingDate', Utils::parseFullDateIso8601($foundingDate)); + return $this; } public function email(string $email): static { $this->setProperty('email', $email); + return $this; } /** - * @param Place $foundingPlace * @return $this */ public function foundingPlace(Place $foundingPlace): static { $this->setProperty('foundingPlace', $this->parseChild($foundingPlace)); + return $this; } /** - * @param \Rami\SeoBundle\Schema\Thing\Organization|\Rami\SeoBundle\Schema\Thing\Person $organization * @return $this */ public function funder(Organization|Person $organization): static { $this->setProperty('funder', $this->parseChild($organization)); + return $this; } /** - * @param Grant $grant * @return $this */ public function funding(Grant $grant): static { $this->setProperty('funding', $this->parseChild($grant)); + return $this; } /** - * @param string $globalLocationNumber * @return $this */ public function globalLocationNumber(string $globalLocationNumber): static { $this->setProperty('globalLocationNumber', $globalLocationNumber); + return $this; } /** - * @param string $legalName * @return $this */ public function legalName(string $legalName): static { $this->setProperty('legalName', $legalName); + return $this; } public function subOrganization(Organization $organization): static { $this->setProperty('subOrganization', $this->parseChild($organization)); + return $this; } @@ -197,19 +217,25 @@ public function slogan(string|DefinedTerm $slogan): static { if (is_string($slogan)) { $this->setProperty('slogan', $slogan); + return $this; } + $this->setProperty('slogan', $this->parseChild($slogan)); + return $this; } - public function logo(CreativeWork\MediaObject\ImageObject|string $logo): static + public function logo(ImageObject|string $logo): static { if (is_string($logo)) { $this->setProperty('logo', $logo); + return $this; } + $this->setProperty('logo', $this->parseChild($logo)); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Traits/ProductTrait.php b/src/Schema/Traits/ProductTrait.php index 9c617e3..2d610ec 100644 --- a/src/Schema/Traits/ProductTrait.php +++ b/src/Schema/Traits/ProductTrait.php @@ -1,5 +1,7 @@ setProperty('sku', $sku); + return $this; } public function colour(string $colour): static { $this->setProperty('color', $colour); + return $this; } public function brand(Organization|Brand $brand): static { $this->setProperty('brand', $this->parseChild($brand)); + return $this; } - public function countryOfOrigin(Country $countryOfOrigin): static + public function countryOfOrigin(Country $country): static { - $this->setProperty('countryOfOrigin', $this->parseChild($countryOfOrigin)); + $this->setProperty('countryOfOrigin', $this->parseChild($country)); + return $this; } public function countryOfLastProcessing(string $countryOfLastProcessing): static { $this->setProperty('countryOfLastProcessing', $countryOfLastProcessing); + return $this; } public function countryOfAssemble(string $countryOfAssemble): static { $this->setProperty('countryOfAssemble', $countryOfAssemble); + return $this; } - public function manufacturer(Organization $manufacturer): static + public function manufacturer(Organization $organization): static { - $this->setProperty('manufacturer', $this->parseChild($manufacturer)); + $this->setProperty('manufacturer', $this->parseChild($organization)); + return $this; } public function slogan(string $slogan): static { $this->setProperty('slogan', $slogan); + return $this; } public function nsn(string $nsn): static { $this->setProperty('nsn', $nsn); + return $this; } public function mpn(string $mpn): static { $this->setProperty('mpn', $mpn); + return $this; } public function mobileUrl(string $mobileUrl): static { $this->setProperty('mobileUrl', $mobileUrl); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Traits/SocialMediaPostingTrait.php b/src/Schema/Traits/SocialMediaPostingTrait.php index d1db977..4be446f 100644 --- a/src/Schema/Traits/SocialMediaPostingTrait.php +++ b/src/Schema/Traits/SocialMediaPostingTrait.php @@ -1,20 +1,24 @@ setProperty('sharedContent', $this->parseChild($content)); + $this->setProperty('sharedContent', $this->parseChild($article)); + return $this; } public function discussionUrl(string $url): static { $this->setProperty('discussionUrl', $url); + return $this; } -} \ No newline at end of file +} diff --git a/src/Schema/Traits/ThingTrait.php b/src/Schema/Traits/ThingTrait.php index 601b3be..8d3ed88 100644 --- a/src/Schema/Traits/ThingTrait.php +++ b/src/Schema/Traits/ThingTrait.php @@ -1,5 +1,7 @@ setProperty('additionalType', $additionalType); + return $this; } public function alternateName(string $alternateName): static { $this->setProperty('alternateName', $alternateName); + return $this; } @@ -32,12 +36,14 @@ public function description(string|TextObject $description): static } else { $this->setProperty('description', $description); } + return $this; } public function disambiguatingDescription(string $description): static { $this->setProperty('disambiguatingDescription', $description); + return $this; } @@ -48,6 +54,7 @@ public function identifier(PropertyValue|string $identifier): static } else { $this->setProperty('identifier', $identifier); } + return $this; } @@ -58,6 +65,7 @@ public function image(ImageObject|string $image): static } else { $this->setProperty('image', $image); } + return $this; } @@ -68,36 +76,42 @@ public function mainEntityOfPage(CreativeWork|string $mainEntityOfPage): static } else { $this->setProperty('mainEntityOfPage', $mainEntityOfPage); } + return $this; } public function name(string $name): static { $this->setProperty('name', $name); + return $this; } public function owner(Organization|Person $owner): static { $this->setProperty('owner', $this->parseChild($owner)); + return $this; } public function potentialAction(Action $action): static { $this->setProperty('potentialAction', $this->parseChild($action)); + return $this; } public function sameAs(string $sameAs): static { $this->setProperty('sameAs', $sameAs); + return $this; } public function serviceOutput(Service $service): Service { $this->setProperty('serviceOutput', $this->parseChild($service)); + return $service; } -} \ No newline at end of file +} diff --git a/src/Schema/Traits/WebPageTrait.php b/src/Schema/Traits/WebPageTrait.php index fc21d0f..34aae3f 100644 --- a/src/Schema/Traits/WebPageTrait.php +++ b/src/Schema/Traits/WebPageTrait.php @@ -1,7 +1,10 @@ setProperty('breadcrumb', $breadcrumb); } + return $this; } - public function lastReviewed(\DateTime $date): static + public function lastReviewed(DateTime $date): static { $this->setProperty('lastReviewed', $date->format('Y-m-d')); + return $this; } - public function mainContentOfPage(WebPageElement $element): static + public function mainContentOfPage(WebPageElement $webPageElement): static { - $this->setProperty('mainContentOfPage', $this->parseChild($element)); + $this->setProperty('mainContentOfPage', $this->parseChild($webPageElement)); + return $this; } - public function primaryImageOfPage(ImageObject $image): static + public function primaryImageOfPage(ImageObject $imageObject): static { - $this->setProperty('primaryImageOfPage', $this->parseChild($image)); + $this->setProperty('primaryImageOfPage', $this->parseChild($imageObject)); + return $this; } @@ -46,8 +55,10 @@ public function relatedLink(string $url): static if (!is_array($existingLinks)) { $existingLinks = [$existingLinks]; } + $existingLinks[] = $url; $this->setProperty('relatedLink', $existingLinks); + return $this; } @@ -57,8 +68,10 @@ public function reviewedBy(Organization|Person $reviewer): static if (!is_array($existingReviewers)) { $existingReviewers = [$existingReviewers]; } + $existingReviewers[] = $this->parseChild($reviewer); $this->setProperty('reviewedBy', $existingReviewers); + return $this; } @@ -68,8 +81,10 @@ public function significantLink(string $url): static if (!is_array($existingLinks)) { $existingLinks = [$existingLinks]; } + $existingLinks[] = $url; $this->setProperty('significantLink', $existingLinks); + return $this; } @@ -87,12 +102,14 @@ public function speakable(SpeakableSpecification|string $speakable): static } $this->setProperty('speakable', $existingSpeakable); + return $this; } public function specialty(Specialty $specialty): static { $this->setProperty('specialty', $this->parseChild($specialty)); + return $this; } } diff --git a/src/Seo/GoogleTagManager/TagManager.php b/src/Seo/GoogleTagManager/TagManager.php index 7940f77..e69c7f0 100644 --- a/src/Seo/GoogleTagManager/TagManager.php +++ b/src/Seo/GoogleTagManager/TagManager.php @@ -1,4 +1,7 @@ gtmId = $gtmId; } - - /** - * @return string - */ public function renderHeadTag(): string { - if (!$this->gtmId) return ''; + if (!$this->gtmId) { + return ''; + } return << - - - HTML; + + + + HTML; } public function renderBodyTag(): string { - if (!$this->gtmId) return ''; + if (!$this->gtmId) { + return ''; + } return << @@ -54,4 +55,4 @@ public function renderBodyTag(): string HTML; } -} \ No newline at end of file +} diff --git a/src/Seo/GoogleTagManager/TagManagerInterface.php b/src/Seo/GoogleTagManager/TagManagerInterface.php index 434a95b..52c931f 100644 --- a/src/Seo/GoogleTagManager/TagManagerInterface.php +++ b/src/Seo/GoogleTagManager/TagManagerInterface.php @@ -1,4 +1,7 @@ pixelId = $pixelId; } - /** - * @return string - */ public function renderPixel(): string { if (null === $this->pixelId) { @@ -33,25 +30,24 @@ public function renderPixel(): string } return << - - - - HTML; - + + + + + HTML; } -} \ No newline at end of file +} diff --git a/src/Seo/MetaPixel/MetaPixelInterface.php b/src/Seo/MetaPixel/MetaPixelInterface.php index bc82ac7..a5c14e4 100644 --- a/src/Seo/MetaPixel/MetaPixelInterface.php +++ b/src/Seo/MetaPixel/MetaPixelInterface.php @@ -1,4 +1,7 @@ format('Y')); + return new DateTime($date->format('Y')); } /** - * @throws \DateMalformedStringException + * @throws DateMalformedStringException */ - public static function parseFullDateIso8601(\DateTime $date): \DateTime + public static function parseFullDateIso8601(DateTime $date): DateTime { - return new \DateTime($date->format('Y-m-d')); + return new DateTime($date->format('Y-m-d')); } -} \ No newline at end of file +} diff --git a/src/SeoBundle.php b/src/SeoBundle.php index 35ce738..673e8db 100644 --- a/src/SeoBundle.php +++ b/src/SeoBundle.php @@ -1,4 +1,7 @@ $config + */ public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void { $container->import('../config/services.php'); @@ -27,16 +38,22 @@ public function loadExtension(array $config, ContainerConfigurator $container, C $container->parameters()->set('seo.open_graph', $config['open_graph'] ?? null); $container->parameters()->set('seo.sitemap', $config['sitemap'] ?? null); - if ($config['google_tag_manager']['enabled']) { - $container->parameters()->set('seo.google_tag_manager', $config['google_tag_manager']); + $googleTagManager = $config['google_tag_manager'] ?? []; + assert(is_array($googleTagManager)); + if ($googleTagManager['enabled'] ?? false) { + $container->parameters()->set('seo.google_tag_manager', $googleTagManager); } - if ($config['schema']['enabled']) { - $container->parameters()->set('seo.schema', $config['schema']); + $schema = $config['schema'] ?? []; + assert(is_array($schema)); + if ($schema['enabled'] ?? false) { + $container->parameters()->set('seo.schema', $schema); } - if ($config['meta_pixel']['enabled']) { - $container->parameters()->set('seo.meta_pixel', $config['meta_pixel']); + $metaPixel = $config['meta_pixel'] ?? []; + assert(is_array($metaPixel)); + if ($metaPixel['enabled'] ?? false) { + $container->parameters()->set('seo.meta_pixel', $metaPixel); } } @@ -47,9 +64,12 @@ public function configure(DefinitionConfigurator $definition): void public function getPath(): string { - $reflected = new \ReflectionObject($this); + $reflectionObject = new ReflectionObject($this); + + /** @var string $fileName */ + $fileName = $reflectionObject->getFileName(); - return \dirname($reflected->getFileName(), 2); + return dirname($fileName, 2); } public function build(ContainerBuilder $container): void @@ -59,4 +79,4 @@ public function build(ContainerBuilder $container): void $container->addCompilerPass(new GoogleTagCompilerPass()); $container->addCompilerPass(new MetaPixelCompilerPass()); } -} \ No newline at end of file +} diff --git a/src/Sitemap/Attributes/Sitemap.php b/src/Sitemap/Attributes/Sitemap.php index d45af60..2d9765a 100644 --- a/src/Sitemap/Attributes/Sitemap.php +++ b/src/Sitemap/Attributes/Sitemap.php @@ -1,18 +1,17 @@ |null $fetchCriteria * @param array|null $urlGenerationAttributes - * @param string|null $lastModifiedField - * @param string|null $fileName */ public function __construct( public ?string $entityClass = null, @@ -20,5 +19,6 @@ public function __construct( public ?array $urlGenerationAttributes = [], public ?string $lastModifiedField = null, public ?string $fileName = null, - ) {} -} \ No newline at end of file + ) { + } +} diff --git a/src/Sitemap/Event/UpdateSitemapEvent.php b/src/Sitemap/Event/UpdateSitemapEvent.php index 241ccf2..d6002b7 100644 --- a/src/Sitemap/Event/UpdateSitemapEvent.php +++ b/src/Sitemap/Event/UpdateSitemapEvent.php @@ -1,4 +1,7 @@ messageBus->dispatch(new GenerateSitemapMessage()); } -} \ No newline at end of file +} diff --git a/src/Sitemap/Message/GenerateSitemapMessage.php b/src/Sitemap/Message/GenerateSitemapMessage.php index 4d0685a..066f879 100644 --- a/src/Sitemap/Message/GenerateSitemapMessage.php +++ b/src/Sitemap/Message/GenerateSitemapMessage.php @@ -1,4 +1,7 @@ baseUrl; } -} \ No newline at end of file +} diff --git a/src/Sitemap/MessageHandler/GenerateSitemapMessageHandler.php b/src/Sitemap/MessageHandler/GenerateSitemapMessageHandler.php index 971a212..0a6d7b9 100644 --- a/src/Sitemap/MessageHandler/GenerateSitemapMessageHandler.php +++ b/src/Sitemap/MessageHandler/GenerateSitemapMessageHandler.php @@ -1,4 +1,7 @@ sitemap->generateSitemap($message->getBaseUrl()); + $this->sitemap->generateSitemap($generateSitemapMessage->getBaseUrl()); } -} \ No newline at end of file +} diff --git a/src/Sitemap/Sitemap.php b/src/Sitemap/Sitemap.php index ed49fb8..f1f707b 100644 --- a/src/Sitemap/Sitemap.php +++ b/src/Sitemap/Sitemap.php @@ -1,4 +1,7 @@ publicDir . 'sitemaps')) mkdir($this->publicDir . 'sitemaps'); + if (false === file_exists($this->publicDir.'sitemaps')) { + mkdir($this->publicDir.'sitemaps'); + } if (!file_exists($this->publicDir.'sitemap.xml')) { $this->createIndexSitemapFile(); } - $routes = $this->router->getRouteCollection(); + $routeCollection = $this->router->getRouteCollection(); $allRoutes = []; - foreach ($routes as $name => $route) { + foreach ($routeCollection as $name => $route) { + if (str_starts_with($name, '_profiler')) { + continue; + } + + if (str_starts_with($name, '_preview_error')) { + continue; + } + + if (str_starts_with($name, '_wdt')) { + continue; + } - if (str_starts_with($name, '_profiler') || str_starts_with($name, '_preview_error') || str_starts_with($name, '_wdt') || str_starts_with($name, '_debug')) { + if (str_starts_with($name, '_debug')) { continue; } - $controller = explode(':', $route->getDefaults()['_controller'])[0]; - $ref = new \ReflectionClass($controller); + $defaults = $route->getDefaults(); + $controllerValue = $defaults['_controller'] ?? null; + if (!is_string($controllerValue)) { + continue; + } + + if ('' === $controllerValue) { + continue; + } + + $controller = explode(':', $controllerValue)[0]; + /** @var class-string $controller */ + $ref = new ReflectionClass($controller); foreach ($ref->getMethods() as $method) { $attributes = $method->getAttributes(); $currentRoute = null; if (count($attributes) > 1) { - $sitemapAttribute = false; - $routerExists = false; + $sitemapAttribute = false; + $routerExists = false; foreach ($attributes as $attribute) { $instance = $attribute->newInstance(); - if ($instance instanceof \Rami\SeoBundle\Sitemap\Attributes\Sitemap) { + if ($instance instanceof SitemapAttribute) { $sitemapAttribute = true; if (null !== $instance->entityClass) { $this->generateDynamicSitemap($attributes, $baseUrl); - break 1; + break; } } + if ($instance instanceof Route) { $routerExists = true; $currentRoute = $instance; } } - if (!$sitemapAttribute || !$routerExists) { + if (!$sitemapAttribute) { continue; } - $allRoutes[] = $currentRoute; - } - } - } - $allRoutes = array_unique($allRoutes, SORT_REGULAR); - $this->addRoutesToXml($allRoutes, $baseUrl); - } + if (!$routerExists) { + continue; + } - /** - * @param array $routes - * @param string|null $baseUrl - * @return void - * @throws \DOMException - */ - private function addRoutesToXml(array $routes, ?string $baseUrl = null): void - { - $filename = $this->publicDir.'sitemaps/default.xml'; - $request = $this->requestStack->getCurrentRequest(); - $defaultSitemap = new \DomDocument('1.0', 'UTF-8'); - $defaultSitemap->formatOutput = true; - $rootElement = $defaultSitemap->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset'); - $defaultSitemap->appendChild($rootElement); - foreach ($routes as $route) { - if (!$route instanceof Route) { - continue; + $allRoutes[] = $currentRoute; + } } - $locationElement = $defaultSitemap->createElement('loc', $this->urlGenerator->generate($route->getName(), [], UrlGeneratorInterface::ABSOLUTE_URL)); - $urlElement = $defaultSitemap->createElement('url'); - $urlElement->appendChild($locationElement); - $rootElement->appendChild($urlElement); - $defaultSitemap->appendChild($rootElement); } - $defaultSitemap->save($this->publicDir.'sitemaps/default.xml'); - if (null !== $request) { - $this->addXmlToSitemap( $request->getSchemeAndHttpHost() .'/sitemaps/'.basename($filename)); - } else { - $this->addXmlToSitemap($baseUrl.'/sitemaps/'.basename($filename)); - } + $allRoutes = array_unique($allRoutes, \SORT_REGULAR); + /** @var array $filteredRoutes */ + $filteredRoutes = array_filter($allRoutes, fn (?Route $route): bool => $route instanceof Route); + $this->addRoutesToXml($filteredRoutes, $baseUrl); } /** - * @param array $attributes - * @param string|null $baseUrl - * @return void - * @throws \DOMException + * @throws DOMException */ public function generateDynamicSitemap(array $attributes, ?string $baseUrl = null): void { @@ -138,43 +153,64 @@ public function generateDynamicSitemap(array $attributes, ?string $baseUrl = nul $sitemap = null; $request = $this->requestStack->getCurrentRequest(); foreach ($attributes as $attribute) { - $attribute = $attribute->newInstance(); - if ($attribute instanceof Route || $attribute instanceof \Symfony\Component\Routing\Annotation\Route) { - $route = $attribute; + if (!$attribute instanceof ReflectionAttribute) { + continue; + } + + $instance = $attribute->newInstance(); + if ($instance instanceof Route) { + $route = $instance; } - if ($attribute instanceof \Rami\SeoBundle\Sitemap\Attributes\Sitemap) { - $sitemap = $attribute; + if ($instance instanceof SitemapAttribute) { + $sitemap = $instance; } } - if (null === $route) { + + if (!$route instanceof Route) { return; } - if (null === $sitemap) { + if (!$sitemap instanceof SitemapAttribute) { return; } - $defaultFilename = explode("\\", $sitemap->entityClass); + $defaultFilename = explode('\\', (string) $sitemap->entityClass); $fileName = $sitemap->fileName ?? strtolower(end($defaultFilename)); - $sitemapDom = new DOMDocument('1.0', 'UTF-8'); - $sitemapDom->formatOutput = true; + $domDocument = new DOMDocument('1.0', 'UTF-8'); + $domDocument->formatOutput = true; + + if (null === $sitemap->entityClass) { + return; + } - $entityManagerRegistery = $this->managerRegistry->getManagerForClass($sitemap->entityClass); + /** @var class-string $entityClass */ + $entityClass = $sitemap->entityClass; + $entityManagerRegistery = $this->managerRegistry->getManagerForClass($entityClass); - if (!$entityManagerRegistery) { + if (!$entityManagerRegistery instanceof ObjectManager) { return; } - $rootElement = $sitemapDom->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset'); - $sitemapDom->appendChild($rootElement); + $rootElement = $domDocument->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset'); + $domDocument->appendChild($rootElement); - $entities = $entityManagerRegistery->getRepository($sitemap->entityClass)->findBy($sitemap->fetchCriteria); + /** @var array $criteria */ + $criteria = $sitemap->fetchCriteria ?? []; + $entities = $entityManagerRegistery->getRepository($entityClass)->findBy($criteria); $urlGenerationAttribute = []; foreach ($entities as $entity) { + if (!is_array($sitemap->urlGenerationAttributes)) { + continue; + } + foreach ($sitemap->urlGenerationAttributes as $key) { + if (!is_string($key)) { + continue; + } + if (property_exists($entity, $key)) { $method = 'get'.ucfirst($key); if (method_exists($entity, $method)) { @@ -184,74 +220,133 @@ public function generateDynamicSitemap(array $attributes, ?string $baseUrl = nul } $modifiedDate = null; - $locationElement = $sitemapDom->createElement('loc', $this->urlGenerator->generate($route->getName(), $urlGenerationAttribute, UrlGeneratorInterface::ABSOLUTE_URL)); - $urlElement = $sitemapDom->createElement('url'); + $routeName = $route->getName(); + if (null === $routeName) { + continue; + } + + $locationElement = $domDocument->createElement('loc', $this->urlGenerator->generate($routeName, $urlGenerationAttribute, UrlGeneratorInterface::ABSOLUTE_URL)); + $urlElement = $domDocument->createElement('url'); $urlElement->appendChild($locationElement); - if ($sitemap->lastModifiedField) { - if (property_exists($entity, $sitemap->lastModifiedField)) { - $method = 'get'.ucfirst($sitemap->lastModifiedField); - if (method_exists($entity, $method)) { - $date = $entity->{$method}(); - if ($date instanceof \DateTime) { - $modifiedDate = $date->format('Y-m-d'); - } - if ($date instanceof \DateTimeImmutable) { - $modifiedDate = $date::createFromFormat('Y-m-d', $date->format('Y-m-d')); - $modifiedDate = $modifiedDate->format('Y-m-d'); - } + if ($sitemap->lastModifiedField && property_exists($entity, $sitemap->lastModifiedField)) { + $method = 'get'.ucfirst($sitemap->lastModifiedField); + if (method_exists($entity, $method)) { + $date = $entity->{$method}(); + if ($date instanceof DateTime) { + $modifiedDate = $date->format('Y-m-d'); } - if ($modifiedDate) { - $lastMod = $sitemapDom->createElement('lastmod', $modifiedDate); - $urlElement->appendChild($lastMod); + if ($date instanceof DateTimeImmutable) { + $modifiedDate = $date->format('Y-m-d'); } } + + if ($modifiedDate) { + $lastMod = $domDocument->createElement('lastmod', $modifiedDate); + $urlElement->appendChild($lastMod); + } } - $this->createSitemapFile($fileName, $urlElement->textContent, ''); + $this->createSitemapFile($fileName, $urlElement->textContent); $rootElement->appendChild($urlElement); } - $sitemapDom->save($this->publicDir.'sitemaps/'.$fileName.'.xml'); - if (null !== $request) { - $this->addXmlToSitemap($request->getSchemeAndHttpHost(). '/sitemaps/'.$fileName .'.xml'); + $domDocument->save($this->publicDir.'sitemaps/'.$fileName.'.xml'); + + if ($request instanceof Request) { + $this->addXmlToSitemap($request->getSchemeAndHttpHost().'/sitemaps/'.$fileName.'.xml'); } else { - $this->addXmlToSitemap($baseUrl."/sitemaps/$fileName.xml"); + $this->addXmlToSitemap($baseUrl.sprintf('/sitemaps/%s.xml', $fileName)); + } + } + + /** + * @param array $routes + * + * @throws DOMException + */ + private function addRoutesToXml(array $routes, ?string $baseUrl = null): void + { + $filename = $this->publicDir.'sitemaps/default.xml'; + $request = $this->requestStack->getCurrentRequest(); + $domDocument = new DOMDocument('1.0', 'UTF-8'); + $domDocument->formatOutput = true; + + $rootElement = $domDocument->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset'); + $domDocument->appendChild($rootElement); + foreach ($routes as $route) { + $routeName = $route->getName(); + if (null === $routeName) { + continue; + } + + $locationElement = $domDocument->createElement('loc', $this->urlGenerator->generate($routeName, [], UrlGeneratorInterface::ABSOLUTE_URL)); + $urlElement = $domDocument->createElement('url'); + $urlElement->appendChild($locationElement); + $rootElement->appendChild($urlElement); + $domDocument->appendChild($rootElement); + } + + $domDocument->save($this->publicDir.'sitemaps/default.xml'); + if ($request instanceof Request) { + $this->addXmlToSitemap($request->getSchemeAndHttpHost().'/sitemaps/'.basename($filename)); + } else { + $this->addXmlToSitemap($baseUrl.'/sitemaps/'.basename($filename)); } } private function addXmlToSitemap(string $xmlPath): void { - $sitemap = new DOMDocument(); - $sitemap->formatOutput = true; + $domDocument = new DOMDocument(); + $domDocument->formatOutput = true; - $sitemap->load($this->publicDir . 'sitemap.xml'); + $domDocument->load($this->publicDir.'sitemap.xml'); - $root = $sitemap->getElementsByTagName('sitemapindex'); + $domNodeList = $domDocument->getElementsByTagName('sitemapindex'); - $xpath = new DOMXPath($sitemap); - $xpath->registerNamespace('sm', 'http://www.sitemaps.org/schemas/sitemap/0.9'); - $nodes = $xpath->query("//sm:sitemap/sm:loc[text()='$xmlPath']"); + $domxPath = new DOMXPath($domDocument); + $domxPath->registerNamespace('sm', 'http://www.sitemaps.org/schemas/sitemap/0.9'); - $now = new \DateTimeImmutable(); + $nodes = $domxPath->query(sprintf("//sm:sitemap/sm:loc[text()='%s']", $xmlPath)); + + if (false === $nodes) { + return; + } - if ($nodes->length === 0) { - $location = $sitemap->createElement(localName: 'loc', value: $xmlPath); - $sitemapRoot = $sitemap->createElement(localName: 'sitemap'); - $root->item(0)->appendChild($sitemapRoot); - $lastMod = $sitemap->createElement('lastmod',$now->format('Y-m-d')); + $now = new DateTimeImmutable(); + + if (0 === $nodes->length) { + $location = $domDocument->createElement(localName: 'loc', value: $xmlPath); + $sitemapRoot = $domDocument->createElement(localName: 'sitemap'); + $firstItem = $domNodeList->item(0); + if (null === $firstItem) { + return; + } + + $firstItem->appendChild($sitemapRoot); + $lastMod = $domDocument->createElement('lastmod', $now->format('Y-m-d')); $sitemapRoot->appendChild($location); $sitemapRoot->appendChild($lastMod); - $nodes = $xpath->query("//sm:sitemap/sm:loc[text()='$xmlPath']"); + $nodes = $domxPath->query(sprintf("//sm:sitemap/sm:loc[text()='%s']", $xmlPath)); + if (false === $nodes) { + return; + } } foreach ($nodes as $node) { + if (!$node instanceof DOMElement) { + continue; + } + $sitemapNode = $node->parentNode; - $locNode = $node->nextSibling; + if (null === $sitemapNode) { + continue; + } + $lastmod = null; foreach ($sitemapNode->childNodes as $child) { - if ($child->nodeType === XML_ELEMENT_NODE && $child->localName === 'lastmod') { + if (\XML_ELEMENT_NODE === $child->nodeType && 'lastmod' === $child->localName) { $lastmod = $child; break; } @@ -260,28 +355,25 @@ private function addXmlToSitemap(string $xmlPath): void if ($lastmod) { $lastmod->nodeValue = $now->format('Y-m-d'); } else { - $lastmod = $sitemap->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'lastmod', $now->format('Y-m-d')); - if ($locNode) { - $sitemapNode->appendChild($lastmod); - } else { - $sitemapNode->appendChild($lastmod); - } + $lastmod = $domDocument->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'lastmod', $now->format('Y-m-d')); + $sitemapNode->appendChild($lastmod); } } - - $sitemap->save($this->publicDir.'sitemap.xml'); + + $domDocument->save($this->publicDir.'sitemap.xml'); } - private function createSitemapFile(string $filename, ?string $name = null, ?string $child = null): void + private function createSitemapFile(string $filename, ?string $name = null): void { - if (!file_exists($this->publicDir . $filename)) { + if (!file_exists($this->publicDir.$filename)) { try { - $sitemap = new \DomDocument('1.0', 'UTF-8'); - $sitemap->formatOutput = true; - $ns = $sitemap->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', $name); - $sitemap->appendChild($ns); - $sitemap->save($filename.'.xml'); - } catch (\Exception $exception) { + $domDocument = new DOMDocument('1.0', 'UTF-8'); + $domDocument->formatOutput = true; + $elementName = $name ?? 'urlset'; + $ns = $domDocument->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', $elementName); + $domDocument->appendChild($ns); + $domDocument->save($filename.'.xml'); + } catch (Exception $exception) { $this->logger->error($exception->getMessage()); } } @@ -289,16 +381,16 @@ private function createSitemapFile(string $filename, ?string $name = null, ?stri private function createIndexSitemapFile(): void { - if (!file_exists($this->publicDir . self::SITEMAP_XML)) { + if (!file_exists($this->publicDir.self::SITEMAP_XML)) { try { - $sitemap = new \DomDocument('1.0', 'UTF-8'); - $sitemap->formatOutput = true; - $ns = $sitemap->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'sitemapindex'); - $sitemap->appendChild($ns); - $sitemap->save($this->publicDir.self::SITEMAP_XML); - } catch (\Exception $exception) { + $domDocument = new DOMDocument('1.0', 'UTF-8'); + $domDocument->formatOutput = true; + $ns = $domDocument->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'sitemapindex'); + $domDocument->appendChild($ns); + $domDocument->save($this->publicDir.self::SITEMAP_XML); + } catch (Exception $exception) { $this->logger->error($exception->getMessage()); } } } -} \ No newline at end of file +} diff --git a/src/Sitemap/SitemapInterface.php b/src/Sitemap/SitemapInterface.php index d22bddd..b0c6d3e 100644 --- a/src/Sitemap/SitemapInterface.php +++ b/src/Sitemap/SitemapInterface.php @@ -1,4 +1,7 @@ $attributes - * @return void - * @throws \DOMException + * + * @throws DOMException */ public function generateDynamicSitemap(array $attributes, ?string $baseUrl = null): void; -} \ No newline at end of file +} diff --git a/src/Twig/Extensions/BreadcrumbExtension.php b/src/Twig/Extensions/BreadcrumbExtension.php index 8e6b278..4cf9a8a 100644 --- a/src/Twig/Extensions/BreadcrumbExtension.php +++ b/src/Twig/Extensions/BreadcrumbExtension.php @@ -1,4 +1,7 @@ true, 'is_safe' => ['html']]), - ]; - } - /** * @throws SyntaxError * @throws RuntimeError * @throws LoaderError */ + #[AsTwigFunction('seo_breadcrumb', isSafe: ['html'])] public function renderBreadcrumb(): string { - /** @var $item[] $items */ + /** @var array $items */ $items = $this->breadcrumbManager->getItems(); - return $this->twig->render('@Seo/breadcrumb.html.twig', [ + return $this->twigEnvironment->render('@Seo/breadcrumb.html.twig', [ 'breadcrumb' => $items, 'options' => $this->breadcrumbManager->getOptions(), ]); } -} \ No newline at end of file +} diff --git a/src/Twig/Extensions/MetaTagsExtension.php b/src/Twig/Extensions/MetaTagsExtension.php index 14e92fd..4623e43 100644 --- a/src/Twig/Extensions/MetaTagsExtension.php +++ b/src/Twig/Extensions/MetaTagsExtension.php @@ -1,4 +1,7 @@ ['html']]), - new TwigFunction('lang_head_value', [$this, 'renderHeadLang'], ['is_safe' => ['html']]), - ]; + private MetaTagsManagerInterface $metaTagsManager + ) { } - /** - * @param string $lang - * @return string - */ + #[AsTwigFunction('lang_head_value', isSafe: ['html'])] public function renderHeadLang(string $lang): string { return 'lang="'.$lang.'"'; } - /** - * @param string|null $title - * @param string|null $description - * @param array|null $keywords - * @param string|null $subject - * @param string|null $charset - * @param array|null $robots - * @param string|null $canonical - * @param string|null $copyright - * @param string|null $viewport - * @param string|null $author - * @param string|null $contentType - * @param bool $xuaCompatible - * @param array|null $customMetaTags - * @return string + * @param array|null $keywords + * @param array|null $robots + * @param array|null $customMetaTags */ + #[AsTwigFunction('meta_tags', isSafe: ['html'])] public function renderMetaTags( ?string $title = '', ?string $description = '', @@ -64,103 +49,111 @@ public function renderMetaTags( ?array $robots = [], ?string $canonical = '', ?string $copyright = '', - ?string $viewport = "", + ?string $viewport = '', ?string $author = '', ?string $contentType = '', bool $xuaCompatible = false, ?array $customMetaTags = [] - ): string - { - $seo = $this->metaTags->getSeoMeta(); - $this->metaTags->setTitle($title ?: $seo->getTitle()) - ->setDescription($description ?: $seo->getDescription()) - ->setKeywords($keywords ?: $seo->getKeywords()) - ->setSubject($subject ?: $seo->getSubject()) - ->setCharacterEncoding($charset ?: $seo->getCharset()) - ->setRobots($robots ?: $seo->getRobots()) - ->setCanonical($canonical ?: $seo->getCanonical()) - ->setCopyright($copyright ?: $seo->getCopyright()) - ->setViewport($viewport ?: $seo->getViewport()) - ->setAuthor($author ?: $seo->getAuthor()) - ->setContentType($contentType ?: $seo->getContentType()); + ): string { + $seoMeta = $this->metaTagsManager->getSeoMeta(); + $this->metaTagsManager->setTitle($title ?: $seoMeta->getTitle()) + ->setDescription($description ?: $seoMeta->getDescription()) + ->setKeywords($keywords ?: $seoMeta->getKeywords()) + ->setSubject($subject ?: $seoMeta->getSubject()) + ->setCharacterEncoding($charset ?: $seoMeta->getCharset()) + ->setRobots($robots ?: $seoMeta->getRobots()) + ->setCanonical($canonical ?: $seoMeta->getCanonical()) + ->setCopyright($copyright ?: $seoMeta->getCopyright()) + ->setViewport($viewport ?: $seoMeta->getViewport()) + ->setAuthor($author ?: $seoMeta->getAuthor()) + ->setContentType($contentType ?: $seoMeta->getContentType()); if ($xuaCompatible) { - $this->metaTags->setXUACompatible(); + $this->metaTagsManager->setXUACompatible(); } if (null !== $customMetaTags && [] !== $customMetaTags) { foreach ($customMetaTags as $name => $content) { - $this->metaTags->setCustomMetaTag($name, $content); + if (is_string($content)) { + $this->metaTagsManager->setCustomMetaTag($name, $content); + } } } return $this->renderTags(); } - /** - * @return string - */ private function renderTags(): string { $metaTags = ''; - $seoMeta = $this->metaTags->seoMeta; + $seoMeta = $this->metaTagsManager->getSeoMeta(); - if (null !== $seoMeta->getCharset() && '' !== $seoMeta->getCharset()) { - $metaTags .= sprintf('', $seoMeta->getCharset()); + $charset = $seoMeta->getCharset(); + if ('' !== $charset) { + $metaTags .= sprintf('', $charset); } - if (null !== $seoMeta->getTitle() && '' !== $seoMeta->getTitle()) { - $metaTags .= sprintf('%s', $seoMeta->getTitle()); + $title = $seoMeta->getTitle(); + if ('' !== $title) { + $metaTags .= sprintf('%s', $title); } - if (null !== $seoMeta->getDescription() && '' !== $seoMeta->getDescription()) { - $metaTags .= sprintf('', $seoMeta->getDescription()); + $description = $seoMeta->getDescription(); + if ('' !== $description) { + $metaTags .= sprintf('', $description); } - if (null !== $seoMeta->getKeywords() && [] !== $seoMeta->getKeywords()) { - $metaTags .= sprintf('', implode(', ', $seoMeta->getKeywords())); + $keywords = $seoMeta->getKeywords(); + if ([] !== $keywords) { + $metaTags .= sprintf('', implode(', ', $keywords)); } - if (null !== $seoMeta->getCanonical() && '' !== $seoMeta->getCanonical()) { - $metaTags .= sprintf('', $seoMeta->getCanonical()); + $canonical = $seoMeta->getCanonical(); + if ('' !== $canonical) { + $metaTags .= sprintf('', $canonical); } - if (null !== $seoMeta->getAuthor() && '' !== $seoMeta->getAuthor()) { - $metaTags .= sprintf('', $seoMeta->getAuthor()); + $author = $seoMeta->getAuthor(); + if ('' !== $author) { + $metaTags .= sprintf('', $author); } - if (null !== $seoMeta->getRobots() && [] !== $seoMeta->getRobots()) { - $metaTags .= sprintf('', implode(', ', $seoMeta->getRobots())); + $robots = $seoMeta->getRobots(); + if ([] !== $robots) { + $metaTags .= sprintf('', implode(', ', $robots)); } - if (null !== $seoMeta->getViewport() && '' !== $seoMeta->getViewport()) { - $metaTags .= sprintf('', $seoMeta->getViewport()); + $viewport = $seoMeta->getViewport(); + if ('' !== $viewport) { + $metaTags .= sprintf('', $viewport); } - if (null !== $seoMeta->getContentSecurityPolicy() && '' !== $seoMeta->getContentSecurityPolicy()) { - $metaTags .= sprintf('', $seoMeta->getContentSecurityPolicy()); + $contentSecurityPolicy = $seoMeta->getContentSecurityPolicy(); + if ('' !== $contentSecurityPolicy) { + $metaTags .= sprintf('', $contentSecurityPolicy); } - if (null !== $seoMeta->getContentType() && '' !== $seoMeta->getContentType()) { - $metaTags .= sprintf('', $seoMeta->getContentType()); + $contentType = $seoMeta->getContentType(); + if ('' !== $contentType) { + $metaTags .= sprintf('', $contentType); } // Render additional custom meta tags - $tags = $this->metaTags->getMetaTags(); + $tags = $this->metaTagsManager->getMetaTags(); foreach ($tags as $name => $value) { if (is_array($value)) { // Handle structured tags like default-style, x-ua-compatible, rel - if (isset($value['http-equiv'], $value['value']) && '' !== $value['http-equiv'] && '' !== $value['value']) { + if (isset($value['http-equiv'], $value['value']) && is_string($value['http-equiv']) && is_string($value['value']) && '' !== $value['http-equiv'] && '' !== $value['value']) { $metaTags .= sprintf('', $value['http-equiv'], $value['value']); - } elseif (isset($value['rel'], $value['href']) && '' !== $value['rel'] && '' !== $value['href']) { - if (isset($value['media']) && '' !== $value['media']) { + } elseif (isset($value['rel'], $value['href']) && is_string($value['rel']) && is_string($value['href']) && '' !== $value['rel'] && '' !== $value['href']) { + if (isset($value['media']) && is_string($value['media']) && '' !== $value['media']) { $metaTags .= sprintf('', $value['rel'], $value['href'], $value['media']); } else { $metaTags .= sprintf('', $value['rel'], $value['href']); } } - } elseif ('charset' !== $name) { + } elseif ('charset' !== $name && is_string($value)) { // Handle custom meta tags (skip charset as it's already handled above) $metaTags .= sprintf('', $name, $value); } @@ -168,4 +161,4 @@ private function renderTags(): string return $metaTags; } -} \ No newline at end of file +} diff --git a/src/Twig/Extensions/OpenGraphExtension.php b/src/Twig/Extensions/OpenGraphExtension.php index 0cc65a2..35be1c5 100644 --- a/src/Twig/Extensions/OpenGraphExtension.php +++ b/src/Twig/Extensions/OpenGraphExtension.php @@ -1,4 +1,7 @@ ['html']]), - new TwigFunction('og_image', [$this, 'renderOgImage'], ['is_safe' => ['html']]), - new TwigFunction('og_video', [$this, 'renderOgVideo'], ['is_safe' => ['html']]), - new TwigFunction('og_article', [$this, 'renderOgArticle'], ['is_safe' => ['html']]), - ]; + private ParameterBagInterface $parameterBag + ) { } + #[AsTwigFunction('open_graph', isSafe: ['html'])] public function renderOpenGraph( ?string $title = '', ?string $description = '', @@ -51,23 +52,24 @@ public function renderOpenGraph( ?string $alternateLocale = '', ?string $audio = '', ?string $video = '', - ): string - { - $og = $this->openGraphManager->getOpenGraph(); - $og->setTitle($title ?: $og->getTitle()) - ->setDescription($description ?: $og->getDescription()) - ->setSiteName($siteName ?: $og->getSiteName()) - ->setImageUrl($imageUrl ?: $og->getImageUrl()) - ->setImageAlt($imageAlt ?: $og->getImageAlt()) - ->setUrl($url ?: $og->getUrl()) - ->setType($type ?: $og->getType()) - ->setLocale($locale ?: $og->getLocale()) - ->setAlternateLocale($alternateLocale ?: $og->getAlternateLocale()) - ->setAudio($audio ?: $og->getAudio()) - ->setVideo($video ?: $og->getVideo()); + ): string { + $openGraph = $this->openGraphManager->getOpenGraph(); + $openGraph->setTitle($title ?: $openGraph->getTitle()) + ->setDescription($description ?: $openGraph->getDescription()) + ->setSiteName($siteName ?: $openGraph->getSiteName()) + ->setImageUrl($imageUrl ?: $openGraph->getImageUrl()) + ->setImageAlt($imageAlt ?: $openGraph->getImageAlt()) + ->setUrl($url ?: $openGraph->getUrl()) + ->setType($type ?: $openGraph->getType()) + ->setLocale($locale ?: $openGraph->getLocale()) + ->setAlternateLocale($alternateLocale ?: $openGraph->getAlternateLocale()) + ->setAudio($audio ?: $openGraph->getAudio()) + ->setVideo($video ?: $openGraph->getVideo()); + return $this->getOG(); } + #[AsTwigFunction('og_image', isSafe: ['html'])] public function renderOgImage( ?string $url = '', ?string $secureUrl = '', @@ -75,22 +77,22 @@ public function renderOgImage( ?string $type = '', ?string $width = '', ?string $height = '', - ): string - { - $og = $this->ogImageManager->getImage(); - - $og - ->setUrl($url ?: $og->getUrl()) - ->setSecureUrl($secureUrl ?: $og->getSecureUrl()) - ->setAlt($alt ?: $og->getAlt()) - ->setType($type ?: $og->getType()) - ->setWidth($width ?: $og->getWidth()) - ->setHeight($height ?: $og->getHeight()) + ): string { + $image = $this->ogImageManager->getImage(); + + $image + ->setUrl($url ?: $image->getUrl()) + ->setSecureUrl($secureUrl ?: $image->getSecureUrl()) + ->setAlt($alt ?: $image->getAlt()) + ->setType($type ?: $image->getType()) + ->setWidth($width ?: $image->getWidth()) + ->setHeight($height ?: $image->getHeight()) ; return $this->getOgImage(); } + #[AsTwigFunction('og_video', isSafe: ['html'])] public function renderOgVideo( ?string $url = '', ?string $secureUrl = '', @@ -98,45 +100,44 @@ public function renderOgVideo( ?string $type = '', ?string $width = '', ?string $height = '', - ): string - { - $og = $this->ogVideoManager->getVideo(); - - $og - ->setUrl($url ?: $og->getUrl()) - ->setSecureUrl($secureUrl ?: $og->getSecureUrl()) - ->setType($type ?: $og->getType()) - ->setWidth($width ?: $og->getWidth()) - ->setHeight($height ?: $og->getHeight()) + ): string { + $video = $this->ogVideoManager->getVideo(); + + $video + ->setUrl($url ?: $video->getUrl()) + ->setSecureUrl($secureUrl ?: $video->getSecureUrl()) + ->setType($type ?: $video->getType()) + ->setWidth($width ?: $video->getWidth()) + ->setHeight($height ?: $video->getHeight()) ; return $this->getOgVideo(); } + /** + * @param array|null $tags + */ + #[AsTwigFunction('og_article', isSafe: ['html'])] public function renderOgArticle( - ?\DateTime $publishedTime = null, - ?\DateTime $modifiedTime = null, + ?DateTime $publishedTime = null, + ?DateTime $modifiedTime = null, ?string $author = '', ?string $section = '', ?array $tags = [] - ): string - { - $og = $this->ogArticleManager->getArticle(); - - $og - ->setPublishedTime($publishedTime ?: $og->getPublishedTime()) - ->setModifiedTime($modifiedTime ?: $og->getModifiedTime()) - ->setAuthor($author ?: $og->getAuthor()) - ->setSection($section ?: $og->getSection()) - ->setTags($tags ?: $og->getTags()) + ): string { + $article = $this->ogArticleManager->getArticle(); + + $article + ->setPublishedTime($publishedTime ?: $article->getPublishedTime()) + ->setModifiedTime($modifiedTime ?: $article->getModifiedTime()) + ->setAuthor($author ?: $article->getAuthor()) + ->setSection($section ?: $article->getSection()) + ->setTags($tags ?: $article->getTags()) ; return $this->getOgArticle(); } - /** - * @return string - */ private function getOG(): string { $openGraphString = ''; @@ -150,56 +151,77 @@ private function getOG(): string if ($hasDefaultConfig) { $defaults = $this->parameterBag->get('seo.open_graph'); - if ((null === $openGraph->getTitle() || '' === $openGraph->getTitle()) && array_key_exists('title', $defaults)) { - $openGraph->setTitle($defaults['title']); + assert(is_array($defaults)); + if ('' === $openGraph->getTitle() && array_key_exists('title', $defaults)) { + $title = $defaults['title']; + assert(is_string($title)); + $openGraph->setTitle($title); } - if ((null === $openGraph->getDescription() || '' === $openGraph->getDescription()) && array_key_exists('description', $defaults)) { - $openGraph->setDescription($defaults['description']); + if ('' === $openGraph->getDescription() && array_key_exists('description', $defaults)) { + $description = $defaults['description']; + assert(is_string($description)); + $openGraph->setDescription($description); } - if ((null === $openGraph->getSiteName() || '' === $openGraph->getSiteName()) && array_key_exists('sitename', $defaults)) { - $openGraph->setSiteName($defaults['sitename']); + if ('' === $openGraph->getSiteName() && array_key_exists('sitename', $defaults)) { + $sitename = $defaults['sitename']; + if (is_string($sitename)) { + $openGraph->setSiteName($sitename); + } } - if ((null === $openGraph->getUrl() || '' === $openGraph->getUrl()) && array_key_exists('url', $defaults)) { - $openGraph->setUrl($defaults['url']); + if ('' === $openGraph->getUrl() && array_key_exists('url', $defaults)) { + $url = $defaults['url']; + if (is_string($url)) { + $openGraph->setUrl($url); + } } - if ((null === $openGraph->getType() || '' === $openGraph->getType()) && array_key_exists('type', $defaults)) { - $openGraph->setType($defaults['type']); + if ('' === $openGraph->getType() && array_key_exists('type', $defaults)) { + $type = $defaults['type']; + if (is_string($type)) { + $openGraph->setType($type); + } } } - if (null !== $openGraph->getTitle() && '' !== $openGraph->getTitle()) { - $openGraphString .= sprintf('', strip_tags($openGraph->getTitle())); + if ('' !== $openGraph->getTitle()) { + $openGraphString .= sprintf('', strip_tags($openGraph->getTitle())); } - if (null !== $openGraph->getDescription() && '' !== $openGraph->getDescription()) { + if ('' !== $openGraph->getDescription()) { $openGraphString .= sprintf('', strip_tags($openGraph->getDescription())); } - if (null !== $openGraph->getImageUrl() && '' !== $openGraph->getImageUrl()) { + if ('' !== $openGraph->getImageUrl()) { $openGraphString .= sprintf('', strip_tags($openGraph->getImageUrl())); } - if (null !== $openGraph->getUrl() && '' !== $openGraph->getUrl()) { + if ('' !== $openGraph->getUrl()) { $openGraphString .= sprintf('', strip_tags($openGraph->getUrl())); } - if (null !== $openGraph->getType() && '' !== $openGraph->getType()) { - $openGraphString .= sprintf('', strip_tags($openGraph->getType())); + if ('' !== $openGraph->getType()) { + $openGraphString .= sprintf('', strip_tags($openGraph->getType())); } - if (null !== $openGraph->getSiteName() && '' !== $openGraph->getSiteName()) { + if ('' !== $openGraph->getSiteName()) { $openGraphString .= sprintf('', $openGraph->getSiteName()); } if ($openGraph->getStructuredProperties()) { - foreach ($openGraph->getStructuredProperties() as $property => $value) { - $openGraphString .= sprintf('', $value[0]['type'], $value[0]['content']); - foreach ($value as $index => $structuredProperty) { - $openGraphString .= sprintf('', $structuredProperty['type'], $structuredProperty['property'], $structuredProperty['content']); + foreach ($openGraph->getStructuredProperties() as $value) { + if (is_array($value) && isset($value[0]) && is_array($value[0]) && isset($value[0]['type'], $value[0]['content']) && is_string($value[0]['type']) && is_string($value[0]['content'])) { + $openGraphString .= sprintf('', $value[0]['type'], $value[0]['content']); + } + + if (is_array($value)) { + foreach ($value as $structuredProperty) { + if (is_array($structuredProperty) && isset($structuredProperty['type'], $structuredProperty['property'], $structuredProperty['content']) && is_string($structuredProperty['type']) && is_string($structuredProperty['property']) && is_string($structuredProperty['content'])) { + $openGraphString .= sprintf('', $structuredProperty['type'], $structuredProperty['property'], $structuredProperty['content']); + } + } } } } @@ -208,13 +230,15 @@ private function getOG(): string $contents = $openGraph->getMusicProperties(); foreach ($contents as $content) { - $openGraphString .= sprintf('', $content['property'], $content['content']); + if (is_array($content) && isset($content['property'], $content['content']) && is_string($content['property']) && is_string($content['content'])) { + $openGraphString .= sprintf('', $content['property'], $content['content']); + } } } - if ([] !== $openGraph->getTwitterCardProperties()) { - foreach ($openGraph->getTwitterCardProperties() as $twitterCardProperty) { - foreach ($twitterCardProperty as $name => $content) { + foreach ($openGraph->getTwitterCardProperties() as $twitterCardProperty) { + foreach ($twitterCardProperty as $name => $content) { + if (is_string($content)) { $openGraphString .= sprintf('', $name, $content); } } @@ -229,27 +253,27 @@ private function getOgImage(): string $ogString = ''; - if (null !== $ogImage->getUrl() && '' !== $ogImage->getUrl()) { + if ('' !== $ogImage->getUrl()) { $ogString .= sprintf('', $ogImage->getUrl()); } - if (null !== $ogImage->getSecureUrl() && '' !== $ogImage->getSecureUrl()) { + if ('' !== $ogImage->getSecureUrl()) { $ogString .= sprintf('', $ogImage->getSecureUrl()); } - if (null !== $ogImage->getType() && '' !== $ogImage->getType()) { + if ('' !== $ogImage->getType()) { $ogString .= sprintf('', $ogImage->getType()); } - if (null !== $ogImage->getWidth() && '' !== $ogImage->getWidth()) { + if ('' !== $ogImage->getWidth()) { $ogString .= sprintf('', $ogImage->getWidth()); } - if (null !== $ogImage->getHeight() && '' !== $ogImage->getHeight()) { + if ('' !== $ogImage->getHeight()) { $ogString .= sprintf('', $ogImage->getHeight()); } - if (null !== $ogImage->getAlt() && '' !== $ogImage->getAlt()) { + if ('' !== $ogImage->getAlt()) { $ogString .= sprintf('', $ogImage->getAlt()); } @@ -262,23 +286,23 @@ private function getOgVideo(): string $ogString = ''; - if (null !== $ogVideo->getUrl() && '' !== $ogVideo->getUrl()) { + if ('' !== $ogVideo->getUrl()) { $ogString .= sprintf('', $ogVideo->getUrl()); } - if (null !== $ogVideo->getSecureUrl() && '' !== $ogVideo->getSecureUrl()) { + if ('' !== $ogVideo->getSecureUrl()) { $ogString .= sprintf('', $ogVideo->getSecureUrl()); } - if (null !== $ogVideo->getType() && '' !== $ogVideo->getType()) { + if ('' !== $ogVideo->getType()) { $ogString .= sprintf('', $ogVideo->getType()); } - if (null !== $ogVideo->getWidth() && '' !== $ogVideo->getWidth()) { + if ('' !== $ogVideo->getWidth()) { $ogString .= sprintf('', $ogVideo->getWidth()); } - if (null !== $ogVideo->getHeight() && '' !== $ogVideo->getHeight()) { + if ('' !== $ogVideo->getHeight()) { $ogString .= sprintf('', $ogVideo->getHeight()); } @@ -291,28 +315,26 @@ private function getOgArticle(): string $articleString = ''; - if (null !== $article->getPublishedTime()) { + if ($article->getPublishedTime() instanceof DateTime) { $articleString .= sprintf('', $article->getPublishedTime()->format('Y-md-m-Y-H-i-s')); } - if (null !== $article->getModifiedTime()) { + if ($article->getModifiedTime() instanceof DateTime) { $articleString .= sprintf('', $article->getModifiedTime()->format('Y-m-d-m-Y-H-i-s')); } - if (null !== $article->getAuthor() && '' !== $article->getAuthor()) { + if ('' !== $article->getAuthor()) { $articleString .= sprintf('', $article->getAuthor()); } - if (null !== $article->getSection() && '' !== $article->getSection()) { + if ('' !== $article->getSection()) { $articleString .= sprintf('', $article->getSection()); } - if (null !== $article->getTags() && [] !== $article->getTags()) { - foreach ($article->getTags() as $tag) { - $articleString .= sprintf('', $tag); - } + foreach ($article->getTags() as $tag) { + $articleString .= sprintf('', $tag); } return $articleString; } -} \ No newline at end of file +} diff --git a/tests/Integration/Controller/MetaTagsControllerTest.php b/tests/Integration/Controller/MetaTagsControllerTest.php index de0eec1..9a3fd58 100644 --- a/tests/Integration/Controller/MetaTagsControllerTest.php +++ b/tests/Integration/Controller/MetaTagsControllerTest.php @@ -1,4 +1,7 @@ metaTagsManager->setTitle($title); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($title, $seoMeta->getTitle()); + $this->assertSame($title, $seoMeta->getTitle()); } public function testSetAndGetDescription(): void @@ -46,7 +52,7 @@ public function testSetAndGetDescription(): void $this->metaTagsManager->setDescription($description); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($description, $seoMeta->getDescription()); + $this->assertSame($description, $seoMeta->getDescription()); } public function testSetAndGetKeywords(): void @@ -55,7 +61,7 @@ public function testSetAndGetKeywords(): void $this->metaTagsManager->setKeywords($keywords); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($keywords, $seoMeta->getKeywords()); + $this->assertSame($keywords, $seoMeta->getKeywords()); } public function testSetAndGetSubject(): void @@ -64,7 +70,7 @@ public function testSetAndGetSubject(): void $this->metaTagsManager->setSubject($subject); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($subject, $seoMeta->getSubject()); + $this->assertSame($subject, $seoMeta->getSubject()); } public function testSetAndGetCopyright(): void @@ -73,7 +79,7 @@ public function testSetAndGetCopyright(): void $this->metaTagsManager->setCopyright($copyright); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($copyright, $seoMeta->getCopyright()); + $this->assertSame($copyright, $seoMeta->getCopyright()); } public function testSetAndGetRobots(): void @@ -82,7 +88,7 @@ public function testSetAndGetRobots(): void $this->metaTagsManager->setRobots($robots); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($robots, $seoMeta->getRobots()); + $this->assertSame($robots, $seoMeta->getRobots()); } public function testSetAndGetViewPort(): void @@ -91,7 +97,7 @@ public function testSetAndGetViewPort(): void $this->metaTagsManager->setViewPort($viewport); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($viewport, $seoMeta->getViewport()); + $this->assertSame($viewport, $seoMeta->getViewport()); } public function testSetAndGetCanonical(): void @@ -100,7 +106,7 @@ public function testSetAndGetCanonical(): void $this->metaTagsManager->setCanonical($canonical); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($canonical, $seoMeta->getCanonical()); + $this->assertSame($canonical, $seoMeta->getCanonical()); } public function testSetAndGetCharacterEncoding(): void @@ -109,7 +115,7 @@ public function testSetAndGetCharacterEncoding(): void $this->metaTagsManager->setCharacterEncoding($charset); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($charset, $seoMeta->getCharset()); + $this->assertSame($charset, $seoMeta->getCharset()); } public function testSetCharacterEncodingWithDefaultValue(): void @@ -117,7 +123,7 @@ public function testSetCharacterEncodingWithDefaultValue(): void $this->metaTagsManager->setCharacterEncoding(); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals('UTF-8', $seoMeta->getCharset()); + $this->assertSame('UTF-8', $seoMeta->getCharset()); } public function testSetAndGetAuthor(): void @@ -126,7 +132,7 @@ public function testSetAndGetAuthor(): void $this->metaTagsManager->setAuthor($author); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($author, $seoMeta->getAuthor()); + $this->assertSame($author, $seoMeta->getAuthor()); } public function testSetAndGetContentSecurityPolicy(): void @@ -135,7 +141,7 @@ public function testSetAndGetContentSecurityPolicy(): void $this->metaTagsManager->setContentSecurityPolicy($csp); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($csp, $seoMeta->getContentSecurityPolicy()); + $this->assertSame($csp, $seoMeta->getContentSecurityPolicy()); } public function testSetAndGetContentType(): void @@ -144,19 +150,19 @@ public function testSetAndGetContentType(): void $this->metaTagsManager->setContentType($contentType); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals($contentType, $seoMeta->getContentType()); + $this->assertSame($contentType, $seoMeta->getContentType()); } public function testFluentInterface(): void { - $result = $this->metaTagsManager + $metaTagsManager = $this->metaTagsManager ->setTitle('Test Title') ->setDescription('Test Description') ->setKeywords(['test', 'seo']) ->setAuthor('Test Author'); - $this->assertInstanceOf(MetaTagsManager::class, $result); - $this->assertSame($this->metaTagsManager, $result); + $this->assertInstanceOf(MetaTagsManager::class, $metaTagsManager); + $this->assertSame($this->metaTagsManager, $metaTagsManager); } public function testSetCustomMetaTag(): void @@ -189,8 +195,10 @@ public function testSetDefaultStyle(): void $metaTags = $this->metaTagsManager->getMetaTags(); $this->assertArrayHasKey('default-style', $metaTags); - $this->assertEquals('Default-Style', $metaTags['default-style']['http-equiv']); - $this->assertEquals($style, $metaTags['default-style']['value']); + $defaultStyle = $metaTags['default-style']; + assert(is_array($defaultStyle)); + $this->assertEquals('Default-Style', $defaultStyle['http-equiv']); + $this->assertEquals($style, $defaultStyle['value']); } public function testSetXUACompatible(): void @@ -199,8 +207,10 @@ public function testSetXUACompatible(): void $metaTags = $this->metaTagsManager->getMetaTags(); $this->assertArrayHasKey('x-ua-compatible', $metaTags); - $this->assertEquals('X-UA-Compatible', $metaTags['x-ua-compatible']['http-equiv']); - $this->assertEquals('IE=edge', $metaTags['x-ua-compatible']['value']); + $xuaCompatible = $metaTags['x-ua-compatible']; + assert(is_array($xuaCompatible)); + $this->assertEquals('X-UA-Compatible', $xuaCompatible['http-equiv']); + $this->assertEquals('IE=edge', $xuaCompatible['value']); } public function testSetAlternate(): void @@ -211,9 +221,11 @@ public function testSetAlternate(): void $metaTags = $this->metaTagsManager->getMetaTags(); $this->assertArrayHasKey('rel', $metaTags); - $this->assertEquals('canonical', $metaTags['rel']['rel']); - $this->assertEquals($href, $metaTags['rel']['href']); - $this->assertEquals($media, $metaTags['rel']['media']); + $rel = $metaTags['rel']; + assert(is_array($rel)); + $this->assertEquals('canonical', $rel['rel']); + $this->assertEquals($href, $rel['href']); + $this->assertEquals($media, $rel['media']); } public function testSetAlternateWithoutMedia(): void @@ -223,9 +235,11 @@ public function testSetAlternateWithoutMedia(): void $metaTags = $this->metaTagsManager->getMetaTags(); $this->assertArrayHasKey('rel', $metaTags); - $this->assertEquals('canonical', $metaTags['rel']['rel']); - $this->assertEquals($href, $metaTags['rel']['href']); - $this->assertEquals('', $metaTags['rel']['media']); + $rel = $metaTags['rel']; + assert(is_array($rel)); + $this->assertEquals('canonical', $rel['rel']); + $this->assertEquals($href, $rel['href']); + $this->assertEquals('', $rel['media']); } public function testGetMetaTagsReturnsArray(): void @@ -233,13 +247,12 @@ public function testGetMetaTagsReturnsArray(): void $this->metaTagsManager->setCustomMetaTag('test', 'value'); $metaTags = $this->metaTagsManager->getMetaTags(); - $this->assertIsArray($metaTags); + $this->assertNotEmpty($metaTags); } public function testGetMetaTagsReturnsEmptyArrayInitially(): void { $metaTags = $this->metaTagsManager->getMetaTags(); - $this->assertIsArray($metaTags); $this->assertEmpty($metaTags); } @@ -306,11 +319,11 @@ public function testComplexMetaTagsScenario(): void ->setCustomMetaTag('og:price:amount', '99.99'); $seoMeta = $this->metaTagsManager->getSeoMeta(); - $this->assertEquals('E-Commerce Product Page', $seoMeta->getTitle()); - $this->assertEquals('Buy the best products online with free shipping', $seoMeta->getDescription()); + $this->assertSame('E-Commerce Product Page', $seoMeta->getTitle()); + $this->assertSame('Buy the best products online with free shipping', $seoMeta->getDescription()); $this->assertCount(4, $seoMeta->getKeywords()); - $this->assertEquals('Shop Team', $seoMeta->getAuthor()); - $this->assertEquals(['index', 'follow'], $seoMeta->getRobots()); + $this->assertSame('Shop Team', $seoMeta->getAuthor()); + $this->assertSame(['index', 'follow'], $seoMeta->getRobots()); $metaTags = $this->metaTagsManager->getMetaTags(); $this->assertArrayHasKey('x-ua-compatible', $metaTags); @@ -318,4 +331,4 @@ public function testComplexMetaTagsScenario(): void $this->assertEquals('product', $metaTags['og:type']); $this->assertEquals('99.99', $metaTags['og:price:amount']); } -} \ No newline at end of file +} diff --git a/tests/Integration/Schema/BaseTypeTest.php b/tests/Integration/Schema/BaseTypeTest.php index c564ac2..b072ae3 100644 --- a/tests/Integration/Schema/BaseTypeTest.php +++ b/tests/Integration/Schema/BaseTypeTest.php @@ -1,4 +1,7 @@ baseType->getType(); - $this->assertEquals('Thing', $type); + $this->assertSame('Thing', $type); } public function testToStringReturnsFullClassName(): void { $className = (string) $this->baseType; - $this->assertEquals(Thing::class, $className); + $this->assertSame(Thing::class, $className); } public function testNameSetsProperty(): void @@ -82,10 +85,10 @@ public function testSetDescriptionSetsProperty(): void public function testSubjectOfSetsPropertyWithBaseType(): void { - $subject = new Person(); - $subject->name('Subject Person'); + $person = new Person(); + $person->name('Subject Person'); - $this->baseType->subjectOf($subject); + $this->baseType->subjectOf($person); $subjectProperty = $this->baseType->getProperty('subjectOf'); $this->assertIsArray($subjectProperty); @@ -98,17 +101,15 @@ public function testGetPropertiesReturnsArray(): void $this->baseType->name('Test')->id('123'); $properties = $this->baseType->getProperties(); - $this->assertIsArray($properties); $this->assertArrayHasKey('name', $properties); $this->assertArrayHasKey('id', $properties); } public function testGetPropertiesReturnsEmptyArrayInitially(): void { - $baseType = new Thing(); - $properties = $baseType->getProperties(); + $thing = new Thing(); + $properties = $thing->getProperties(); - $this->assertIsArray($properties); $this->assertEmpty($properties); } @@ -120,13 +121,13 @@ public function testGetPropertyReturnsNullForNonExistentProperty(): void public function testFluentInterface(): void { - $result = $this->baseType + $baseType = $this->baseType ->name('Test') ->id('123') ->url('https://example.com') ->inLanguage('en'); - $this->assertSame($this->baseType, $result); + $this->assertSame($this->baseType, $baseType); } public function testRenderReturnsJsonLdScript(): void @@ -151,9 +152,9 @@ public function testRenderIncludesProperties(): void $rendered = $this->baseType->render(); - $this->assertStringContainsString('Test Thing', $rendered); - $this->assertStringContainsString('test-123', $rendered); - $this->assertStringContainsString('https://example.com', $rendered); + $this->assertStringContainsString('Test Thing', (string) $rendered); + $this->assertStringContainsString('test-123', (string) $rendered); + $this->assertStringContainsString('https://example.com', (string) $rendered); } public function testRenderOutputsValidJson(): void @@ -161,7 +162,7 @@ public function testRenderOutputsValidJson(): void $this->baseType->name('Test Thing'); $rendered = $this->baseType->render(); - preg_match('/]*>(.*?)<\/script>/s', $rendered, $matches); + preg_match('/]*>(.*?)<\/script>/s', (string) $rendered, $matches); $json = $matches[1] ?? ''; $decoded = json_decode($json, true); @@ -211,7 +212,7 @@ public function testRenderWithNestedObject(): void $rendered = $this->baseType->render(); - $this->assertStringContainsString('Main Thing', $rendered); - $this->assertStringContainsString('Person', $rendered); + $this->assertStringContainsString('Main Thing', (string) $rendered); + $this->assertStringContainsString('Person', (string) $rendered); } } diff --git a/tests/Integration/Schema/CreativeWorkTest.php b/tests/Integration/Schema/CreativeWorkTest.php index 0a7234e..1739cca 100644 --- a/tests/Integration/Schema/CreativeWorkTest.php +++ b/tests/Integration/Schema/CreativeWorkTest.php @@ -1,4 +1,7 @@ assertEquals('CreativeWork', $this->creativeWork->getType()); + $this->assertSame('CreativeWork', $this->creativeWork->getType()); } public function testAbstractSetsProperty(): void @@ -106,10 +111,10 @@ public function testAlternativeHeadlineSetsProperty(): void public function testAuthorWithPerson(): void { - $author = new Person(); - $author->name('John Author'); + $person = new Person(); + $person->name('John Author'); - $this->creativeWork->author($author); + $this->creativeWork->author($person); $authorProperty = $this->creativeWork->getProperty('author'); $this->assertIsArray($authorProperty); @@ -136,10 +141,10 @@ public function testAwardSetsProperty(): void public function testCharacterSetsProperty(): void { - $character = new Person(); - $character->name('Main Character'); + $person = new Person(); + $person->name('Main Character'); - $this->creativeWork->character($character); + $this->creativeWork->character($person); $characterProperty = $this->creativeWork->getProperty('character'); $this->assertIsArray($characterProperty); @@ -154,10 +159,10 @@ public function testCitationWithString(): void public function testContributorSetsProperty(): void { - $contributor = new Person(); - $contributor->name('Contributor Name'); + $person = new Person(); + $person->name('Contributor Name'); - $this->creativeWork->contributor($contributor); + $this->creativeWork->contributor($person); $contributorProperty = $this->creativeWork->getProperty('contributor'); $this->assertIsArray($contributorProperty); @@ -166,10 +171,10 @@ public function testContributorSetsProperty(): void public function testCreatorSetsProperty(): void { - $creator = new Person(); - $creator->name('Content Creator'); + $person = new Person(); + $person->name('Content Creator'); - $this->creativeWork->creator($creator); + $this->creativeWork->creator($person); $creatorProperty = $this->creativeWork->getProperty('creator'); $this->assertIsArray($creatorProperty); @@ -190,10 +195,10 @@ public function testCountryOfOriginSetsProperty(): void public function testCopyrightHolderSetsProperty(): void { - $holder = new Organization(); - $holder->name('Copyright Holder Inc'); + $organization = new Organization(); + $organization->name('Copyright Holder Inc'); - $this->creativeWork->copyrightHolder($holder); + $this->creativeWork->copyrightHolder($organization); $holderProperty = $this->creativeWork->getProperty('copyrightHolder'); $this->assertIsArray($holderProperty); @@ -226,10 +231,10 @@ public function testKeywordsSetsProperty(): void public function testMaintainerSetsProperty(): void { - $maintainer = new Person(); - $maintainer->name('Content Maintainer'); + $person = new Person(); + $person->name('Content Maintainer'); - $this->creativeWork->maintainer($maintainer); + $this->creativeWork->maintainer($person); $maintainerProperty = $this->creativeWork->getProperty('maintainer'); $this->assertIsArray($maintainerProperty); @@ -253,10 +258,10 @@ public function testCreditTextSetsProperty(): void public function testEditorSetsProperty(): void { - $editor = new Person(); - $editor->name('Editor Name'); + $person = new Person(); + $person->name('Editor Name'); - $this->creativeWork->editor($editor); + $this->creativeWork->editor($person); $editorProperty = $this->creativeWork->getProperty('editor'); $this->assertIsArray($editorProperty); @@ -265,10 +270,10 @@ public function testEditorSetsProperty(): void public function testFunderSetsProperty(): void { - $funder = new Organization(); - $funder->name('Research Foundation'); + $organization = new Organization(); + $organization->name('Research Foundation'); - $this->creativeWork->funder($funder); + $this->creativeWork->funder($organization); $funderProperty = $this->creativeWork->getProperty('funder'); $this->assertIsArray($funderProperty); @@ -277,10 +282,10 @@ public function testFunderSetsProperty(): void public function testPublisherSetsProperty(): void { - $publisher = new Organization(); - $publisher->name('Publishing Company'); + $organization = new Organization(); + $organization->name('Publishing Company'); - $this->creativeWork->publisher($publisher); + $this->creativeWork->publisher($organization); $publisherProperty = $this->creativeWork->getProperty('publisher'); $this->assertIsArray($publisherProperty); @@ -289,10 +294,10 @@ public function testPublisherSetsProperty(): void public function testSponsorSetsProperty(): void { - $sponsor = new Organization(); - $sponsor->name('Sponsor Corp'); + $organization = new Organization(); + $organization->name('Sponsor Corp'); - $this->creativeWork->sponsor($sponsor); + $this->creativeWork->sponsor($organization); $sponsorProperty = $this->creativeWork->getProperty('sponsor'); $this->assertIsArray($sponsorProperty); @@ -319,7 +324,7 @@ public function testVersionSetsProperty(): void public function testDateCreatedFormatsCorrectly(): void { - $date = new \DateTime('2025-01-15 10:00:00'); + $date = new DateTime('2025-01-15 10:00:00'); $this->creativeWork->dateCreated($date); $dateCreated = $this->creativeWork->getProperty('dateCreated'); @@ -329,10 +334,10 @@ public function testDateCreatedFormatsCorrectly(): void public function testDateCreatedWithTimezone(): void { - $date = new \DateTime('2025-01-15 10:00:00', new \DateTimeZone('UTC')); - $timezone = new \DateTimeZone('Europe/Berlin'); + $date = new DateTime('2025-01-15 10:00:00', new DateTimeZone('UTC')); + $dateTimeZone = new DateTimeZone('Europe/Berlin'); - $this->creativeWork->dateCreated($date, $timezone); + $this->creativeWork->dateCreated($date, $dateTimeZone); $dateCreated = $this->creativeWork->getProperty('dateCreated'); $this->assertIsString($dateCreated); @@ -340,7 +345,7 @@ public function testDateCreatedWithTimezone(): void public function testDateModifiedFormatsCorrectly(): void { - $date = new \DateTime('2025-02-20 14:30:00'); + $date = new DateTime('2025-02-20 14:30:00'); $this->creativeWork->dateModified($date); $dateModified = $this->creativeWork->getProperty('dateModified'); @@ -350,7 +355,7 @@ public function testDateModifiedFormatsCorrectly(): void public function testDatePublishedFormatsCorrectly(): void { - $date = new \DateTime('2025-03-10 09:00:00'); + $date = new DateTime('2025-03-10 09:00:00'); $this->creativeWork->datePublished($date); $datePublished = $this->creativeWork->getProperty('datePublished'); @@ -360,31 +365,31 @@ public function testDatePublishedFormatsCorrectly(): void public function testFluentInterface(): void { - $result = $this->creativeWork + $creativeWork = $this->creativeWork ->headline('Test Headline') ->abstract('Test Abstract') ->keywords('test, keywords') ->isFamilyFriendly(true); - $this->assertSame($this->creativeWork, $result); + $this->assertSame($this->creativeWork, $creativeWork); } public function testCompleteCreativeWorkSchema(): void { - $author = new Person(); - $author->name('Jane Author'); + $person = new Person(); + $person->name('Jane Author'); - $publisher = new Organization(); - $publisher->name('Publishing House Ltd'); + $organization = new Organization(); + $organization->name('Publishing House Ltd'); - $datePublished = new \DateTime('2025-06-01'); + $datePublished = new DateTime('2025-06-01'); $this->creativeWork ->name('Complete Creative Work') ->headline('Main Headline') ->abstract('This is the abstract') - ->author($author) - ->publisher($publisher) + ->author($person) + ->publisher($organization) ->datePublished($datePublished) ->copyrightYear(2025) ->copyrightNotice('© 2025 Publishing House') @@ -402,18 +407,18 @@ public function testCompleteCreativeWorkSchema(): void public function testRenderOutputsValidJsonLd(): void { - $author = new Person(); - $author->name('Test Author'); + $person = new Person(); + $person->name('Test Author'); $this->creativeWork ->name('Test Creative Work') ->headline('Test Headline') - ->author($author); + ->author($person); $rendered = $this->creativeWork->render(); - $this->assertStringContainsString('"@type": "CreativeWork"', $rendered); - $this->assertStringContainsString('Test Creative Work', $rendered); - $this->assertStringContainsString('Test Headline', $rendered); + $this->assertStringContainsString('"@type": "CreativeWork"', (string) $rendered); + $this->assertStringContainsString('Test Creative Work', (string) $rendered); + $this->assertStringContainsString('Test Headline', (string) $rendered); } } diff --git a/tests/Integration/Schema/EventTest.php b/tests/Integration/Schema/EventTest.php index 41bf5e0..247bc40 100644 --- a/tests/Integration/Schema/EventTest.php +++ b/tests/Integration/Schema/EventTest.php @@ -1,4 +1,7 @@ assertEquals('Event', $this->event->getType()); + $this->assertSame('Event', $this->event->getType()); } public function testStartDateFormatsCorrectly(): void { - $date = new \DateTime('2025-06-15 10:00:00'); + $date = new DateTime('2025-06-15 10:00:00'); $this->event->startDate($date); $startDate = $this->event->getProperty('startDate'); @@ -55,10 +60,10 @@ public function testStartDateFormatsCorrectly(): void public function testStartDateWithTimezone(): void { - $date = new \DateTime('2025-06-15 10:00:00', new \DateTimeZone('UTC')); - $timezone = new \DateTimeZone('Europe/Berlin'); + $date = new DateTime('2025-06-15 10:00:00', new DateTimeZone('UTC')); + $dateTimeZone = new DateTimeZone('Europe/Berlin'); - $this->event->startDate($date, $timezone); + $this->event->startDate($date, $dateTimeZone); $startDate = $this->event->getProperty('startDate'); $this->assertIsString($startDate); @@ -67,7 +72,7 @@ public function testStartDateWithTimezone(): void public function testEndDateFormatsCorrectly(): void { - $date = new \DateTime('2025-06-15 18:00:00'); + $date = new DateTime('2025-06-15 18:00:00'); $this->event->endDate($date); $endDate = $this->event->getProperty('endDate'); @@ -77,10 +82,10 @@ public function testEndDateFormatsCorrectly(): void public function testEndDateWithTimezone(): void { - $date = new \DateTime('2025-06-15 18:00:00', new \DateTimeZone('UTC')); - $timezone = new \DateTimeZone('America/New_York'); + $date = new DateTime('2025-06-15 18:00:00', new DateTimeZone('UTC')); + $dateTimeZone = new DateTimeZone('America/New_York'); - $this->event->endDate($date, $timezone); + $this->event->endDate($date, $dateTimeZone); $endDate = $this->event->getProperty('endDate'); $this->assertIsString($endDate); @@ -88,10 +93,10 @@ public function testEndDateWithTimezone(): void public function testFunderWithPerson(): void { - $funder = new Person(); - $funder->name('Funding Person'); + $person = new Person(); + $person->name('Funding Person'); - $this->event->funder($funder); + $this->event->funder($person); $funderProperty = $this->event->getProperty('funder'); $this->assertIsArray($funderProperty); @@ -100,10 +105,10 @@ public function testFunderWithPerson(): void public function testFunderWithOrganization(): void { - $funder = new Organization(); - $funder->name('Funding Organization'); + $organization = new Organization(); + $organization->name('Funding Organization'); - $this->event->funder($funder); + $this->event->funder($organization); $funderProperty = $this->event->getProperty('funder'); $this->assertIsArray($funderProperty); @@ -112,10 +117,10 @@ public function testFunderWithOrganization(): void public function testOrganizerSetsProperty(): void { - $organizer = new Organization(); - $organizer->name('Event Organizer Inc'); + $organization = new Organization(); + $organization->name('Event Organizer Inc'); - $this->event->organizer($organizer); + $this->event->organizer($organization); $organizerProperty = $this->event->getProperty('organizer'); $this->assertIsArray($organizerProperty); @@ -124,10 +129,10 @@ public function testOrganizerSetsProperty(): void public function testPerformerSetsProperty(): void { - $performer = new Person(); - $performer->name('Famous Performer'); + $person = new Person(); + $person->name('Famous Performer'); - $this->event->performer($performer); + $this->event->performer($person); $performerProperty = $this->event->getProperty('performer'); $this->assertIsArray($performerProperty); @@ -168,10 +173,10 @@ public function testLocationWithPlace(): void public function testLocationWithPostalAddress(): void { - $address = new PostalAddress(); - $address->name('Event Venue'); + $postalAddress = new PostalAddress(); + $postalAddress->name('Event Venue'); - $this->event->location($address); + $this->event->location($postalAddress); $locationProperty = $this->event->getProperty('location'); $this->assertIsArray($locationProperty); @@ -192,10 +197,10 @@ public function testLocationWithVirtualLocation(): void public function testSponsorSetsProperty(): void { - $sponsor = new Organization(); - $sponsor->name('Sponsor Company'); + $organization = new Organization(); + $organization->name('Sponsor Company'); - $this->event->sponsor($sponsor); + $this->event->sponsor($organization); $sponsorProperty = $this->event->getProperty('sponsor'); $this->assertIsArray($sponsorProperty); @@ -204,10 +209,10 @@ public function testSponsorSetsProperty(): void public function testDirectorSetsProperty(): void { - $director = new Person(); - $director->name('Event Director'); + $person = new Person(); + $person->name('Event Director'); - $this->event->director($director); + $this->event->director($person); $directorProperty = $this->event->getProperty('director'); $this->assertIsArray($directorProperty); @@ -216,10 +221,10 @@ public function testDirectorSetsProperty(): void public function testAttendeeSetsProperty(): void { - $attendee = new Person(); - $attendee->name('Attendee Name'); + $person = new Person(); + $person->name('Attendee Name'); - $this->event->attendee($attendee); + $this->event->attendee($person); $attendeeProperty = $this->event->getProperty('attendee'); $this->assertIsArray($attendeeProperty); @@ -228,10 +233,10 @@ public function testAttendeeSetsProperty(): void public function testComposerSetsProperty(): void { - $composer = new Person(); - $composer->name('Music Composer'); + $person = new Person(); + $person->name('Music Composer'); - $this->event->composer($composer); + $this->event->composer($person); $composerProperty = $this->event->getProperty('composer'); $this->assertIsArray($composerProperty); @@ -282,18 +287,18 @@ public function testImageWithImageObject(): void public function testFluentInterface(): void { - $result = $this->event + $event = $this->event ->name('Tech Conference') ->eventStatus('https://schema.org/EventScheduled') ->eventAttendanceMode('https://schema.org/OfflineEventAttendanceMode'); - $this->assertSame($this->event, $result); + $this->assertSame($this->event, $event); } public function testCompleteEventSchema(): void { - $organizer = new Organization(); - $organizer->name('Tech Events Inc'); + $organization = new Organization(); + $organization->name('Tech Events Inc'); $place = new Place(); $place->name('Convention Center Berlin'); @@ -301,8 +306,8 @@ public function testCompleteEventSchema(): void $offer = new Offer(); $offer->name('Standard Ticket'); - $startDate = new \DateTime('2025-09-15 09:00:00'); - $endDate = new \DateTime('2025-09-15 18:00:00'); + $startDate = new DateTime('2025-09-15 09:00:00'); + $endDate = new DateTime('2025-09-15 18:00:00'); $this->event ->name('Annual Tech Conference 2025') @@ -310,7 +315,7 @@ public function testCompleteEventSchema(): void ->startDate($startDate) ->endDate($endDate) ->location($place) - ->organizer($organizer) + ->organizer($organization) ->offers($offer) ->eventStatus('https://schema.org/EventScheduled') ->eventAttendanceMode('https://schema.org/OfflineEventAttendanceMode'); @@ -326,7 +331,7 @@ public function testCompleteEventSchema(): void public function testRenderOutputsValidJsonLd(): void { - $startDate = new \DateTime('2025-10-01 10:00:00'); + $startDate = new DateTime('2025-10-01 10:00:00'); $this->event ->name('Workshop') @@ -335,8 +340,8 @@ public function testRenderOutputsValidJsonLd(): void $rendered = $this->event->render(); - $this->assertStringContainsString('"@type": "Event"', $rendered); - $this->assertStringContainsString('Workshop', $rendered); - $this->assertStringContainsString('2025-10-01', $rendered); + $this->assertStringContainsString('"@type": "Event"', (string) $rendered); + $this->assertStringContainsString('Workshop', (string) $rendered); + $this->assertStringContainsString('2025-10-01', (string) $rendered); } } diff --git a/tests/Integration/Schema/OrganizationTest.php b/tests/Integration/Schema/OrganizationTest.php index 2cf1c59..f754efe 100644 --- a/tests/Integration/Schema/OrganizationTest.php +++ b/tests/Integration/Schema/OrganizationTest.php @@ -1,4 +1,7 @@ assertEquals('Organization', $this->organization->getType()); + $this->assertSame('Organization', $this->organization->getType()); } public function testInheritsFromThing(): void @@ -43,11 +46,11 @@ public function testInheritsFromThing(): void public function testFluentInterface(): void { - $result = $this->organization + $baseType = $this->organization ->name('Tech Company') ->url('https://techcompany.com'); - $this->assertSame($this->organization, $result); + $this->assertSame($this->organization, $baseType); } public function testRenderOutputsValidJsonLd(): void @@ -59,9 +62,9 @@ public function testRenderOutputsValidJsonLd(): void $rendered = $this->organization->render(); - $this->assertStringContainsString('"@type": "Organization"', $rendered); - $this->assertStringContainsString('Tech Company Ltd', $rendered); - $this->assertStringContainsString('https://techcompany.com', $rendered); + $this->assertStringContainsString('"@type": "Organization"', (string) $rendered); + $this->assertStringContainsString('Tech Company Ltd', (string) $rendered); + $this->assertStringContainsString('https://techcompany.com', (string) $rendered); } public function testOrganizationUsesTraits(): void diff --git a/tests/Integration/Schema/PersonTest.php b/tests/Integration/Schema/PersonTest.php index 6e5e692..d29b095 100644 --- a/tests/Integration/Schema/PersonTest.php +++ b/tests/Integration/Schema/PersonTest.php @@ -1,4 +1,7 @@ assertEquals('Person', $this->person->getType()); + $this->assertSame('Person', $this->person->getType()); } public function testAdditionalNameSetsProperty(): void @@ -58,7 +62,7 @@ public function testJobTitleSetsProperty(): void public function testBirthDateFormatsCorrectly(): void { - $date = new \DateTime('1990-05-15'); + $date = new DateTime('1990-05-15'); $this->person->birthDate($date); $this->assertEquals('1990-05-15', $this->person->getProperty('birthDate')); } @@ -101,10 +105,10 @@ public function testAddressWithString(): void public function testAddressWithPostalAddress(): void { - $address = new PostalAddress(); - $address->name('Home Address'); + $postalAddress = new PostalAddress(); + $postalAddress->name('Home Address'); - $this->person->address($address); + $this->person->address($postalAddress); $addressProperty = $this->person->getProperty('address'); $this->assertIsArray($addressProperty); @@ -133,10 +137,10 @@ public function testRelatedToWithPerson(): void public function testAlumniOfSetsOrganization(): void { - $university = new Organization(); - $university->name('MIT'); + $organization = new Organization(); + $organization->name('MIT'); - $this->person->alumniOf($university); + $this->person->alumniOf($organization); $alumniProperty = $this->person->getProperty('alumniOf'); $this->assertIsArray($alumniProperty); @@ -151,10 +155,10 @@ public function testCallSignSetsProperty(): void public function testChildrenWithSinglePerson(): void { - $child = new Person(); - $child->name('Child Person'); + $person = new Person(); + $person->name('Child Person'); - $this->person->children($child); + $this->person->children($person); $childrenProperty = $this->person->getProperty('children'); $this->assertIsArray($childrenProperty); @@ -178,10 +182,10 @@ public function testChildrenWithArray(): void public function testSpouseSetsPersonProperty(): void { - $spouse = new Person(); - $spouse->name('Spouse Name'); + $person = new Person(); + $person->name('Spouse Name'); - $this->person->spouse($spouse); + $this->person->spouse($person); $spouseProperty = $this->person->getProperty('spouse'); $this->assertIsArray($spouseProperty); @@ -190,10 +194,10 @@ public function testSpouseSetsPersonProperty(): void public function testWorksForSetsOrganization(): void { - $company = new Organization(); - $company->name('Tech Company'); + $organization = new Organization(); + $organization->name('Tech Company'); - $this->person->worksFor($company); + $this->person->worksFor($organization); $worksForProperty = $this->person->getProperty('worksFor'); $this->assertIsArray($worksForProperty); @@ -214,24 +218,24 @@ public function testNationalitySetsCountry(): void public function testFluentInterface(): void { - $result = $this->person + $person = $this->person ->givenName('John') ->familyName('Doe') ->email('john@example.com') ->jobTitle('Developer'); - $this->assertSame($this->person, $result); + $this->assertSame($this->person, $person); } public function testCompletePersonSchema(): void { - $address = new PostalAddress(); - $address->name('Home'); + $postalAddress = new PostalAddress(); + $postalAddress->name('Home'); - $company = new Organization(); - $company->name('Tech Corp'); + $organization = new Organization(); + $organization->name('Tech Corp'); - $birthDate = new \DateTime('1985-06-20'); + $birthDate = new DateTime('1985-06-20'); $this->person ->name('Dr. John Doe') @@ -243,8 +247,8 @@ public function testCompletePersonSchema(): void ->birthDate($birthDate) ->birthPlace('New York') ->jobTitle('Senior Software Engineer') - ->address($address) - ->worksFor($company); + ->address($postalAddress) + ->worksFor($organization); $properties = $this->person->getProperties(); @@ -265,9 +269,9 @@ public function testRenderOutputsValidJsonLd(): void $rendered = $this->person->render(); - $this->assertStringContainsString('"@type": "Person"', $rendered); - $this->assertStringContainsString('John Doe', $rendered); - $this->assertStringContainsString('john@example.com', $rendered); - $this->assertStringContainsString('Developer', $rendered); + $this->assertStringContainsString('"@type": "Person"', (string) $rendered); + $this->assertStringContainsString('John Doe', (string) $rendered); + $this->assertStringContainsString('john@example.com', (string) $rendered); + $this->assertStringContainsString('Developer', (string) $rendered); } } diff --git a/tests/Integration/Schema/SchemaTest.php b/tests/Integration/Schema/SchemaTest.php index 7b1bbd3..cf81077 100644 --- a/tests/Integration/Schema/SchemaTest.php +++ b/tests/Integration/Schema/SchemaTest.php @@ -1,4 +1,7 @@ schema->administrativeArea(); - $this->assertInstanceOf(AdministrativeArea::class, $area); + $administrativeArea = $this->schema->administrativeArea(); + $this->assertInstanceOf(AdministrativeArea::class, $administrativeArea); } public function testPostalAddressMethodReturnsPostalAddressInstance(): void { - $address = $this->schema->postalAddress(); - $this->assertInstanceOf(PostalAddress::class, $address); + $postalAddress = $this->schema->postalAddress(); + $this->assertInstanceOf(PostalAddress::class, $postalAddress); } public function testAudienceMethodReturnsAudienceInstance(): void @@ -164,14 +174,14 @@ public function testMonetaryAmountMethodReturnsMonetaryAmountInstance(): void public function testEducationOccupationalCredentialMethodReturnsInstance(): void { - $credential = $this->schema->educationOccupationalCredential(); - $this->assertInstanceOf(EducationalOccupationalCredential::class, $credential); + $educationalOccupationalCredential = $this->schema->educationOccupationalCredential(); + $this->assertInstanceOf(EducationalOccupationalCredential::class, $educationalOccupationalCredential); } public function testDefinedTermMethodReturnsDefinedTermInstance(): void { - $term = $this->schema->definedTerm(); - $this->assertInstanceOf(DefinedTerm::class, $term); + $definedTerm = $this->schema->definedTerm(); + $this->assertInstanceOf(DefinedTerm::class, $definedTerm); } public function testCountryMethodReturnsCountryInstance(): void @@ -188,8 +198,8 @@ public function testPlaceMethodReturnsPlaceInstance(): void public function testLocalBusinessMethodReturnsLocalBusinessInstance(): void { - $business = $this->schema->localBusiness(); - $this->assertInstanceOf(LocalBusiness::class, $business); + $localBusiness = $this->schema->localBusiness(); + $this->assertInstanceOf(LocalBusiness::class, $localBusiness); } public function testLibraryMethodReturnsLibraryInstance(): void @@ -255,13 +265,13 @@ public function testCollectionPageMethodReturnsCollectionPageInstance(): void public function testMediaGalleryMethodReturnsMediaGalleryInstance(): void { $mediaGallery = $this->schema->mediaGallery(); - $this->assertInstanceOf(CollectionPage\MediaGallery::class, $mediaGallery); + $this->assertInstanceOf(MediaGallery::class, $mediaGallery); } public function testImageGalleryMethodReturnsImageGalleryInstance(): void { $imageGallery = $this->schema->imageGallery(); - $this->assertInstanceOf(CollectionPage\MediaGallery\ImageGallery::class, $imageGallery); + $this->assertInstanceOf(ImageGallery::class, $imageGallery); } public function testAboutPageMethodReturnsAboutPageInstance(): void @@ -273,31 +283,31 @@ public function testAboutPageMethodReturnsAboutPageInstance(): void public function testFaqPageMethodReturnsFAQPageInstance(): void { $faqPage = $this->schema->faqPage(); - $this->assertInstanceOf(WebPage\FAQPage::class, $faqPage); + $this->assertInstanceOf(FAQPage::class, $faqPage); } public function testItemPageMethodReturnsItemPageInstance(): void { $itemPage = $this->schema->itemPage(); - $this->assertInstanceOf(WebPage\ItemPage::class, $itemPage); + $this->assertInstanceOf(ItemPage::class, $itemPage); } public function testCheckoutPageMethodReturnsCheckoutPageInstance(): void { $checkoutPage = $this->schema->checkoutPage(); - $this->assertInstanceOf(WebPage\CheckoutPage::class, $checkoutPage); + $this->assertInstanceOf(CheckoutPage::class, $checkoutPage); } public function testProfilePageMethodReturnsProfilePageInstance(): void { $profilePage = $this->schema->profilePage(); - $this->assertInstanceOf(WebPage\ProfilePage::class, $profilePage); + $this->assertInstanceOf(ProfilePage::class, $profilePage); } public function testSearchResultPageMethodReturnsSearchResultsPageInstance(): void { - $searchPage = $this->schema->searchResultPage(); - $this->assertInstanceOf(WebPage\SearchResultsPage::class, $searchPage); + $searchResultsPage = $this->schema->searchResultPage(); + $this->assertInstanceOf(SearchResultsPage::class, $searchResultsPage); } public function testMediaObjectMethodReturnsMediaObjectInstance(): void @@ -320,8 +330,8 @@ public function testImageObjectMethodReturnsImageObjectInstance(): void public function testWebPageElementMethodReturnsWebPageElementInstance(): void { - $element = $this->schema->webPageElement(); - $this->assertInstanceOf(WebPageElement::class, $element); + $webPageElement = $this->schema->webPageElement(); + $this->assertInstanceOf(WebPageElement::class, $webPageElement); } public function testBreadcrumbListMethodReturnsBreadcrumbListInstance(): void @@ -338,8 +348,8 @@ public function testListItemMethodReturnsListItemInstance(): void public function testSpeakableSpecificationMethodReturnsSpeakableSpecificationInstance(): void { - $speakable = $this->schema->speakableSpecification(); - $this->assertInstanceOf(SpeakableSpecification::class, $speakable); + $speakableSpecification = $this->schema->speakableSpecification(); + $this->assertInstanceOf(SpeakableSpecification::class, $speakableSpecification); } public function testSpecialtyMethodReturnsSpecialtyInstance(): void @@ -362,8 +372,8 @@ public function testContactPageMethodReturnsContactPageInstance(): void public function testSocialMediaPostingMethodReturnsSocialMediaPostingInstance(): void { - $socialMedia = $this->schema->socialMediaPosting(); - $this->assertInstanceOf(SocialMediaPosting::class, $socialMedia); + $socialMediaPosting = $this->schema->socialMediaPosting(); + $this->assertInstanceOf(SocialMediaPosting::class, $socialMediaPosting); } public function testBlogPostingMethodReturnsBlogPostingInstance(): void @@ -396,19 +406,13 @@ public function testGetTypeReturnsCurrentType(): void $this->assertInstanceOf(BaseType::class, $type); } - public function testGetTypeReturnsNullableBaseType(): void - { - $type = $this->schema->getType(); - $this->assertTrue($type instanceof BaseType || $type === null); - } - public function testMultipleFactoryMethodCalls(): void { $person1 = $this->schema->person(); $person2 = $this->schema->person(); $this->assertNotSame($person1, $person2); - $this->assertEquals(get_class($person1), get_class($person2)); + $this->assertInstanceOf($person1::class, $person2); } public function testRenderChangesBaseType(): void diff --git a/tests/Util/App/BaseKernel.php b/tests/Util/App/BaseKernel.php index e2309de..dfe0ae3 100644 --- a/tests/Util/App/BaseKernel.php +++ b/tests/Util/App/BaseKernel.php @@ -1,4 +1,7 @@ load(__DIR__ . '/config/config.yaml'); + $loader->load(__DIR__.'/config/config.yaml'); } public function getCacheDir(): string @@ -52,4 +52,4 @@ public function getProjectDir(): string { return __DIR__.'/../'; } -} \ No newline at end of file +}