Completed
Pull Request — master (#41)
by Vladimir
04:25
created

Compiler::setPageViews()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
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 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
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
 *
29
 * @since 0.1.1
30
 */
31
class Compiler extends BaseManager
32
{
33
    /** @var string|false */
34
    private $redirectTemplate;
35
36
    /** @var PageView[] */
37
    private $pageViews;
38
39
    /** @var Folder */
40
    private $folder;
41
42
    /** @var Twig_Environment */
43
    private $twig;
44
45 5
    public function __construct()
46
    {
47 5
        parent::__construct();
48
49 5
        $this->twig = TwigManager::getInstance();
50 5
    }
51
52
    /**
53
     * @param string|false $template
54
     */
55
    public function setRedirectTemplate($template)
56
    {
57
        $this->redirectTemplate = $template;
58
    }
59
60
    /**
61
     * @param Folder $folder
62
     */
63 5
    public function setTargetFolder(Folder $folder)
64
    {
65 5
        $this->folder = $folder;
66 5
    }
67
68
    /**
69
     * @param PageView[] $pageViews
70
     */
71 5
    public function setPageViews(array $pageViews)
72
    {
73 5
        $this->pageViews = $pageViews;
74 5
    }
75
76
    ///
77
    // IO Functionality
78
    ///
79
80
    /**
81
     * Compile all of the PageViews registered with the compiler.
82
     *
83
     * @since 0.1.0
84
     */
85 5
    public function compileAll()
86
    {
87 5
        foreach ($this->pageViews as &$pageView)
88
        {
89 5
            $this->compilePageView($pageView);
90 5
        }
91 5
    }
92
93
    /**
94
     * Compile an individual PageView item.
95
     *
96
     * This function will take care of determining *how* to treat the PageView and write the compiled output to a the
97
     * respective target file.
98
     *
99
     * @param DynamicPageView|RepeaterPageView|PageView $pageView The PageView that needs to be compiled
100
     *
101
     * @since 0.1.1
102
     */
103 5
    private function compilePageView(&$pageView)
104
    {
105 5
        switch ($pageView->getType())
106
        {
107 5
            case PageView::STATIC_TYPE:
108 5
                $this->compileStaticPageView($pageView);
109 5
                $this->compileStandardRedirects($pageView);
110 5
                break;
111
112
            case PageView::DYNAMIC_TYPE:
113
                $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...
114
                $this->compileStandardRedirects($pageView);
115
                break;
116
117
            case PageView::REPEATER_TYPE:
118
                $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...
119
                $this->compileExpandedRedirects($pageView);
120
                break;
121 5
        }
122 5
    }
123
124
    /**
125
     * Write the compiled output for a static PageView.
126
     *
127
     * @param PageView $pageView
128
     *
129
     * @since 0.1.1
130
     */
131 5
    private function compileStaticPageView(&$pageView)
132
    {
133 5
        $targetFile = $pageView->getTargetFile();
134 5
        $output = $this->renderStaticPageView($pageView);
135
136 5
        $this->output->notice('Writing file: {file}', array('file' => $targetFile));
137 5
        $this->folder->writeFile($targetFile, $output);
138 5
    }
139
140
    /**
141
     * Write the compiled output for a dynamic PageView.
142
     *
143
     * @param DynamicPageView $pageView
144
     *
145
     * @since 0.1.1
146
     */
147 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...
148
    {
149
        $contentItems = $pageView->getContentItems();
150
        $template = $this->createTwigTemplate($pageView);
151
152
        foreach ($contentItems as $contentItem)
153
        {
154
            $targetFile = $contentItem->getTargetFile();
155
            $output = $this->renderDynamicPageView($template, $pageView, $contentItem);
156
157
            $this->output->notice('Writing file: {file}', array('file' => $targetFile));
158
            $this->folder->writeFile($targetFile, $output);
159
        }
160
    }
161
162
    /**
163
     * Write the compiled output for a repeater PageView.
164
     *
165
     * @param RepeaterPageView $pageView
166
     *
167
     * @since 0.1.1
168
     */
169 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...
170
    {
171
        $pageView->rewindPermalink();
172
173
        $template = $this->createTwigTemplate($pageView);
174
        $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...
175
176
        foreach ($permalinks as $permalink)
177
        {
178
            $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...
179
            $targetFile = $pageView->getTargetFile();
180
            $output = $this->renderRepeaterPageView($template, $pageView, $permalink);
181
182
            $this->output->notice('Writing repeater file: {file}', array('file' => $targetFile));
183
            $this->folder->writeFile($targetFile, $output);
184
        }
185
    }
186
187
    ///
188
    // Redirect handling
189
    ///
190
191
    /**
192
     * Write redirects for standard redirects.
193
     *
194
     * @param PageView $pageView
195
     *
196
     * @since 0.1.1
197
     */
198 5
    private function compileStandardRedirects(&$pageView)
199
    {
200 5
        $redirects = $pageView->getRedirects();
201
202 5
        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...
203
        {
204
            $redirectPageView = PageView::createRedirect(
205
                $redirect,
206
                $pageView->getPermalink(),
207
                $this->redirectTemplate
208
            );
209
210
            $this->compilePageView($redirectPageView);
211 5
        }
212 5
    }
213
214
    /**
215
     * Write redirects for expanded redirects.
216
     *
217
     * @param RepeaterPageView $pageView
218
     *
219
     * @since 0.1.1
220
     */
221
    private function compileExpandedRedirects(&$pageView)
222
    {
223
        $permalinks = $pageView->getRepeaterPermalinks();
224
225
        /** @var ExpandedValue[] $repeaterRedirect */
226
        foreach ($pageView->getRepeaterRedirects() as $repeaterRedirect)
227
        {
228
            /**
229
             * @var int           $index
230
             * @var ExpandedValue $redirect
231
             */
232
            foreach ($repeaterRedirect as $index => $redirect)
233
            {
234
                $redirectPageView = PageView::createRedirect(
235
                    $redirect->getEvaluated(),
236
                    $permalinks[$index]->getEvaluated(),
237
                    $this->redirectTemplate
238
                );
239
                $this->compilePageView($redirectPageView);
240
            }
241
        }
242
    }
243
244
    ///
245
    // Twig Functionality
246
    ///
247
248
    /**
249
     * Get the compiled HTML for a specific iteration of a repeater PageView.
250
     *
251
     * @param Twig_Template $template
252
     * @param PageView      $pageView
253
     * @param ExpandedValue $expandedValue
254
     *
255
     * @since  0.1.1
256
     *
257
     * @return string
258
     */
259
    private function renderRepeaterPageView(&$template, &$pageView, &$expandedValue)
260
    {
261
        $this->twig->addGlobal('__currentTemplate', $pageView->getFilePath());
262
263
        $pageView->setFrontMatter(array(
264
            'permalink' => $expandedValue->getEvaluated(),
265
            'iterators' => $expandedValue->getIterators(),
266
        ));
267
268
        return $template
269
            ->render(array(
270
                'this' => $pageView->createJail(),
271
            ));
272
    }
273
274
    /**
275
     * Get the compiled HTML for a specific ContentItem.
276
     *
277
     * @param Twig_Template $template
278
     * @param PageView      $pageView
279
     * @param ContentItem   $contentItem
280
     *
281
     * @since  0.1.1
282
     *
283
     * @return string
284
     */
285
    private function renderDynamicPageView(&$template, &$pageView, &$contentItem)
286
    {
287
        $this->twig->addGlobal('__currentTemplate', $pageView->getFilePath());
288
289
        return $template
290
            ->render(array(
291
                'this' => $contentItem->createJail(),
292
            ));
293
    }
294
295
    /**
296
     * Get the compiled HTML for a static PageView.
297
     *
298
     * @param PageView $pageView
299
     *
300
     * @since  0.1.1
301
     *
302
     * @throws \Exception
303
     * @throws \Throwable
304
     * @throws Twig_Error_Syntax
305
     *
306
     * @return string
307
     */
308 5
    private function renderStaticPageView(&$pageView)
309
    {
310 5
        $this->twig->addGlobal('__currentTemplate', $pageView->getFilePath());
311
312 5
        return $this
313 5
            ->createTwigTemplate($pageView)
314 5
            ->render(array(
315 5
                'this' => $pageView->createJail(),
316 5
            ));
317
    }
318
319
    /**
320
     * Create a Twig template that just needs an array to render.
321
     *
322
     * @param PageView $pageView The PageView whose body will be used for Twig compilation
323
     *
324
     * @since  0.1.1
325
     *
326
     * @throws \Exception
327
     * @throws \Throwable
328
     * @throws Twig_Error_Syntax
329
     *
330
     * @return Twig_Template
331
     */
332 5
    private function createTwigTemplate(&$pageView)
333
    {
334
        try
335
        {
336 5
            return $this->twig->createTemplate($pageView->getContent());
337
        }
338
        catch (Twig_Error_Syntax $e)
339
        {
340
            $e->setTemplateLine($e->getTemplateLine() + $pageView->getLineOffset());
341
            $e->setSourceContext(new Twig_Source(
342
                $pageView->getContent(),
343
                $pageView->getName(),
344
                $pageView->getRelativeFilePath()
345
            ));
346
347
            throw $e;
348
        }
349
    }
350
}
351