Completed
Push — master ( a40390...c25130 )
by
11s
created

AuthorizationMiddleware::execute()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
cc 5
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 && LoginCommand::CMD !== $command->storage->getLineActiveCmd()) {
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
     * @param User $user
48
     *
49
     * @return bool
50
     */
51
    private function isSecureExpired(User $user)
52
    {
53
        // never expired
54
        if (!$this->expirationPeriod) {
55
            return false;
56
        }
57
58
        if (!$lastLogin = $user->getLineLastLogin()) {
59
            return true;
60
        }
61
62
        return (new \DateTime('-'.$this->expirationPeriod)) > $lastLogin;
63
    }
64
}
65