-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImagesNextToBuiltFiles.php
53 lines (41 loc) · 1.86 KB
/
ImagesNextToBuiltFiles.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
<?php
declare(strict_types=1);
namespace App\Listeners;
use DOMDocument;
use TightenCo\Jigsaw\Collection\CollectionItem;
use TightenCo\Jigsaw\Jigsaw;
class ImagesNextToBuiltFiles
{
public function handle(Jigsaw $jigsaw): void
{
collect($jigsaw->getPages())
->filter(fn($page) => $page instanceof CollectionItem)
->each(function (CollectionItem $item) use ($jigsaw) {
// Read the output file
$itemFolderName = $item->getPath();
$html = $jigsaw->readOutputFile($itemFolderName.'/index.html');
// Scan the HTML for collection-specific images.
$document = new DOMDocument();
@$document->loadHTML($html);
$container = $document->getElementById('post-content');
if ($container === null) {
return;
}
/** @var \DOMElement[] $images */
$images = $container->getElementsByTagName('img');
foreach ($images as $image) {
if ($image->hasAttribute('keeplocation')) {
continue;
}
$originalImageLocation = $image->getAttribute('src');
// Move the image into the post's output folder.
$newImageLocation = $itemFolderName.'/'.basename($originalImageLocation);
$jigsaw->writeOutputFile($newImageLocation, $jigsaw->readOutputFile(ltrim($originalImageLocation, DIRECTORY_SEPARATOR)));
// Change the src of the image to the new path.
$image->setAttribute('src', $newImageLocation);
}
// Write the new HTML into the output file.
$jigsaw->writeOutputFile($itemFolderName.'/index.html', $document->saveHTML());
});
}
}