xref: /webtrees/app/Services/TimeoutService.php (revision 00b1984e374faddab4698e73088f0c964e529b65)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22use Psr\Http\Message\ServerRequestInterface;
23
24use function app;
25
26/**
27 * Check for PHP timeouts.
28 */
29class TimeoutService
30{
31    /** @var float Long-running scripts run in small chunks */
32    private const TIME_LIMIT = 1.5;
33
34    /** @var float Seconds until we run out of time */
35    private const TIME_UP_THRESHOLD = 3.0;
36
37    /** @var float|null The start time of the request */
38    private $start_time;
39
40    /**
41     * TimeoutService constructor.
42     *
43     * @param float $start_time
44     */
45    public function __construct(float $start_time = null)
46    {
47        $this->start_time = $start_time ?? microtime(true);
48    }
49
50    /**
51     * Some long-running scripts need to know when to stop.
52     *
53     * @param float $threshold
54     *
55     * @return bool
56     */
57    public function isTimeNearlyUp(float $threshold = self::TIME_UP_THRESHOLD): bool
58    {
59        $max_execution_time = (int) ini_get('max_execution_time');
60
61        // If there's no time limit, then we can't run out of time.
62        if ($max_execution_time === 0) {
63            return false;
64        }
65
66        $now = microtime(true);
67
68        return $now + $threshold > $this->start_time + (float) $max_execution_time;
69    }
70
71    /**
72     * Some long running scripts are broken down into small chunks.
73     *
74     * @param float $limit
75     *
76     * @return bool
77     */
78    public function isTimeLimitUp(float $limit = self::TIME_LIMIT): bool
79    {
80        $now = microtime(true);
81
82        return $now > $this->start_time + $limit;
83    }
84
85    /**
86     * @return float
87     */
88    protected function startTime(): float
89    {
90        if ($this->start_time === null) {
91            $request = app(ServerRequestInterface::class);
92
93            $this->start_time = (float) ($request->getServerParams()['REQUEST_TIME_FLOAT'] ?? microtime(true));
94        }
95
96        return $this->start_time;
97    }
98}
99