Issues (2500)

app/Services/TimeoutService.php (1 issue)

Labels
Severity
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2025 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
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Services;
21
22
use Fisharebest\Webtrees\Registry;
23
24
/**
25
 * Check for PHP timeouts.
26
 */
27
class TimeoutService
28
{
29
    //Long-running scripts run in small chunks
30
    private const float TIME_LIMIT = 1.5;
0 ignored issues
show
A parse error occurred: Syntax error, unexpected T_STRING, expecting '=' on line 30 at column 24
Loading history...
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
    public function __construct(
39
        private PhpService $php_service,
40
        float|null $start_time = null,
41
    ) {
42
        $this->start_time = $start_time ?? Registry::timeFactory()->now();
43
    }
44
45
    /**
46
     * Some long-running scripts need to know when to stop.
47
     */
48
    public function isTimeNearlyUp(float $threshold = self::TIME_UP_THRESHOLD): bool
49
    {
50
        $max_execution_time = $this->php_service->maxExecutionTime();
51
52
        // If there's no time limit, then we can't run out of time.
53
        if ($max_execution_time === 0) {
54
            return false;
55
        }
56
57
        $now = Registry::timeFactory()->now();
58
59
        return $now + $threshold > $this->start_time + (float) $max_execution_time;
60
    }
61
62
    /**
63
     * Some long-running scripts are broken down into small chunks.
64
     */
65
    public function isTimeLimitUp(float $limit = self::TIME_LIMIT): bool
66
    {
67
        $now = Registry::timeFactory()->now();
68
69
        return $now > $this->start_time + $limit;
70
    }
71
}
72