xref: /webtrees/app/Services/TimeoutService.php (revision e873f434551745f888937263ff89e80db3b0f785)
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\Services;
21
22use Fisharebest\Webtrees\Registry;
23
24/**
25 * Check for PHP timeouts.
26 */
27class TimeoutService
28{
29    //Long-running scripts run in small chunks
30    private const float TIME_LIMIT = 1.5;
31
32    // Seconds until we run out of time
33    private const float TIME_UP_THRESHOLD = 3.0;
34
35    // The start time of the request
36    private float $start_time;
37
38    /**
39     * @param float|null $start_time
40     */
41    public function __construct(float|null $start_time = null)
42    {
43        $this->start_time = $start_time ?? Registry::timeFactory()->now();
44    }
45
46    /**
47     * Some long-running scripts need to know when to stop.
48     *
49     * @param float $threshold
50     *
51     * @return bool
52     */
53    public function isTimeNearlyUp(float $threshold = self::TIME_UP_THRESHOLD): bool
54    {
55        $max_execution_time = (int) ini_get('max_execution_time');
56
57        // If there's no time limit, then we can't run out of time.
58        if ($max_execution_time === 0) {
59            return false;
60        }
61
62        $now = Registry::timeFactory()->now();
63
64        return $now + $threshold > $this->start_time + (float) $max_execution_time;
65    }
66
67    /**
68     * Some long-running scripts are broken down into small chunks.
69     *
70     * @param float $limit
71     *
72     * @return bool
73     */
74    public function isTimeLimitUp(float $limit = self::TIME_LIMIT): bool
75    {
76        $now = Registry::timeFactory()->now();
77
78        return $now > $this->start_time + $limit;
79    }
80}
81