xref: /webtrees/app/Services/TimeoutService.php (revision c908635b89a84d0a06f38a4d07640639e838703f)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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
22/**
23 * Check for PHP timeouts.
24 */
25class TimeoutService
26{
27    //Long-running scripts run in small chunks
28    private const TIME_LIMIT = 1.5;
29
30    // Seconds until we run out of time
31    private const TIME_UP_THRESHOLD = 3.0;
32
33    // The start time of the request
34    private float $start_time;
35
36    /**
37     * TimeoutService constructor.
38     *
39     * @param float|null $start_time
40     */
41    public function __construct(float $start_time = null)
42    {
43        $this->start_time = $start_time ?? microtime(true);
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 = microtime(true);
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 = microtime(true);
77
78        return $now > $this->start_time + $limit;
79    }
80}
81