-
Notifications
You must be signed in to change notification settings - Fork 0
/
SetSocialImagesForCollectionItems.php
58 lines (45 loc) · 1.86 KB
/
SetSocialImagesForCollectionItems.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
namespace App\Listeners;
use DOMDocument;
use DOMElement;
use RuntimeException;
use TightenCo\Jigsaw\Collection\CollectionItem;
use TightenCo\Jigsaw\Jigsaw;
class SetSocialImagesForCollectionItems
{
public function handle(Jigsaw $jigsaw)
{
collect($jigsaw->getPages())
->filter(fn($page) => $page instanceof CollectionItem)
->each(function (CollectionItem $item) use ($jigsaw) {
$itemFolderName = $item->getPath();
$html = $jigsaw->readOutputFile($itemFolderName.'/index.html');
$document = new DOMDocument();
@$document->loadHTML($html);
try {
$socialImageUrl = $item->link($this->getSocialImage($document));
$ogElement = $document->getElementById('social-img-og');
$ogElement?->setAttribute('content', $socialImageUrl);
$ogElement?->removeAttribute('id');
$twElement = $document->getElementById('social-img-tw');
$twElement?->setAttribute('content', $socialImageUrl);
$twElement?->removeAttribute('id');
$jigsaw->writeOutputFile($itemFolderName.'/index.html', $document->saveHTML());
} catch (RuntimeException $e) {
// no-op
}
});
}
private function getSocialImage(DOMDocument $document): string
{
$socialImage = $document->getElementById('social-image');
if ($socialImage instanceof DOMElement) {
return $socialImage->getAttribute('src');
}
[$firstImage] = $document->getElementsByTagName('img');
if ($firstImage instanceof DOMElement) {
return $firstImage->getAttribute('src');
}
throw new \RuntimeException('No social image to be found.');
}
}