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

ProtectedController::protectWithRedirect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 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