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 Psr\Log\LoggerInterface;
23
24
/**
25
 * ExternalBody generator class.
26
 *
27
 * This class is responsible for generating the body of pages
28
 * by fetching content from external sources specified in the 'external' variable of each page.
29
 * It reads the content from the specified URL, converts it to HTML using the Converter,
30
 * and sets the resulting HTML as the body of the page.
31
 * If an error occurs while fetching the content, it logs the error message.
32
 */
33
class ExternalBody extends AbstractGenerator implements GeneratorInterface
34
{
35
    private Converter $converter;
36
37
    public function __construct(
38
        Builder $builder,
39
        Config $config,
40
        LoggerInterface $logger,
41
        Converter $converter
42
    ) {
43
        parent::__construct($builder, $config, $logger);
44
        $this->converter = $converter;
45
    }
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function generate(): void
50
    {
51
        $filteredPages = $this->builder->getPages()->filter(function (Page $page) {
52
            return $page->getVariable('external') !== null;
53
        });
54
55
        /** @var Page $page */
56
        foreach ($filteredPages as $page) {
57
            try {
58
                $pageContent = Util\File::fileGetContents($page->getVariable('external'));
59
                if ($pageContent === false) {
60
                    throw new RuntimeException(\sprintf('Unable to get external contents from "%s".', $page->getVariable('external')));
61
                }
62
                $html = $this->converter->convertBody($pageContent);
63
                $page->setBodyHtml($html);
64
65
                $this->generatedPages->add($page);
66
            } catch (\Exception $e) {
67
                $message = \sprintf('Error in "%s": %s', $page->getFilePath(), $e->getMessage());
68
                $this->logger->error($message);
69
            }
70
        }
71
    }
72
}
73