Completed
Push — b0.25.0 ( 8d1eb0...bc6f08 )
by Sebastian
02:46
created

ProtectedController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 8
dl 0
loc 34
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A protectWithRedirect() 0 5 2
A protect() 0 5 2
1
<?php
2
3
/**
4
 * Linna Framework.
5
 *
6
 * @author Sebastian Rapetti <[email protected]>
7
 * @copyright (c) 2018, Sebastian Rapetti
8
 * @license http://opensource.org/licenses/MIT MIT License
9
 */
10
declare(strict_types=1);
11
12
namespace Linna\Authentication;
13
14
use Linna\Authentication\Exception\AuthenticationException;
15
16
/**
17
 * Help protect a controller with login.
18
 */
19
trait ProtectedController
20
{
21
    /**
22
     * @var bool Contain login status
23
     */
24
    private $authentication = false;
25
26
    /**
27
     * Allow access to controller class or methods only if logged.
28
     * Return a status code, useful with AJAX requests.
29
     *
30
     * @param Authentication $authentication
31
     * @param int            $httpResponseCode
32
     */
33 3
    private function protect(Authentication $authentication, int $httpResponseCode = 403): void
34
    {
35 3
        if (($this->authentication = $authentication->isLogged()) === false) {
36 2
            http_response_code($httpResponseCode);
37 2
            throw new AuthenticationException('');
38
        }
39 1
    }
40
41
    /**
42
     * Allow access to controller class or methods only if logged
43
     * and do a redirection.
44
     *
45
     * @param Authentication $authentication
46
     * @param string         $location
47
     */
48 2
    private function protectWithRedirect(Authentication $authentication, string $location): void
49
    {
50 2
        if (($this->authentication = $authentication->isLogged()) === false) {
51 2
            header('Location: '.$location);
52 2
            throw new AuthenticationException('');
53
        }
54
    }
55
}
56