Completed
Pull Request — master (#75)
by Vladimir
02:18
created

Compiler::buildDynamicPageViewHTML()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19

Duplication

Lines 19
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 19
loc 19
ccs 0
cts 9
cp 0
rs 9.6333
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx;
9
10
use allejo\stakx\Document\BasePageView;
11
use allejo\stakx\Document\CollectableItem;
12
use allejo\stakx\Document\ContentItem;
13
use allejo\stakx\Document\DynamicPageView;
14
use allejo\stakx\Document\PermalinkDocument;
15
use allejo\stakx\Document\RepeaterPageView;
16
use allejo\stakx\Document\StaticPageView;
17
use allejo\stakx\Document\TemplateReadyDocument;
18
use allejo\stakx\Event\CompileProcessPostRenderPageView;
19
use allejo\stakx\Event\CompileProcessPreRenderPageView;
20
use allejo\stakx\Event\CompileProcessTemplateCreation;
21
use allejo\stakx\Exception\FileAwareException;
22
use allejo\stakx\Filesystem\Folder;
23
use allejo\stakx\FrontMatter\ExpandedValue;
24
use allejo\stakx\Manager\CollectionManager;
25
use allejo\stakx\Manager\DataManager;
26
use allejo\stakx\Manager\MenuManager;
27
use allejo\stakx\Manager\PageManager;
28
use allejo\stakx\Templating\TemplateBridgeInterface;
29
use allejo\stakx\Templating\TemplateErrorInterface;
30
use allejo\stakx\Templating\TemplateInterface;
31
use Psr\Log\LoggerInterface;
32
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
33
34
/**
35
 * This class takes care of rendering the Twig body of PageViews with the respective information and it also takes care
36
 * of writing the rendered Twig to the filesystem.
37
 *
38
 * @since 0.1.1
39
 */
40
class Compiler
41
{
42
    /** @var string|false */
43
    private $redirectTemplate;
44
45
    /**
46
     * All of the PageViews handled by this Compiler instance indexed by their file paths relative to the site root.
47
     *
48
     * ```
49
     * array['_pages/index.html.twig'] = &PageView;
50
     * ```
51
     *
52
     * @var BasePageView[]
53
     */
54
    private $pageViewsFlattened;
55
56
    /** @var string[] */
57
    private $templateMapping;
58
59
    /** @var Folder */
60
    private $folder;
61
62
    /** @var string */
63
    private $theme;
64
65
    private $templateBridge;
66
    private $pageManager;
67
    private $eventDispatcher;
68
    private $configuration;
69
70 12
    public function __construct(
71
        TemplateBridgeInterface $templateBridge,
72
        Configuration $configuration,
73
        CollectionManager $collectionManager,
74
        DataManager $dataManager,
75
        MenuManager $menuManager,
76
        PageManager $pageManager,
77
        EventDispatcherInterface $eventDispatcher,
78
        LoggerInterface $logger
79
    ) {
80 12
        $this->templateBridge = $templateBridge;
81 12
        $this->theme = '';
82 12
        $this->pageManager = $pageManager;
83 12
        $this->eventDispatcher = $eventDispatcher;
84 12
        $this->logger = $logger;
0 ignored issues
show
Bug introduced by
The property logger does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
85 12
        $this->configuration = $configuration;
86
87 12
        $this->pageViewsFlattened = &$pageManager->getPageViewsFlattened();
88 12
        $this->redirectTemplate = $this->configuration->getRedirectTemplate();
89
90
        // Global variables maintained by stakx
91 12
        $this->templateBridge->setGlobalVariable('site', $configuration->getConfiguration());
92 12
        $this->templateBridge->setGlobalVariable('data', $dataManager->getJailedDataItems());
93 12
        $this->templateBridge->setGlobalVariable('collections', $collectionManager->getJailedCollections());
94 12
        $this->templateBridge->setGlobalVariable('menu', $menuManager->getSiteMenu());
95 12
        $this->templateBridge->setGlobalVariable('pages', $pageManager->getJailedStaticPageViews());
96 12
    }
97
98
    /**
99
     * @param Folder $folder
100
     */
101 12
    public function setTargetFolder(Folder $folder)
102
    {
103 12
        $this->folder = $folder;
104 12
    }
105
106
    /**
107
     * @param string $themeName
108
     */
109
    public function setThemeName($themeName)
110
    {
111
        $this->theme = $themeName;
112
    }
113
114
    ///
115
    // Twig parent templates
116
    ///
117
118
    public function getTemplateMappings()
119
    {
120
        return $this->templateMapping;
121
    }
122
123
    ///
124
    // Rendering HTML Functionality
125
    ///
126
127
    /**
128
     * Get the HTML for a Static PageView.
129
     *
130
     * This function just **renders** the HTML but does not write it to the filesystem. Use `compilePageView()` for that
131
     * instead.
132
     *
133
     * @param StaticPageView $pageView
134
     *
135
     * @throws TemplateErrorInterface
136
     *
137
     * @return string The HTML for a Static PageView.
138
     */
139 10
    public function renderStaticPageView(StaticPageView $pageView)
140
    {
141 10
        $pageView->compile();
142
143 10
        return $this->buildStaticPageViewHTML($pageView);
144
    }
145
146
    /**
147
     * Get the HTML for a Dynamic PageView and ContentItem.
148
     *
149
     * This function just **renders** the HTML but does not write it to the filesystem. Use `compileDynamicPageView()`
150
     * for that instead.
151
     *
152
     * @param DynamicPageView       $pageView
153
     * @param TemplateReadyDocument $contentItem
154
     *
155
     * @throws TemplateErrorInterface
156
     *
157
     * @return string
158
     */
159
    public function renderDynamicPageView(DynamicPageView $pageView, TemplateReadyDocument $contentItem)
160
    {
161
        $template = $this->createTwigTemplate($pageView);
162
163
        return $this->buildDynamicPageViewHTML($template, $contentItem);
164
    }
165
166
    ///
167
    // IO Functionality
168
    ///
169
170
    /**
171
     * Compile all of the PageViews registered with the compiler.
172
     *
173
     * @since 0.1.0
174
     */
175 12
    public function compileAll()
176
    {
177 12
        foreach ($this->pageViewsFlattened as &$pageView)
178
        {
179 12
            $this->compilePageView($pageView);
180
        }
181 12
    }
182
183
    /**
184
     * Compile an individual PageView item.
185
     *
186
     * This function will take care of determining *how* to treat the PageView and write the compiled output to a the
187
     * respective target file.
188
     *
189
     * @param DynamicPageView|RepeaterPageView|StaticPageView $pageView The PageView that needs to be compiled
0 ignored issues
show
Documentation introduced by
Should the type for parameter $pageView not be BasePageView?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
190
     *
191
     * @since 0.1.1
192
     */
193 12
    public function compilePageView(BasePageView &$pageView)
194
    {
195 12
        $this->templateBridge->setGlobalVariable('__currentTemplate', $pageView->getAbsoluteFilePath());
196 12
        $this->logger->debug('Compiling {type} PageView: {pageview}', [
197 12
            'pageview' => $pageView->getRelativeFilePath(),
198 12
            'type' => $pageView->getType(),
199
        ]);
200
201
        try
202
        {
203 12
            switch ($pageView->getType())
204
            {
205 12
                case BasePageView::STATIC_TYPE:
206 10
                    $this->compileStaticPageView($pageView);
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Document\BasePageView> is not a sub-type of object<allejo\stakx\Document\StaticPageView>. It seems like you assume a child class of the class allejo\stakx\Document\BasePageView 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...
207 10
                    $this->compileStandardRedirects($pageView);
208 10
                    break;
209
210 3
                case BasePageView::DYNAMIC_TYPE:
211
                    $this->compileDynamicPageView($pageView);
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Document\BasePageView> is not a sub-type of object<allejo\stakx\Document\DynamicPageView>. It seems like you assume a child class of the class allejo\stakx\Document\BasePageView 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...
212
                    $this->compileStandardRedirects($pageView);
213
                    break;
214
215 3
                case BasePageView::REPEATER_TYPE:
216 3
                    $this->compileRepeaterPageView($pageView);
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Document\BasePageView> is not a sub-type of object<allejo\stakx\Document\RepeaterPageView>. It seems like you assume a child class of the class allejo\stakx\Document\BasePageView 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...
217 3
                    $this->compileExpandedRedirects($pageView);
218 12
                    break;
219
            }
220
        }
221
        catch (TemplateErrorInterface $e)
222
        {
223
            throw new FileAwareException(
224
                $e->getMessage(),
225
                $e->getCode(),
226
                $e,
227
                $pageView->getRelativeFilePath(),
228
                $e->getTemplateLine() + $pageView->getLineOffset()
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface allejo\stakx\Document\PermalinkDocument as the method getLineOffset() does only exist in the following implementations of said interface: allejo\stakx\Document\BasePageView, allejo\stakx\Document\ContentItem, allejo\stakx\Document\DynamicPageView, allejo\stakx\Document\PermalinkFrontMatterDocument, allejo\stakx\Document\RepeaterPageView, allejo\stakx\Document\StaticPageView.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
229
            );
230
        }
231 12
    }
232
233
    /**
234
     * Write the compiled output for a static PageView.
235
     *
236
     * @since 0.1.1
237
     *
238
     * @throws TemplateErrorInterface
239
     */
240 10
    private function compileStaticPageView(StaticPageView &$pageView)
241
    {
242 10
        $this->writeToFilesystem(
243 10
            $pageView->getTargetFile(),
244 10
            $this->renderStaticPageView($pageView),
245 10
            BasePageView::STATIC_TYPE
246
        );
247 10
    }
248
249
    /**
250
     * Write the compiled output for a dynamic PageView.
251
     *
252
     * @param DynamicPageView $pageView
253
     *
254
     * @since 0.1.1
255
     *
256
     * @throws TemplateErrorInterface
257
     */
258
    private function compileDynamicPageView(DynamicPageView &$pageView)
259
    {
260
        $contentItems = $pageView->getCollectableItems();
261
        $template = $this->createTwigTemplate($pageView);
262
263
        foreach ($contentItems as &$contentItem)
264
        {
265
            if ($contentItem->isDraft() && !Service::hasRunTimeFlag(RuntimeStatus::USING_DRAFTS))
266
            {
267
                $this->logger->debug('{file}: marked as a draft', [
268
                    'file' => $contentItem->getRelativeFilePath(),
269
                ]);
270
271
                continue;
272
            }
273
274
            $this->writeToFilesystem(
275
                $contentItem->getTargetFile(),
276
                $this->buildDynamicPageViewHTML($template, $contentItem),
0 ignored issues
show
Documentation introduced by
$contentItem is of type object<allejo\stakx\Document\CollectableItem>, but the function expects a object<allejo\stakx\Docu...\TemplateReadyDocument>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
277
                BasePageView::DYNAMIC_TYPE
278
            );
279
280
            $this->compileStandardRedirects($contentItem);
0 ignored issues
show
Documentation introduced by
$contentItem is of type object<allejo\stakx\Docu...\TemplateReadyDocument>, but the function expects a object<allejo\stakx\Document\PermalinkDocument>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
281
        }
282
    }
283
284
    /**
285
     * Write the compiled output for a repeater PageView.
286
     *
287
     * @param RepeaterPageView $pageView
288
     *
289
     * @since 0.1.1
290
     *
291
     * @throws TemplateErrorInterface
292
     */
293 3
    private function compileRepeaterPageView(RepeaterPageView &$pageView)
294
    {
295 3
        $pageView->rewindPermalink();
296
297 3
        $template = $this->createTwigTemplate($pageView);
298 3
        $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\Document\BasePageView as the method getRepeaterPermalinks() does only exist in the following sub-classes of allejo\stakx\Document\BasePageView: allejo\stakx\Document\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...
299
300 3
        foreach ($permalinks as $permalink)
301
        {
302 3
            $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\Document\BasePageView as the method bumpPermalink() does only exist in the following sub-classes of allejo\stakx\Document\BasePageView: allejo\stakx\Document\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...
303
304 3
            $this->writeToFilesystem(
305 3
                $pageView->getTargetFile(),
306 3
                $this->buildRepeaterPageViewHTML($template, $pageView, $permalink),
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Document\BasePageView> is not a sub-type of object<allejo\stakx\Document\RepeaterPageView>. It seems like you assume a child class of the class allejo\stakx\Document\BasePageView 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...
307 3
                BasePageView::REPEATER_TYPE
308
            );
309
        }
310 3
    }
311
312
    /**
313
     * Write the given $output to the $targetFile as a $fileType PageView.
314
     *
315
     * @param string $targetFile
316
     * @param string $output
317
     * @param string $fileType
318
     */
319 12
    private function writeToFilesystem($targetFile, $output, $fileType)
320
    {
321 12
        $this->logger->notice('Writing {type} PageView file: {file}', [
322 12
            'type' => $fileType,
323 12
            'file' => $targetFile,
324
        ]);
325 12
        $this->folder->writeFile($targetFile, $output);
326 12
    }
327
328
    ///
329
    // Redirect handling
330
    ///
331
332
    /**
333
     * Write redirects for standard redirects.
334
     *
335
     * @throws TemplateErrorInterface
336
     *
337
     * @since 0.1.1
338
     */
339 10
    private function compileStandardRedirects(PermalinkDocument &$pageView)
340
    {
341 10
        $redirects = $pageView->getRedirects();
342
343 10 View Code Duplication
        foreach ($redirects as $redirect)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
344
        {
345 1
            $redirectPageView = BasePageView::createRedirect(
346 1
                $redirect,
347 1
                $pageView->getPermalink(),
348 1
                $this->redirectTemplate
349
            );
350 1
            $redirectPageView->evaluateFrontMatter([], [
351 1
                'site' => $this->configuration->getConfiguration(),
352
            ]);
353
354 1
            $this->compileStaticPageView($redirectPageView);
355
        }
356 10
    }
357
358
    /**
359
     * Write redirects for expanded redirects.
360
     *
361
     * @param RepeaterPageView $pageView
362
     *
363
     * @since 0.1.1
364
     */
365 3
    private function compileExpandedRedirects(RepeaterPageView &$pageView)
366
    {
367 3
        $permalinks = $pageView->getRepeaterPermalinks();
368
369
        /** @var ExpandedValue[] $repeaterRedirect */
370 3
        foreach ($pageView->getRepeaterRedirects() as $repeaterRedirect)
371
        {
372
            /**
373
             * @var int
374
             * @var ExpandedValue $redirect
375
             */
376 1 View Code Duplication
            foreach ($repeaterRedirect as $index => $redirect)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
377
            {
378 1
                $redirectPageView = BasePageView::createRedirect(
379 1
                    $redirect->getEvaluated(),
380 1
                    $permalinks[$index]->getEvaluated(),
381 1
                    $this->redirectTemplate
382
                );
383 1
                $redirectPageView->evaluateFrontMatter([], [
384 1
                    'site' => $this->configuration->getConfiguration(),
385
                ]);
386
387 1
                $this->compilePageView($redirectPageView);
388
            }
389
        }
390 3
    }
391
392
    ///
393
    // Twig Functionality
394
    ///
395
396
    /**
397
     * Get the compiled HTML for a specific iteration of a repeater PageView.
398
     *
399
     * @param TemplateInterface $template
400
     * @param RepeaterPageView  $pageView
401
     * @param ExpandedValue     $expandedValue
402
     *
403
     * @since  0.1.1
404
     *
405
     * @return string
406
     */
407 3
    private function buildRepeaterPageViewHTML(TemplateInterface &$template, RepeaterPageView &$pageView, ExpandedValue &$expandedValue)
408
    {
409
        $defaultContext = [
410 3
            'this' => $pageView->createJail(),
411
        ];
412
413 3
        $pageView->evaluateFrontMatter([
414 3
            'permalink' => $expandedValue->getEvaluated(),
415 3
            'iterators' => $expandedValue->getIterators(),
416
        ]);
417
418 3
        $preEvent = new CompileProcessPreRenderPageView(BasePageView::REPEATER_TYPE);
419 3
        $this->eventDispatcher->dispatch(CompileProcessPreRenderPageView::NAME, $preEvent);
420
421 3
        $context = array_merge($preEvent->getCustomVariables(), $defaultContext);
422
        $output = $template
423 3
            ->render($context)
424
        ;
425
426 3
        $postEvent = new CompileProcessPostRenderPageView(BasePageView::REPEATER_TYPE, $output);
427 3
        $this->eventDispatcher->dispatch(CompileProcessPostRenderPageView::NAME, $postEvent);
428
429 3
        return $postEvent->getCompiledOutput();
430
    }
431
432
    /**
433
     * Get the compiled HTML for a specific ContentItem.
434
     *
435
     * @since  0.1.1
436
     *
437
     * @return string
438
     */
439 View Code Duplication
    private function buildDynamicPageViewHTML(TemplateInterface &$template, TemplateReadyDocument &$twigItem)
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...
440
    {
441
        $defaultContext = [
442
            'this' => $twigItem->createJail(),
443
        ];
444
445
        $preEvent = new CompileProcessPreRenderPageView(BasePageView::DYNAMIC_TYPE);
446
        $this->eventDispatcher->dispatch(CompileProcessPreRenderPageView::NAME, $preEvent);
447
448
        $context = array_merge($preEvent->getCustomVariables(), $defaultContext);
449
        $output = $template
450
            ->render($context)
451
        ;
452
453
        $postEvent = new CompileProcessPostRenderPageView(BasePageView::DYNAMIC_TYPE, $output);
454
        $this->eventDispatcher->dispatch(CompileProcessPostRenderPageView::NAME, $postEvent);
455
456
        return $postEvent->getCompiledOutput();
457
    }
458
459
    /**
460
     * Get the compiled HTML for a static PageView.
461
     *
462
     * @since  0.1.1
463
     *
464
     * @throws TemplateErrorInterface
465
     *
466
     * @return string
467
     */
468 10 View Code Duplication
    private function buildStaticPageViewHTML(StaticPageView &$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...
469
    {
470
        $defaultContext = [
471 10
            'this' => $pageView->createJail(),
472
        ];
473
474 10
        $preEvent = new CompileProcessPreRenderPageView(BasePageView::STATIC_TYPE);
475 10
        $this->eventDispatcher->dispatch(CompileProcessPreRenderPageView::NAME, $preEvent);
476
477 10
        $context = array_merge($preEvent->getCustomVariables(), $defaultContext);
478
        $output = $this
479 10
            ->createTwigTemplate($pageView)
480 10
            ->render($context)
481
        ;
482
483 10
        $postEvent = new CompileProcessPostRenderPageView(BasePageView::STATIC_TYPE, $output);
484 10
        $this->eventDispatcher->dispatch(CompileProcessPostRenderPageView::NAME, $postEvent);
485
486 10
        return $postEvent->getCompiledOutput();
487
    }
488
489
    /**
490
     * Create a Twig template that just needs an array to render.
491
     *
492
     * @since  0.1.1
493
     *
494
     * @throws TemplateErrorInterface
495
     *
496
     * @return TemplateInterface
497
     */
498 12
    private function createTwigTemplate(BasePageView &$pageView)
499
    {
500
        try
501
        {
502 12
            $template = $this->templateBridge->createTemplate($pageView->getContent());
503
504 12
            $this->templateMapping[$template->getTemplateName()] = $pageView->getRelativeFilePath();
505
506 12
            $event = new CompileProcessTemplateCreation($pageView, $template, $this->theme);
507 12
            $this->eventDispatcher->dispatch(CompileProcessTemplateCreation::NAME, $event);
508
509 12
            return $template;
510
        }
511
        catch (TemplateErrorInterface $e)
512
        {
513
            $e
514
                ->setTemplateLine($e->getTemplateLine() + $pageView->getLineOffset())
515
                ->setContent($pageView->getContent())
516
                ->setName($pageView->getRelativeFilePath())
517
                ->setRelativeFilePath($pageView->getRelativeFilePath())
518
                ->buildException()
519
            ;
520
521
            throw $e;
522
        }
523
    }
524
}
525