Passed
Push — master ( 72c793...7f699f )
by Kirill
03:22
created

ViewCache   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 64
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 7 2
A reset() 0 8 2
A resetPath() 0 4 2
A has() 0 3 1
A set() 0 3 1
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Views;
13
14
use Spiral\Views\Exception\CacheException;
15
16
final class ViewCache
17
{
18
    /** @var array */
19
    private $cache = [];
20
21
    /**
22
     * @param ContextInterface|null $context
23
     */
24
    public function reset(ContextInterface $context = null): void
25
    {
26
        if (empty($context)) {
27
            $this->cache = [];
28
            return;
29
        }
30
31
        unset($this->cache[$context->getID()]);
32
    }
33
34
    /**
35
     * Reset view cache from all the contexts.
36
     *
37
     * @param string $path
38
     */
39
    public function resetPath(string $path): void
40
    {
41
        foreach ($this->cache as &$cache) {
42
            unset($cache[$path], $cache);
43
        }
44
    }
45
46
    /**
47
     * @param ContextInterface $context
48
     * @param string           $path
49
     * @return bool
50
     */
51
    public function has(ContextInterface $context, string $path): bool
52
    {
53
        return isset($this->cache[$context->getID()][$path]);
54
    }
55
56
    /**
57
     * @param ContextInterface $context
58
     * @param string           $path
59
     * @param ViewInterface    $view
60
     */
61
    public function set(ContextInterface $context, string $path, ViewInterface $view): void
62
    {
63
        $this->cache[$context->getID()][$path] = $view;
64
    }
65
66
    /**
67
     * @param ContextInterface $context
68
     * @param string           $path
69
     * @return ViewInterface
70
     *
71
     * @throws CacheException
72
     */
73
    public function get(ContextInterface $context, string $path): ViewInterface
74
    {
75
        if (!$this->has($context, $path)) {
76
            throw new CacheException("No cache is available for {$path}.");
77
        }
78
79
        return $this->cache[$context->getID()][$path];
80
    }
81
}
82