Passed
Pull Request — master (#79)
by David
02:19
created

FileModificationTimeCacheValidatorTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
dl 0
loc 33
c 0
b 0
f 0
eloc 6
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A addTrackedFile() 0 3 1
A isValid() 0 8 3
1
<?php
2
3
4
namespace TheCodingMachine\GraphQL\Controllers\Cache;
5
6
use function filemtime;
7
8
/**
9
 * A trait that validates a cache item based on a file modification time
10
 */
11
trait FileModificationTimeCacheValidatorTrait
12
{
13
    /**
14
     * An array mapping the file name to its latest modification date.
15
     *
16
     * @var array<string, int>
17
     */
18
    protected $trackedFiles = [];
19
20
    /**
21
     * Adds a file to track.
22
     * All files must not have changed for the cache to be valid.
23
     *
24
     * @param string $fileName
25
     */
26
    public function addTrackedFile(string $fileName): void
27
    {
28
        $this->trackedFiles[$fileName] = filemtime($fileName);
29
    }
30
31
    /**
32
     * Returns true if this item is valid (coming out of cache), false otherwise.
33
     *
34
     * @return bool
35
     */
36
    public function isValid(): bool
37
    {
38
        foreach ($this->trackedFiles as $fileName => $mtime) {
39
            if (filemtime($fileName) !== $mtime) {
40
                return false;
41
            }
42
        }
43
        return true;
44
    }
45
}
46