Completed
Push — develop ( 11971b...45f15f )
by Nate
06:59
created

CheckAccessTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 63
ccs 0
cts 24
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A checkAccess() 0 11 3
A statusCodeUnauthorized() 0 4 2
A messageUnauthorized() 0 4 2
A handleUnauthorizedResponse() 0 7 1
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember/
7
 */
8
9
namespace flipbox\craft\ember\actions;
10
11
use yii\web\UnauthorizedHttpException;
12
13
/**
14
 * @author Flipbox Factory <[email protected]>
15
 * @since 2.0.0
16
 */
17
trait CheckAccessTrait
18
{
19
    /**
20
     * @var int|null
21
     */
22
    public $statusCodeUnauthorized;
23
24
    /**
25
     * @var string|null
26
     */
27
    public $messageUnauthorized;
28
29
    /**
30
     * @var null|callable
31
     */
32
    public $checkAccess = null;
33
34
    /**
35
     * @param mixed ...$params
36
     * @return mixed
37
     * @throws UnauthorizedHttpException
38
     */
39
    public function checkAccess(...$params)
40
    {
41
        if ($this->checkAccess) {
42
            if (call_user_func_array($this->checkAccess, $params) === false) {
43
                /** @noinspection PhpVoidFunctionResultUsedInspection */
44
                return $this->handleUnauthorizedResponse();
45
            };
46
        }
47
48
        return true;
49
    }
50
51
    /**
52
     * HTTP forbidden response code
53
     *
54
     * @return int
55
     */
56
    protected function statusCodeUnauthorized(): int
57
    {
58
        return $this->statusCodeUnauthorized ?: 403;
59
    }
60
61
    /**
62
     * @return string
63
     */
64
    protected function messageUnauthorized(): string
65
    {
66
        return $this->messageUnauthorized ?: 'Unable to perform action.';
67
    }
68
69
    /**
70
     * @throws UnauthorizedHttpException
71
     */
72
    protected function handleUnauthorizedResponse()
73
    {
74
        throw new UnauthorizedHttpException(
75
            $this->statusCodeUnauthorized(),
76
            $this->messageUnauthorized()
77
        );
78
    }
79
}
80