Passed
Push — master ( 2b98ee...9e4ca2 )
by Eric
11:52
created

Template::pruneExpired()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * This file is part of Esi\SimpleTpl.
7
 *
8
 * (c) 2006 - 2024 Eric Sizemore <[email protected]>
9
 *
10
 * This file is licensed under The MIT License. For the full copyright and
11
 * license information, please view the LICENSE.md file that was distributed
12
 * with this source code.
13
 */
14
15
namespace Esi\SimpleTpl;
16
17
use InvalidArgumentException;
18
use LogicException;
19
use RuntimeException;
20
use Symfony\Component\Cache\Adapter\AdapterInterface;
21
use Symfony\Component\Cache\Adapter\AbstractAdapter;
22
use Symfony\Component\Cache\PruneableInterface;
23
24
use function array_keys;
25
use function array_map;
26
use function array_values;
27
use function file_get_contents;
28
use function is_file;
29
use function is_readable;
30
use function md5;
31
use function sprintf;
32
use function str_replace;
33
use function sys_get_temp_dir;
34
35
final class Template
36
{
37
    private AdapterInterface $cache;
38
39
    private string $leftDelimiter = '{';
40
41
    private string $rightDelimiter = '}';
42
43
    /**
44
     * @var array<string>
45
     */
46
    private array $tplVars = [];
47
48
    /**
49
     * Constructor.
50
     */
51 13
    public function __construct(?AdapterInterface $cacheAdapter = null, ?string $cachePath = null)
52
    {
53 13
        $this->cache = $cacheAdapter ?? AbstractAdapter::createSystemCache('simple_tpl', 300, '', $cachePath ?? sys_get_temp_dir());
54 13
        $this->pruneExpired();
55
    }
56
57 1
    public function clearCache(): bool
58
    {
59 1
        return $this->cache->clear();
60
    }
61
62 1
    public function display(string $tplFile): void
63
    {
64 1
        echo $this->parse($tplFile);
65
    }
66
67 1
    public function getLeftDelimiter(): string
68
    {
69 1
        return $this->leftDelimiter;
70
    }
71
72 1
    public function getRightDelimiter(): string
73
    {
74 1
        return $this->rightDelimiter;
75
    }
76
77
    /**
78
     * @return array<string>
79
     */
80 2
    public function getTplVars(): array
81
    {
82 2
        return $this->tplVars;
83
    }
84
85
    /**
86
     * @throws InvalidArgumentException if the file cannot be found or read.
87
     * @throws RuntimeException         if the file has no content.
88
     * @throws LogicException           if there are no template variables set.
89
     */
90 9
    public function parse(string $tplFile): string
91
    {
92
        // Make sure it's a valid file, and it exists
93 9
        if (!is_file($tplFile) || !is_readable($tplFile)) {
94 3
            throw new InvalidArgumentException(sprintf('"%s" does not exist or is not a file.', $tplFile));
95
        }
96
97 6
        $cacheKey = 'template_' . md5($tplFile);
98
99 6
        if ($this->cache->hasItem($cacheKey)) {
100
            /**
101
             * @var string $templateCache
102
             */
103 1
            $templateCache = $this->cache->getItem($cacheKey)->get();
104
105 1
            return $templateCache;
106
        }
107
108 5
        $contents = (string) file_get_contents($tplFile);
109
110
        // Make sure it has content.
111 5
        if ($contents === '') {
112 1
            throw new RuntimeException(sprintf('"%s" does not appear to have any valid content.', $tplFile));
113
        }
114
115 4
        if ($this->tplVars === []) {
116 1
            throw new LogicException('Unable to parse template, no tplVars found');
117
        }
118
119
        // Perform replacements
120 3
        $contents = str_replace(
121 3
            array_map(
122 3
                fn (int|string $find): string => sprintf('%s%s%s', $this->leftDelimiter, $find, $this->rightDelimiter),
123 3
                array_keys($this->tplVars)
124 3
            ),
125 3
            array_values($this->tplVars),
126 3
            $contents
127 3
        );
128
129 3
        $this->cache->save($this->cache->getItem($cacheKey)->set($contents));
130
131 3
        return $contents;
132
    }
133
134 13
    public function pruneExpired(): void
135
    {
136 13
        if ($this->cache instanceof PruneableInterface) {
137 12
            $this->cache->prune();
1 ignored issue
show
Bug introduced by
The method prune() does not exist on Symfony\Component\Cache\Adapter\AdapterInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Symfony\Component\Cache\...agAwareAdapterInterface or Symfony\Component\Cache\Adapter\NullAdapter or Symfony\Component\Cache\Adapter\ArrayAdapter or Symfony\Component\Cache\Adapter\AbstractAdapter or Symfony\Component\Cache\...AbstractTagAwareAdapter or Symfony\Component\Cache\...er\RedisTagAwareAdapter or Symfony\Component\Cache\Adapter\ApcuAdapter or Symfony\Component\Cache\Adapter\RedisAdapter or Symfony\Component\Cache\...\CouchbaseBucketAdapter or Symfony\Component\Cache\...chbaseCollectionAdapter or Symfony\Component\Cache\Adapter\MemcachedAdapter. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

137
            $this->cache->/** @scrutinizer ignore-call */ 
138
                          prune();
Loading history...
138
        }
139
    }
140
141 1
    public function refreshCache(string $tplFile): bool
142
    {
143 1
        $cacheKey = 'template_' . md5($tplFile);
144
145 1
        return $this->cache->deleteItem($cacheKey);
146
    }
147
148 1
    public function setLeftDelimiter(string $delimiter): void
149
    {
150 1
        $this->leftDelimiter = $delimiter;
151
    }
152
153 1
    public function setRightDelimiter(string $delimiter): void
154
    {
155 1
        $this->rightDelimiter = $delimiter;
156
    }
157
158
    /**
159
     * @param array<string> $tplVars Template variables and replacements
160
     */
161 7
    public function setTplVars(array $tplVars): void
162
    {
163 7
        $this->tplVars = $tplVars;
164
    }
165
}
166