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

Convert   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 118
Duplicated Lines 0 %

Test Coverage

Coverage 83.02%

Importance

Changes 0
Metric Value
eloc 53
dl 0
loc 118
ccs 44
cts 53
cp 0.8302
rs 10
c 0
b 0
f 0
wmc 21

5 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 6 2
A getName() 0 7 2
A convertPage() 0 27 6
A __construct() 0 8 1
B process() 0 40 10
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\Step\Pages;
15
16
use Cecil\Builder;
17
use Cecil\Collection\Page\Page;
18
use Cecil\Config;
19
use Cecil\Converter\Converter;
20
use Cecil\Converter\ConverterInterface;
21
use Cecil\Exception\RuntimeException;
22
use Cecil\Step\AbstractStep;
23
use Cecil\Util;
24
use Psr\Log\LoggerInterface;
25
26
/**
27
 * Convert step.
28
 *
29
 * This step is responsible for converting pages from their source format
30
 * (i.e. Markdown) to HTML, applying front matter processing,
31
 * and ensuring that the pages are ready for rendering. It handles both
32
 * published and draft pages, depending on the build options.
33
 */
34
class Convert extends AbstractStep
35
{
36
    private Converter $converter;
37
38 1
    public function __construct(
39
        Builder $builder,
40
        Config $config,
41
        LoggerInterface $logger,
42
        Converter $converter
43
    ) {
44 1
        parent::__construct($builder, $config, $logger);
45 1
        $this->converter = $converter;
46
    }
47
    /**
48
     * {@inheritdoc}
49
     */
50 1
    public function getName(): string
51
    {
52 1
        if ($this->builder->getBuildOptions()['drafts']) {
53 1
            return 'Converting pages (drafts included)';
54
        }
55
56
        return 'Converting pages';
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 1
    public function init(array $options): void
63
    {
64 1
        parent::init($options);
65
66 1
        if (\is_null($this->builder->getPages())) {
67
            $this->canProcess = false;
68
        }
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74 1
    public function process(): void
75
    {
76 1
        if (!is_iterable($this->builder->getPages()) || \count($this->builder->getPages()) == 0) {
77
            return;
78
        }
79
80 1
        $total = \count($this->builder->getPages());
81 1
        $count = 0;
82
        /** @var Page $page */
83 1
        foreach ($this->builder->getPages() as $page) {
84 1
            if (!$page->isVirtual()) {
85 1
                $count++;
86
87
                try {
88 1
                    $convertedPage = $this->convertPage($this->builder, $page);
89
                    // set default language (ex: "en") if necessary
90 1
                    if ($convertedPage->getVariable('language') === null) {
91 1
                        $convertedPage->setVariable('language', $this->config->getLanguageDefault());
92
                    }
93 1
                } catch (RuntimeException $e) {
94 1
                    $this->logger->error(\sprintf('Unable to convert "%s:%s": %s', $e->getFile(), $e->getLine(), $e->getMessage()));
95 1
                    $this->builder->getPages()->remove($page->getId());
96 1
                    continue;
97
                } catch (\Exception $e) {
98
                    $this->logger->error(\sprintf('Unable to convert "%s": %s', Util::joinPath(Util\File::getFS()->makePathRelative($page->getFilePath(), $this->config->getPagesPath())), $e->getMessage()));
99
                    $this->builder->getPages()->remove($page->getId());
100
                    continue;
101
                }
102 1
                $message = \sprintf('Page "%s" converted', $page->getId());
103 1
                $statusMessage = ' (not published)';
104
                // forces drafts convert?
105 1
                if ($this->builder->getBuildOptions()['drafts']) {
106 1
                    $page->setVariable('published', true);
107
                }
108
                // replaces page in collection
109 1
                if ($page->getVariable('published')) {
110 1
                    $this->builder->getPages()->replace($page->getId(), $convertedPage);
111 1
                    $statusMessage = '';
112
                }
113 1
                $this->logger->info($message . $statusMessage, ['progress' => [$count, $total]]);
114
            }
115
        }
116
    }
117
118
    /**
119
     * Converts page content:
120
     *  - front matter to PHP array
121
     *  - body to HTML.
122
     *
123
     * @throws RuntimeException
124
     */
125 1
    public function convertPage(Builder $builder, Page $page, ?string $format = null, ?ConverterInterface $converter = null): Page
126
    {
127 1
        $format = $format ?? (string) $builder->getConfig()->get('pages.frontmatter');
128 1
        $converter = $converter ?? $this->converter;
129
130
        // converts front matter
131 1
        if ($page->getFrontmatter()) {
132
            try {
133 1
                $variables = $converter->convertFrontmatter($page->getFrontmatter(), $format);
134 1
            } catch (RuntimeException $e) {
135 1
                throw new RuntimeException($e->getMessage(), file: $page->getFilePath(), line: $e->getLine());
136
            }
137 1
            $page->setFmVariables($variables);
138 1
            $page->setVariables($variables);
139
        }
140
141
        // converts body (only if page is published or drafts option is enabled)
142 1
        if ($page->getVariable('published') || $this->options['drafts']) {
143
            try {
144 1
                $html = $converter->convertBody($page->getBody());
145
            } catch (RuntimeException $e) {
146
                throw new \Exception($e->getMessage());
147
            }
148 1
            $page->setBodyHtml($html);
149
        }
150
151 1
        return $page;
152
    }
153
}
154