Completed
Push — develop ( a32047...d9f18e )
by Jens
03:00
created

HandlebarsCacheWarmer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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