xref: /webtrees/app/Factories/TimestampFactory.php (revision 202c018b592d5a516e4a465dc6dc515f3be37399)
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\Auth;
23use Fisharebest\Webtrees\Contracts\TimestampFactoryInterface;
24use Fisharebest\Webtrees\Contracts\TimestampInterface;
25use Fisharebest\Webtrees\Contracts\UserInterface;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Site;
28use Fisharebest\Webtrees\Timestamp;
29use InvalidArgumentException;
30
31use function date;
32use function date_create_from_format;
33use function time;
34
35/**
36 * Create a timestamp object.
37 */
38class TimestampFactory implements TimestampFactoryInterface
39{
40    /**
41     * @param int                $timestamp
42     * @param UserInterface|null $user
43     *
44     * @return TimestampInterface
45     */
46    public function make(int $timestamp, UserInterface|null $user = null): TimestampInterface
47    {
48        $user     ??= Auth::user();
49        $timezone = $user->getPreference(UserInterface::PREF_TIME_ZONE, Site::getPreference('TIMEZONE'));
50        $locale   = I18N::locale()->code();
51
52        return new Timestamp($timestamp, $timezone, $locale);
53    }
54
55    /**
56     * @param string|null        $string YYYY-MM-DD HH:MM:SS (as provided by SQL).
57     * @param string             $format
58     * @param UserInterface|null $user
59     *
60     * @return TimestampInterface
61     */
62    public function fromString(string|null $string, string $format = 'Y-m-d H:i:s', UserInterface|null $user = null): TimestampInterface
63    {
64        $string    ??= date($format);
65        $timestamp = date_create_from_format($format, $string);
66
67        if ($timestamp === false) {
68            throw new InvalidArgumentException('date/time "' . $string . '" does not match pattern "' . $format . '"');
69        }
70
71        return $this->make($timestamp->getTimestamp(), $user);
72    }
73
74    /**
75     * @param UserInterface|null $user
76     *
77     * @return TimestampInterface
78     */
79    public function now(UserInterface|null $user = null): TimestampInterface
80    {
81        return $this->make(time(), $user);
82    }
83}
84