Completed
Pull Request — master (#41)
by Vladimir
02:35
created

Compiler::compilePageView()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 10.75

Importance

Changes 0
Metric Value
cc 4
eloc 14
nc 4
nop 1
dl 0
loc 20
ccs 4
cts 16
cp 0.25
crap 10.75
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright 2017 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx;
9
10
use allejo\stakx\FrontMatter\ExpandedValue;
11
use allejo\stakx\Manager\BaseManager;
12
use allejo\stakx\Manager\TwigManager;
13
use allejo\stakx\Object\ContentItem;
14
use allejo\stakx\Object\DynamicPageView;
15
use allejo\stakx\Object\PageView;
16
use allejo\stakx\Object\RepeaterPageView;
17
use allejo\stakx\System\Folder;
18
use Twig_Environment;
19
use Twig_Error_Syntax;
20
use Twig_Source;
21
use Twig_Template;
22
23
/**
24
 * This class takes care of rendering the Twig body of PageViews with the respective information and it also takes care
25
 * of writing the rendered Twig to the filesystem.
26
 *
27
 * @internal
28
 * @since 0.1.1
29
 */
30
class Compiler extends BaseManager
31
{
32
    /** @var string|false */
33
    private $redirectTemplate;
34
35
    /** @var PageView[] */
36
    private $pageViews;
37
38
    /** @var Folder */
39
    private $folder;
40
41
    /** @var Twig_Environment */
42
    private $twig;
43
44 5
    public function __construct()
45
    {
46 5
        parent::__construct();
47
48 5
        $this->twig = TwigManager::getInstance();
49 5
    }
50
51
    /**
52
     * @param string|false $template
53
     */
54
    public function setRedirectTemplate ($template)
55
    {
56
        $this->redirectTemplate = $template;
57
    }
58
59
    /**
60
     * @param Folder $folder
61
     */
62 5
    public function setTargetFolder (Folder $folder)
63
    {
64 5
        $this->folder = $folder;
65 5
    }
66
67
    /**
68
     * @param PageView[] $pageViews
69
     */
70 5
    public function setPageViews (array $pageViews)
71
    {
72 5
        $this->pageViews = $pageViews;
73 5
    }
74
75
    ///
76
    // IO Functionality
77
    ///
78
79
    /**
80
     * Compile all of the PageViews registered with the compiler
81
     *
82
     * @since 0.1.0
83
     */
84 5
    public function compileAll ()
85
    {
86 5
        foreach ($this->pageViews as &$pageView)
87
        {
88 5
            $this->compilePageView($pageView);
89
        }
90
    }
91
92
    /**
93
     * Compile an individual PageView item
94
     *
95
     * This function will take care of determining *how* to treat the PageView and write the compiled output to a the
96
     * respective target file.
97
     *
98
     * @param DynamicPageView|RepeaterPageView|PageView $pageView The PageView that needs to be compiled
99
     * @since 0.1.1
100
     */
101 5
    private function compilePageView (&$pageView)
102
    {
103 5
        switch ($pageView->getType())
104
        {
105 5
            case PageView::STATIC_TYPE:
106 5
                $this->compileStaticPageView($pageView);
107
                $this->compileStandardRedirects($pageView);
108
                break;
109
110
            case PageView::DYNAMIC_TYPE:
111
                $this->compileDynamicPageViews($pageView);
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Object\PageView> is not a sub-type of object<allejo\stakx\Object\DynamicPageView>. It seems like you assume a child class of the class allejo\stakx\Object\PageView to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
112
                $this->compileStandardRedirects($pageView);
113
                break;
114
115
            case PageView::REPEATER_TYPE:
116
                $this->compileRepeaterPageViews($pageView);
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Object\PageView> is not a sub-type of object<allejo\stakx\Object\RepeaterPageView>. It seems like you assume a child class of the class allejo\stakx\Object\PageView to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
117
                $this->compileExpandedRedirects($pageView);
118
                break;
119
        }
120
    }
121
122
    /**
123
     * Write the compiled output for a static PageView
124
     *
125
     * @param PageView $pageView
126
     * @since 0.1.1
127
     */
128 5
    private function compileStaticPageView (&$pageView)
129
    {
130 5
        $targetFile = $pageView->getTargetFile();
131 5
        $output = $this->renderStaticPageView($pageView);
132
133
        $this->output->notice("Writing file: {file}", array('file' => $targetFile));
134
        $this->folder->writeFile($targetFile, $output);
135
    }
136
137
    /**
138
     * Write the compiled output for a dynamic PageView
139
     *
140
     * @param DynamicPageView $pageView
141
     * @since 0.1.1
142
     */
143 View Code Duplication
    private function compileDynamicPageViews (&$pageView)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144
    {
145
        $contentItems = $pageView->getContentItems();
146
        $template = $this->createTwigTemplate($pageView);
147
148
        foreach ($contentItems as $contentItem)
149
        {
150
            $targetFile = $contentItem->getTargetFile();
151
            $output = $this->renderDynamicPageView($template, $pageView, $contentItem);
152
153
            $this->output->notice("Writing file: {file}", array('file' => $targetFile));
154
            $this->folder->writeFile($targetFile, $output);
155
        }
156
    }
157
158
    /**
159
     * Write the compiled output for a repeater PageView
160
     *
161
     * @param RepeaterPageView $pageView
162
     * @since 0.1.1
163
     */
164 View Code Duplication
    private function compileRepeaterPageViews (&$pageView)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
165
    {
166
        $pageView->rewindPermalink();
167
168
        $template = $this->createTwigTemplate($pageView);
169
        $permalinks = $pageView->getRepeaterPermalinks();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class allejo\stakx\Object\PageView as the method getRepeaterPermalinks() does only exist in the following sub-classes of allejo\stakx\Object\PageView: allejo\stakx\Object\RepeaterPageView. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
170
171
        foreach ($permalinks as $permalink)
172
        {
173
            $pageView->bumpPermalink();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class allejo\stakx\Object\PageView as the method bumpPermalink() does only exist in the following sub-classes of allejo\stakx\Object\PageView: allejo\stakx\Object\RepeaterPageView. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
174
            $targetFile = $pageView->getTargetFile();
175
            $output = $this->renderRepeaterPageView($template, $pageView, $permalink);
176
177
            $this->output->notice("Writing repeater file: {file}", array('file' => $targetFile));
178
            $this->folder->writeFile($targetFile, $output);
179
        }
180
    }
181
182
    ///
183
    // Redirect handling
184
    ///
185
186
    /**
187
     * Write redirects for standard redirects
188
     *
189
     * @param PageView $pageView
190
     * @since 0.1.1
191
     */
192
    private function compileStandardRedirects (&$pageView)
193
    {
194
        $redirects = $pageView->getRedirects();
195
196
        foreach ($redirects as $redirect)
0 ignored issues
show
Bug introduced by
The expression $redirects of type null|array<integer,string> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
197
        {
198
            $redirectPageView = PageView::createRedirect(
199
                $redirect,
200
                $pageView->getPermalink(),
201
                $this->redirectTemplate
202
            );
203
204
            $this->compilePageView($redirectPageView);
205
        }
206
    }
207
208
    /**
209
     * Write redirects for expanded redirects
210
     *
211
     * @param RepeaterPageView $pageView
212
     * @since 0.1.1
213
     */
214
    private function compileExpandedRedirects (&$pageView)
215
    {
216
        $permalinks = $pageView->getRepeaterPermalinks();
217
218
        /** @var ExpandedValue[] $repeaterRedirect */
219
        foreach ($pageView->getRepeaterRedirects() as $repeaterRedirect)
220
        {
221
            /**
222
             * @var int           $index
223
             * @var ExpandedValue $redirect
224
             */
225
            foreach ($repeaterRedirect as $index => $redirect)
226
            {
227
                $redirectPageView = PageView::createRedirect(
228
                    $redirect->getEvaluated(),
229
                    $permalinks[$index]->getEvaluated(),
230
                    $this->redirectTemplate
231
                );
232
                $this->compilePageView($redirectPageView);
233
            }
234
        }
235
    }
236
237
    ///
238
    // Twig Functionality
239
    ///
240
241
    /**
242
     * Get the compiled HTML for a specific iteration of a repeater PageView
243
     *
244
     * @param Twig_Template $template
245
     * @param PageView      $pageView
246
     * @param ExpandedValue $expandedValue
247
     *
248
     * @since  0.1.1
249
     * @return string
250
     */
251
    private function renderRepeaterPageView (&$template, &$pageView, &$expandedValue)
252
    {
253
        $this->twig->addGlobal('__currentTemplate', $pageView->getFilePath());
254
255
        $pageView->setFrontMatter(array(
256
            'permalink' => $expandedValue->getEvaluated(),
257
            'iterators' => $expandedValue->getIterators()
258
        ));
259
260
        return $template
261
            ->render(array(
262
                'this' => $pageView->createJail()
263
            ));
264
    }
265
266
    /**
267
     * Get the compiled HTML for a specific ContentItem
268
     *
269
     * @param  Twig_Template $template
270
     * @param  PageView      $pageView
271
     * @param  ContentItem   $contentItem
272
     *
273
     * @since  0.1.1
274
     * @return string
275
     */
276
    private function renderDynamicPageView (&$template, &$pageView, &$contentItem)
277
    {
278
        $this->twig->addGlobal('__currentTemplate', $pageView->getFilePath());
279
280
        return $template
281
            ->render(array(
282
                'this' => $contentItem->createJail()
283
            ));
284
    }
285
286
    /**
287
     * Get the compiled HTML for a static PageView
288
     *
289
     * @param  PageView $pageView
290
     *
291
     * @since  0.1.1
292
     * @return string
293
     *
294
     * @throws \Exception
295
     * @throws \Throwable
296
     * @throws Twig_Error_Syntax
297
     */
298 5
    private function renderStaticPageView (&$pageView)
299
    {
300 5
        $this->twig->addGlobal('__currentTemplate', $pageView->getFilePath());
301
302 5
        return $this
303 5
            ->createTwigTemplate($pageView)
304
            ->render(array(
305
                'this' => $pageView->createJail()
306
            ));
307
    }
308
309
    /**
310
     * Create a Twig template that just needs an array to render
311
     *
312
     * @param  PageView $pageView The PageView whose body will be used for Twig compilation
313
     * @since  0.1.1
314
     *
315
     * @return Twig_Template
316
     *
317
     * @throws \Exception
318
     * @throws \Throwable
319
     * @throws Twig_Error_Syntax
320
     */
321 5
    private function createTwigTemplate (&$pageView)
322
    {
323
        try
324
        {
325 5
            return $this->twig->createTemplate($pageView->getContent());
326
        }
327 5
        catch (Twig_Error_Syntax $e)
328
        {
329 5
            $e->setTemplateLine($e->getTemplateLine() + $pageView->getLineOffset());
330 5
            $e->setSourceContext(new Twig_Source(
331 5
                $pageView->getContent(),
332 5
                $pageView->getName(),
333 5
                $pageView->getRelativeFilePath()
334 5
            ));
335
336 5
            throw $e;
337
        }
338
    }
339
}
340