Completed
Push — feature-output-formats ( 57920b...fb821f )
by Arnaud
02:54
created

PagesRender::process()   C

Complexity

Conditions 12
Paths 73

Size

Total Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 71
rs 6.206
c 0
b 0
f 0
cc 12
nc 73
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Step;
10
11
use Cecil\Collection\Page\Page;
12
use Cecil\Exception\Exception;
13
use Cecil\Renderer\Layout;
14
use Cecil\Renderer\Twig as Twig;
15
16
/**
17
 * Pages rendering.
18
 */
19
class PagesRender extends AbstractStep
20
{
21
    /**
22
     * {@inheritdoc}
23
     *
24
     * @throws Exception
25
     */
26
    public function init($options)
27
    {
28
        if (!is_dir($this->config->getLayoutsPath()) && !$this->config->hasTheme()) {
29
            throw new Exception(sprintf(
30
                "'%s' is not a valid layouts directory",
31
                $this->config->getLayoutsPath()
32
            ));
33
        }
34
35
        $this->process = true;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     *
41
     * @throws Exception
42
     */
43
    public function process()
44
    {
45
        // prepares renderer
46
        $this->builder->setRenderer(new Twig($this->getAllLayoutsPaths(), $this->config));
47
48
        // add globals variables
49
        $this->addGlobals();
50
51
        call_user_func_array($this->builder->getMessageCb(), ['RENDER', 'Rendering pages']);
52
53
        // collect published pages
54
        /* @var $page Page */
55
        $filteredPages = $this->builder->getPages()->filter(function (Page $page) {
56
            return !empty($page->getVariable('published'));
57
        });
58
        $max = count($filteredPages);
59
60
        // render each page
61
        $count = 0;
62
        foreach ($filteredPages as $page) {
63
            $count++;
64
            $formats = ['html'];
65
            $rendered = null;
66
            $hasAlternates = false;
0 ignored issues
show
Unused Code introduced by
$hasAlternates is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
67
            $alternates = [];
68
69
            // get available formats
70
            if (\is_array($this->config->get('site.output.pagesformats.'.$page->getType()))) {
71
                $formats = $this->config->get('site.output.pagesformats.'.$page->getType());
72
            }
73
            if (\is_array($page->getVariable('output'))) {
74
                $formats = $page->getVariable('output');
75
            }
76
77
            // list alternates
78
            if (count($formats) > 1 && array_key_exists('html', $formats)) {
79
                $hasAlternates = true;
0 ignored issues
show
Unused Code introduced by
$hasAlternates is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
80
            }
81
            foreach ($formats as $format) {
82
                if ($format == 'html') {
83
                    continue;
84
                }
85
                $alternates[] = [
86
                    'rel'   => 'alternate',
87
                    'type'  => $this->config->get("site.output.formats.$format.mediatype"),
88
                    'title' => strtoupper($format),
89
                    'href'  => $page->getPermalink().'/'.$this->config->get("site.output.formats.$format.filename"),
90
                ];
91
            }
92
            $page->setVariable('alternates', $alternates);
93
94
            // render each format
95
            foreach ($formats as $format) {
96
                if ($format != 'html' && $page->hasVariable('destination')) {
97
                    continue;
98
                }
99
                $layout = (new Layout())->finder($page, $format, $this->config);
100
                $rendered[$format]['output'] = $this->builder->getRenderer()->render(
101
                    $layout,
102
                    ['page' => $page]
103
                );
104
                $rendered[$format]['template'] = $layout;
105
            }
106
            $page->setVariable('rendered', $rendered);
107
            $this->builder->getPages()->replace($page->getId(), $page);
108
109
            $layouts = implode(', ', array_column($rendered, 'template'));
110
            $message = sprintf('%s (%s)', ($page->getId() ?: 'index'), $layouts);
111
            call_user_func_array($this->builder->getMessageCb(), ['RENDER_PROGRESS', $message, $count, $max]);
112
        }
113
    }
114
115
    /**
116
     * Return an array of layouts directories.
117
     *
118
     * @return array Layouts directory
119
     */
120
    protected function getAllLayoutsPaths()
121
    {
122
        $paths = [];
123
124
        // layouts/
125
        if (is_dir($this->config->getLayoutsPath())) {
126
            $paths[] = $this->config->getLayoutsPath();
127
        }
128
        // <theme>/layouts/
129
        if ($this->config->hasTheme()) {
130
            $themes = $this->config->getTheme();
131
            foreach ($themes as $theme) {
132
                $paths[] = $this->config->getThemeDirPath($theme);
133
            }
134
        }
135
        // res/layouts/
136
        if (is_dir($this->config->getInternalLayoutsPath())) {
137
            $paths[] = $this->config->getInternalLayoutsPath();
138
        }
139
140
        return $paths;
141
    }
142
143
    /**
144
     * Add globals variables.
145
     */
146
    protected function addGlobals()
147
    {
148
        // adds global variables
149
        $this->builder->getRenderer()->addGlobal('site', array_merge(
150
            $this->config->get('site'),
151
            ['menus' => $this->builder->getMenus()],
152
            ['pages' => $this->builder->getPages()->filter(function (Page $page) {
153
                return $page->getVariable('published');
154
            })],
155
            ['time' => time()]
156
        ));
157
        $this->builder->getRenderer()->addGlobal('cecil', [
158
            'url'       => sprintf('https://cecil.app/#%s', $this->builder->getVersion()),
159
            'version'   => $this->builder->getVersion(),
160
            'poweredby' => sprintf('Cecil v%s', $this->builder->getVersion()),
161
        ]);
162
    }
163
}
164