Completed
Push — master ( fd5325...d7e193 )
by Schlaefer
05:54 queued 03:00
created

LastRefreshDatabase::persist()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 7
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
     * {@inheritDoc}
74
     */
75
    public function setMarker(): void
76
    {
77
        $this->persist();
78
    }
79
80
    /**
81
     * Persist to strorage
82
     *
83
     * @param DateTimeInterface $timestamp datetime string for last_refresh
84
     * @return void
85
     */
86
    protected function persist(DateTimeInterface $timestamp = null): void
87
    {
88
        $this->_storage->setLastRefresh(
89
            $this->_CurrentUser->getId(),
90
            $timestamp
91
        );
92
    }
93
}
94