xref: /webtrees/app/Factories/CacheFactory.php (revision 24f2a3af38709f9bf0a739b30264240d20ba34e8)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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 <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Factories;
21
22use Fisharebest\Webtrees\Cache;
23use Fisharebest\Webtrees\Contracts\CacheFactoryInterface;
24use Fisharebest\Webtrees\Webtrees;
25use Symfony\Component\Cache\Adapter\ArrayAdapter;
26use Symfony\Component\Cache\Adapter\FilesystemAdapter;
27
28use function random_int;
29
30/**
31 * Make a cache.
32 */
33class 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