xref: /webtrees/app/Factories/CacheFactory.php (revision a9b613b19a7bebd6295716a08ffb33e94a76bd34)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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    private ArrayAdapter $array_adapter;
43
44    private FilesystemAdapter $filesystem_adapter;
45
46    /**/
47    public function __construct()
48    {
49        $this->array_adapter      = new ArrayAdapter(0, false);
50        $this->filesystem_adapter = new FilesystemAdapter('', self::FILES_TTL, self::FILES_DIR);
51    }
52
53    /**
54     * Create an array-based cache.
55     *
56     * @return Cache
57     */
58    public function array(): Cache
59    {
60        return new Cache($this->array_adapter);
61    }
62
63    /**
64     * Create an file-based cache.
65     *
66     * @return Cache
67     */
68    public function file(): Cache
69    {
70        return new Cache($this->filesystem_adapter);
71    }
72
73    /**
74     * Perform garbage collection.
75     */
76    public function __destruct()
77    {
78        if (random_int(1, self::GC_PROBABILITY) === 1) {
79            $this->filesystem_adapter->prune();
80        }
81    }
82}
83