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 * CacheFactory constructor. 48 */ 49 public function __construct() 50 { 51 $this->array_adapter = new ArrayAdapter(0, false); 52 $this->filesystem_adapter = new FilesystemAdapter('', self::FILES_TTL, self::FILES_DIR); 53 } 54 55 /** 56 * Create an array-based cache. 57 * 58 * @return Cache 59 */ 60 public function array(): Cache 61 { 62 return new Cache($this->array_adapter); 63 } 64 65 /** 66 * Create an file-based cache. 67 * 68 * @return Cache 69 */ 70 public function file(): Cache 71 { 72 return new Cache($this->filesystem_adapter); 73 } 74 75 /** 76 * Perform garbage collection. 77 */ 78 public function __destruct() 79 { 80 if (random_int(1, self::GC_PROBABILITY) === 1) { 81 $this->filesystem_adapter->prune(); 82 } 83 } 84} 85