Passed
Pull Request — master (#18)
by
02:40
created

AuthorizationMiddleware::isSecureExpired()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
1
<?php
2
3
namespace LineMob\Core\Mocky\Auth;
4
5
use League\Tactician\Middleware;
6
use LineMob\Core\Mocky\Doctrine\Model\User;
7
8
class AuthorizationMiddleware implements Middleware
9
{
10
    /**
11
     * @var string
12
     */
13
    private $expirationPeriod;
14
15
    public function __construct($expirationPeriod = '1 day')
16
    {
17
        $this->expirationPeriod = $expirationPeriod;
18
    }
19
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function execute($command, callable $next)
24
    {
25
        if (!$command->storage) {
26
            throw new \LogicException("Require storage before using this middleware!");
27
        }
28
29
        if (!$command->secured) {
30
            return $next($command);
31
        }
32
33
        if (!$this->isSecureExpired($command->storage)) {
34
            return $next($command);
35
        }
36
37
        $cmd = new LoginCommand();
38
        $cmd->input = $command->input;
39
        $cmd->storage = $command->storage;
40
        $cmd->logs = $command->logs;
41
42
        $command['switchTo'] = $cmd;
43
44
        return $next($command);
45
46
    }
47
48
    /**
49
     * @param User $user
50
     *
51
     * @return bool
52
     */
53
    private function isSecureExpired(User $user)
54
    {
55
        // never expired
56
        if (!$this->expirationPeriod) {
57
            return false;
58
        }
59
60
        if (!$lastLogin = $user->getLineLastLogin()) {
61
            return true;
62
        }
63
64
        return (new \DateTime('-'.$this->expirationPeriod)) > $lastLogin;
65
    }
66
}
67