Passed
Push — php-di ( 14dc40...53e65d )
by Arnaud
21:01 queued 17:21
created

ExternalBody::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 4
dl 0
loc 8
ccs 3
cts 3
cp 1
crap 1
rs 10
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 1
    public function __construct(
38
        Builder $builder,
39
        Config $config,
40
        LoggerInterface $logger,
41
        Converter $converter
42
    ) {
43 1
        parent::__construct($builder, $config, $logger);
44 1
        $this->converter = $converter;
45
    }
46
    /**
47
     * {@inheritdoc}
48
     */
49 1
    public function generate(): void
50
    {
51 1
        $filteredPages = $this->builder->getPages()->filter(function (Page $page) {
52 1
            return $page->getVariable('external') !== null;
53 1
        });
54
55
        /** @var Page $page */
56 1
        foreach ($filteredPages as $page) {
57
            try {
58 1
                $pageContent = Util\File::fileGetContents($page->getVariable('external'));
59 1
                if ($pageContent === false) {
60 1
                    throw new RuntimeException(\sprintf('Unable to get external contents from "%s".', $page->getVariable('external')));
61
                }
62 1
                $html = $this->converter->convertBody($pageContent);
63 1
                $page->setBodyHtml($html);
64
65 1
                $this->generatedPages->add($page);
66 1
            } catch (\Exception $e) {
67 1
                $message = \sprintf('Error in "%s": %s', $page->getFilePath(), $e->getMessage());
68 1
                $this->logger->error($message);
69
            }
70
        }
71
    }
72
}
73