1<?php
2
3/*
4 * This file is part of Mustache.php.
5 *
6 * (c) 2010-2017 Justin Hileman
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/**
13 * Mustache template Filesystem Source.
14 *
15 * This template Source uses stat() to generate the Source key, so that using
16 * pre-compiled templates doesn't require hitting the disk to read the source.
17 * It is more suitable for production use, and is used by default in the
18 * ProductionFilesystemLoader.
19 */
20class Mustache_Source_FilesystemSource implements Mustache_Source
21{
22    private $fileName;
23    private $statProps;
24    private $stat;
25
26    /**
27     * Filesystem Source constructor.
28     *
29     * @param string $fileName
30     * @param array  $statProps
31     */
32    public function __construct($fileName, array $statProps)
33    {
34        $this->fileName = $fileName;
35        $this->statProps = $statProps;
36    }
37
38    /**
39     * Get the Source key (used to generate the compiled class name).
40     *
41     * @throws RuntimeException when a source file cannot be read
42     *
43     * @return string
44     */
45    public function getKey()
46    {
47        $chunks = array(
48            'fileName' => $this->fileName,
49        );
50
51        if (!empty($this->statProps)) {
52            if (!isset($this->stat)) {
53                $this->stat = @stat($this->fileName);
54            }
55
56            if ($this->stat === false) {
57                throw new RuntimeException(sprintf('Failed to read source file "%s".', $this->fileName));
58            }
59
60            foreach ($this->statProps as $prop) {
61                $chunks[$prop] = $this->stat[$prop];
62            }
63        }
64
65        return json_encode($chunks);
66    }
67
68    /**
69     * Get the template Source.
70     *
71     * @return string
72     */
73    public function getSource()
74    {
75        return file_get_contents($this->fileName);
76    }
77}
78