Passed
Push — master ( 933866...696755 )
by Greg
06:17
created

CacheFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 51
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A array() 0 3 1
A __destruct() 0 4 2
A file() 0 3 1
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2020 webtrees development team
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Factories;
21
22
use Fisharebest\Webtrees\Cache;
23
use Fisharebest\Webtrees\Contracts\CacheFactoryInterface;
24
use Fisharebest\Webtrees\Webtrees;
25
use Symfony\Component\Cache\Adapter\ArrayAdapter;
26
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
27
28
use function random_int;
29
30
/**
31
 * Make a cache.
32
 */
33
class CacheFactory implements CacheFactoryInterface
34
{
35
    // How frequently to perform garbage collection.
36
    private const GC_PROBABILITY = 1000;
37
38
    // Filesystem cache parameters.
39
    private const FILES_TTL = 8640000;
40
    private const FILES_DIR = Webtrees::DATA_DIR . 'cache/';
41
42
    /** @var ArrayAdapter */
43
    private $array_adapter;
44
45
    /** @var FilesystemAdapter */
46
    private $filesystem_adapter;
47
48
    /**
49
     * CacheFactory constructor.
50
     */
51
    public function __construct()
52
    {
53
        $this->array_adapter      = new ArrayAdapter(0, false);
54
        $this->filesystem_adapter = new FilesystemAdapter('', self::FILES_TTL, self::FILES_DIR);
55
    }
56
57
    /**
58
     * Create an array-based cache.
59
     *
60
     * @return Cache
61
     */
62
    public function array(): Cache
63
    {
64
        return new Cache($this->array_adapter);
65
    }
66
67
    /**
68
     * Create an file-based cache.
69
     *
70
     * @return Cache
71
     */
72
    public function file(): Cache
73
    {
74
        return new Cache($this->filesystem_adapter);
75
    }
76
77
    /**
78
     * Perform garbage collection.
79
     */
80
    public function __destruct()
81
    {
82
        if (random_int(1, self::GC_PROBABILITY) === 1) {
83
            $this->filesystem_adapter->prune();
84
        }
85
    }
86
}
87