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

AuthorizationMiddleware::execute()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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