Completed
Branch feature/phpstanLevel3 (de378e)
by Schlaefer
02:30
created

LastRefreshDatabase::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Saito - The Threaded Web Forum
7
 *
8
 * @copyright Copyright (c) the Saito Project Developers
9
 * @link https://github.com/Schlaefer/Saito
10
 * @license http://opensource.org/licenses/MIT
11
 */
12
13
namespace Saito\User\LastRefresh;
14
15
use App\Model\Table\UsersTable;
16
use DateTimeInterface;
17
use Saito\RememberTrait;
18
use Saito\User\CurrentUser\CurrentUserInterface;
19
20
/**
21
 * handles last refresh time for current user via database
22
 *
23
 * used for logged-in users
24
 */
25
class LastRefreshDatabase extends LastRefreshAbstract
26
{
27
    use RememberTrait;
28
29
    /**
30
     * @var UsersTable
31
     */
32
    protected $storage;
33
34
    private $initialized = false;
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function __construct(CurrentUserInterface $CurrentUser, UsersTable $storage)
40
    {
41
        parent::__construct($CurrentUser, $storage);
42
    }
43
44
    /**
45
     * {@inheritDoc}
46
     */
47
    protected function _get(): ?int
48
    {
49
        return $this->remember('timestamp', function () {
50
            // can't use ArrayIterator access because array_key_exists doesn't work
51
            // on ArrayIterator … Yeah for PHP!1!!
52
            $settings = $this->_CurrentUser->getSettings();
53
            if (!array_key_exists('last_refresh', $settings)) {
54
                throw new \Exception('last_refresh not set');
55
            } elseif ($settings['last_refresh'] === null) {
56
                // mar is not initialized
57
                return null;
58
            }
59
60
            return $this->_CurrentUser->get('last_refresh_unix');
61
        });
62
    }
63
64
    /**
65
     * {@inheritDoc}
66
     */
67
    protected function _set(\DateTimeImmutable $timestamp): void
68
    {
69
        $this->persist($timestamp);
70
    }
71
72
    /**
73
     * Set temporary marker
74
     *
75
     * @return void
76
     */
77
    public function setMarker()
78
    {
79
        $this->persist();
80
    }
81
82
    /**
83
     * Persist to strorage
84
     *
85
     * @param DateTimeInterface $timestamp datetime string for last_refresh
86
     * @return void
87
     */
88
    protected function persist(DateTimeInterface $timestamp = null): void
89
    {
90
        $this->_storage->setLastRefresh(
91
            $this->_CurrentUser->getId(),
92
            $timestamp
93
        );
94
    }
95
}
96