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

AuthorizationMiddleware   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
dl 0
loc 57
rs 10
c 0
b 0
f 0

3 Methods

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