ExternalBody::generate()   A
last analyzed

Complexity

Conditions 4
Paths 7

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 7
nop 0
dl 0
loc 20
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil\Generator;
15
16
use Cecil\Builder;
17
use Cecil\Collection\Page\Page;
18
use Cecil\Config;
19
use Cecil\Converter\Converter;
20
use Cecil\Exception\RuntimeException;
21
use Cecil\Util;
22
use DI\Attribute\Inject;
23
use Psr\Log\LoggerInterface;
24
25
/**
26
 * ExternalBody generator class.
27
 *
28
 * This class is responsible for generating the body of pages
29
 * by fetching content from external sources specified in the 'external' variable of each page.
30
 * It reads the content from the specified URL, converts it to HTML using the Converter,
31
 * and sets the resulting HTML as the body of the page.
32
 * If an error occurs while fetching the content, it logs the error message.
33
 */
34
class ExternalBody extends AbstractGenerator implements GeneratorInterface
35
{
36
    #[Inject]
37
    private Converter $converter;
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function generate(): void
43
    {
44
        $filteredPages = $this->builder->getPages()->filter(function (Page $page) {
45
            return $page->getVariable('external') !== null;
46
        });
47
48
        /** @var Page $page */
49
        foreach ($filteredPages as $page) {
50
            try {
51
                $pageContent = Util\File::fileGetContents($page->getVariable('external'));
52
                if ($pageContent === false) {
53
                    throw new RuntimeException(\sprintf('Unable to get external contents from "%s".', $page->getVariable('external')));
54
                }
55
                $html = $this->converter->convertBody($pageContent);
56
                $page->setBodyHtml($html);
57
58
                $this->generatedPages->add($page);
59
            } catch (\Exception $e) {
60
                $message = \sprintf('Error in "%s": %s', $page->getFilePath(), $e->getMessage());
61
                $this->logger->error($message);
62
            }
63
        }
64
    }
65
}
66