HandlebarsCacheWarmer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 5
cts 5
cp 1
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 1
1
<?php
2
/**
3
 * @author @jenschude <[email protected]>
4
 */
5
6
7
namespace JaySDe\HandlebarsBundle\CacheWarmer;
8
9
use JaySDe\HandlebarsBundle\HandlebarsEngine;
10
use JaySDe\HandlebarsBundle\HandlebarsEnvironment;
11
use Psr\Log\LoggerInterface;
12
use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinderInterface;
13
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
14
15
class HandlebarsCacheWarmer implements CacheWarmerInterface
16
{
17
    private $environment;
18
    private $finder;
19
    private $logger;
20
21
    /**
22
     * Constructor.
23
     *
24
     * @param HandlebarsEngine $environment The handlebars engine
25
     * @param TemplateFinderInterface $finder The template paths cache warmer
26
     * @param LoggerInterface $logger
27
     */
28 3
    public function __construct(
29
        HandlebarsEnvironment $environment,
30
        TemplateFinderInterface $finder,
31
        LoggerInterface $logger = null
32
    ) {
33
        // We don't inject the HandlebarsEngine directly as it depends on the
34
        // template locator (via the loader) which might be a cached one.
35
        // The cached template locator is available once the TemplatePathsCacheWarmer
36
        // has been warmed up
37 3
        $this->environment = $environment;
38 3
        $this->finder = $finder;
39 3
        $this->logger = $logger;
40 3
    }
41
    /**
42
     * Warms up the cache.
43
     *
44
     * @param string $cacheDir The cache directory
45
     */
46 2
    public function warmUp($cacheDir)
47
    {
48 2
        $environment = $this->environment;
49 2
        foreach ($this->finder->findAllTemplates() as $template) {
50 2
            if (!in_array($template->get('engine'), ['hbs', 'handlebars'])) {
51 1
                continue;
52
            }
53
            try {
54 2
                $environment->compile($template);
55 1
            } catch (\Exception $e) {
56
                // problem during compilation, log it and give up
57 1
                if ($this->logger instanceof LoggerInterface) {
58 1
                    $this->logger->warning(
59 1
                        sprintf(
60 1
                            'Failed to compile Handlebars template "%s": "%s"',
61 1
                            (string) $template,
62 2
                            $e->getMessage()
63
                        )
64
                    );
65
                }
66
            }
67
        }
68 2
    }
69
70
    /**
71
     * Checks whether this warmer is optional or not.
72
     *
73
     * @return Boolean always true
74
     */
75 1
    public function isOptional()
76
    {
77 1
        return true;
78
    }
79
}
80