Passed
Push — master ( 5399ee...fe113d )
by Caen
03:32 queued 12s
created

PageMetadataBag::addDynamicPageMetadata()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 13
rs 10
1
<?php
2
3
namespace Hyde\Framework\Modules\Metadata;
4
5
use Hyde\Framework\Concerns\HydePage;
6
use Hyde\Framework\Helpers\Meta;
7
use Hyde\Framework\Models\Pages\MarkdownPost;
8
9
class PageMetadataBag extends MetadataBag
10
{
11
    protected HydePage $page;
12
13
    public function __construct(HydePage $page)
14
    {
15
        $this->page = $page;
16
17
        $this->generate();
18
    }
19
20
    protected function generate(): void
21
    {
22
        $this->addDynamicPageMetadata($this->page);
23
    }
24
25
    protected function addDynamicPageMetadata(HydePage $page): void
26
    {
27
        if ($page->has('canonicalUrl')) {
28
            $this->add(Meta::link('canonical', $page->get('canonicalUrl')));
29
        }
30
31
        if ($page->has('title')) {
32
            $this->add(Meta::name('twitter:title', $page->htmlTitle()));
33
            $this->add(Meta::property('title', $page->htmlTitle()));
34
        }
35
36
        if ($page instanceof MarkdownPost) {
37
            $this->addMetadataForMarkdownPost($page);
38
        }
39
    }
40
41
    protected function addMetadataForMarkdownPost(MarkdownPost $page): void
42
    {
43
        $this->addPostMetadataIfExists($page, 'description');
44
        $this->addPostMetadataIfExists($page, 'author');
45
        $this->addPostMetadataIfExists($page, 'category', 'keywords');
46
        $this->addPostMetadataIfExists($page, 'canonicalUrl', 'url');
47
48
        if ($page->has('canonicalUrl')) {
49
            $this->add(Meta::property('url', $page->get('canonicalUrl')));
50
        }
51
52
        if ($page->has('date')) {
53
            $this->add(Meta::property('og:article:published_time', $page->date->datetime));
54
        }
55
56
        if ($page->has('image')) {
57
            $this->add(Meta::property('image', $this->resolveImageLink($page->get('image'))));
58
        }
59
60
        $this->add(Meta::property('type', 'article'));
61
    }
62
63
    protected function addPostMetadataIfExists(MarkdownPost $page, string $property, ?string $name = null): void
64
    {
65
        if ($page->has($property)) {
66
            $this->add(Meta::name($name ?? $property, $page->get($property)));
67
        }
68
    }
69
70
    protected function resolveImageLink(string $image): string
71
    {
72
        // Since this is run before the page is rendered, we don't have the currentPage property
73
        // but since we know that this is for a blog post we know what the property will be
74
        // since Hyde does not currently support custom Blog post output directories.
75
        return str_starts_with($image, 'http') ? $image : "../$image";
76
    }
77
}
78