45 lines
1.9 KiB
PHP
45 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace Modules\Stylist\Html;
|
|
|
|
use Illuminate\Support\HtmlString;
|
|
use Modules\Stylist\Theme\Stylist;
|
|
use Modules\Stylist\Theme\UrlGenerator;
|
|
|
|
final class ThemeSeoBuilder
|
|
{
|
|
public function __construct(private readonly Stylist $stylist, private readonly UrlGenerator $urls) {}
|
|
|
|
public function render(array $overrides = []): HtmlString
|
|
{
|
|
$theme = $this->stylist->current();
|
|
$seo = array_replace($theme->seo(), $overrides);
|
|
$settings = $this->stylist->settings();
|
|
$title = (string) ($seo['title'] ?? $settings['site_title'] ?? $theme->name());
|
|
$description = (string) ($seo['description'] ?? $settings['site_description'] ?? $theme->description());
|
|
$image = $seo['image'] ?? $theme->preview();
|
|
if ($image && $theme->has($image)) {
|
|
$image = $this->urls->asset($image);
|
|
}
|
|
$tags = ['<title>'.e($title).'</title>'];
|
|
if ($description !== '') {
|
|
$tags[] = '<meta name="description" content="'.e($description).'">';
|
|
}
|
|
foreach (['og:title' => $title, 'og:description' => $description, 'twitter:card' => 'summary_large_image', 'twitter:title' => $title, 'twitter:description' => $description] as $property => $content) {
|
|
if ($content === '') {
|
|
continue;
|
|
}$attribute = str_starts_with($property, 'og:') ? 'property' : 'name';
|
|
$tags[] = '<meta '.$attribute.'="'.e($property).'" content="'.e($content).'">';
|
|
}
|
|
if ($image) {
|
|
$tags[] = '<meta property="og:image" content="'.e($image).'">';
|
|
$tags[] = '<meta name="twitter:image" content="'.e($image).'">';
|
|
}
|
|
if (isset($seo['json_ld']) && is_array($seo['json_ld'])) {
|
|
$tags[] = '<script type="application/ld+json">'.json_encode($seo['json_ld'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE).'</script>';
|
|
}
|
|
|
|
return new HtmlString(implode("\n", $tags));
|
|
}
|
|
}
|