Completed
Branch 09branch (31301e)
by Anton
02:42
created

StemplerCache   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 86
rs 10
c 0
b 0
f 0
wmc 7
lcom 1
cbo 2

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A withEnvironment() 0 7 1
A cacheFilename() 0 6 1
A timeCached() 0 13 3
A write() 0 9 1
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Views\Engines\Stempler;
10
11
use Spiral\Files\FilesInterface;
12
use Spiral\Views\EnvironmentInterface;
13
14
/**
15
 * Very simple Stempler cache. Almost identical to twig cache except generateKey method.
16
 */
17
class StemplerCache
18
{
19
    /**
20
     * @var FilesInterface
21
     */
22
    protected $files = null;
23
24
    /**
25
     * @var EnvironmentInterface
26
     */
27
    protected $environment = null;
28
29
    /**
30
     * @param EnvironmentInterface $environment
31
     * @param FilesInterface       $files
32
     */
33
    public function __construct(EnvironmentInterface $environment, FilesInterface $files)
34
    {
35
        $this->files = $files;
36
        $this->environment = $environment;
37
    }
38
39
    /**
40
     * @param EnvironmentInterface $environment
41
     *
42
     * @return StemplerCache
43
     */
44
    public function withEnvironment(EnvironmentInterface $environment): StemplerCache
45
    {
46
        $cache = clone $this;
47
        $cache->environment = $environment;
48
49
        return $cache;
50
    }
51
52
    /**
53
     * Generate cache filename for given path.
54
     *
55
     * @param string $path
56
     *
57
     * @return string
58
     */
59
    public function cacheFilename(string $path): string
60
    {
61
        $hash = hash('md5', $path . '.' . $this->environment->getID());
62
63
        return $this->environment->cacheDirectory() . $hash . '.php';
64
    }
65
66
    /**
67
     * Last update time.
68
     *
69
     * @param string $cacheFilename
70
     *
71
     * @return int
72
     */
73
    public function timeCached(string $cacheFilename): int
74
    {
75
        if (!$this->environment->isCachable()) {
76
            //Always expired
77
            return 0;
78
        }
79
80
        if ($this->files->exists($cacheFilename)) {
81
            return $this->files->time($cacheFilename);
82
        }
83
84
        return 0;
85
    }
86
87
    /**
88
     * Store data into cache.
89
     *
90
     * @param string $cacheFilename
91
     * @param string $content
92
     */
93
    public function write(string $cacheFilename, string $content)
94
    {
95
        $this->files->write(
96
            $cacheFilename,
97
            $content,
98
            FilesInterface::RUNTIME,
99
            true
100
        );
101
    }
102
}