TwigTemplateCacheWarmer::warmUp()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 13
cts 13
cp 1
rs 9.2
c 0
b 0
f 0
cc 3
eloc 13
nc 3
nop 1
crap 3
1
<?php
2
3
/*
4
 * This file is part of the puli/twig-puli-extension package.
5
 *
6
 * (c) Bernhard Schussek <[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
namespace Puli\TwigExtension\CacheWarmer;
13
14
use Puli\Repository\Api\ResourceRepository;
15
use Puli\Repository\Resource\Iterator\RecursiveResourceIteratorIterator;
16
use Puli\Repository\Resource\Iterator\ResourceCollectionIterator;
17
use Puli\Repository\Resource\Iterator\ResourceFilterIterator;
18
use RuntimeException;
19
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
20
use Twig_Environment;
21
use Twig_Error;
22
23
/**
24
 * Generates the Twig cache for all templates in the resource repository.
25
 *
26
 * @author Bernhard Schussek <[email protected]>
27
 */
28
class TwigTemplateCacheWarmer implements CacheWarmerInterface
29
{
30
    /**
31
     * @var ResourceRepository
32
     */
33
    private $repo;
34
35
    /**
36
     * @var string
37
     */
38
    private $suffix;
39
40
    /**
41
     * @var Twig_Environment
42
     */
43
    private $twig;
44
45 1
    public function __construct(ResourceRepository $repo, Twig_Environment $twig, $suffix = '.twig')
46
    {
47 1
        $this->repo = $repo;
48 1
        $this->suffix = $suffix;
49 1
        $this->twig = $twig;
50 1
    }
51
52
    /**
53
     * Warms up the cache.
54
     *
55
     * @param string $cacheDir The cache directory
56
     *
57
     * @throws RuntimeException If setEnvironment() wasn't called
58
     */
59 1
    public function warmUp($cacheDir)
60
    {
61 1
        $iterator = new ResourceFilterIterator(
62 1
            new RecursiveResourceIteratorIterator(
63 1
                new ResourceCollectionIterator(
64 1
                    $this->repo->get('/')->listChildren(),
65 1
                    ResourceCollectionIterator::CURRENT_AS_PATH
66
                ),
67 1
                RecursiveResourceIteratorIterator::SELF_FIRST
68
            ),
69 1
            $this->suffix,
70 1
            ResourceFilterIterator::FILTER_BY_NAME | ResourceFilterIterator::MATCH_SUFFIX
71
        );
72
73 1
        foreach ($iterator as $path) {
74
            try {
75 1
                $this->twig->loadTemplate($path);
76 1
            } catch (Twig_Error $e) {
77
                // Problem during compilation, stop
78
            }
79
        }
80 1
    }
81
82
    /**
83
     * Returns whether this warmer is optional or not.
84
     *
85
     * @return bool always true
86
     */
87
    public function isOptional()
88
    {
89
        return true;
90
    }
91
}
92