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

CurrentUserTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A findUser() 0 4 1
A getUser() 0 8 2
A statusCodeUserNotFound() 0 4 2
A messageUserNotFound() 0 4 2
A handleUserNotFoundResponse() 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 Craft;
12
use craft\elements\User as UserElement;
13
use yii\web\HttpException;
14
15
/**
16
 * @author Flipbox Factory <[email protected]>
17
 * @since 2.0.0
18
 */
19
trait CurrentUserTrait
20
{
21
    /**
22
     * @return int|null
23
     */
24
    public $statusCodeUserNotFound;
25
26
    /**
27
     * @return string|null
28
     */
29
    public $messageUserNotFound;
30
31
    /**
32
     * @return UserElement|null
33
     */
34
    protected function findUser()
35
    {
36
        return Craft::$app->getUser()->getIdentity();
37
    }
38
39
    /**
40
     * @return UserElement
41
     * @throws HttpException
42
     */
43
    protected function getUser()
44
    {
45
        if (($currentUser = $this->findUser()) === null) {
46
            return $this->handleUserNotFoundResponse();
47
        };
48
49
        return $currentUser;
50
    }
51
52
    /**
53
     * HTTP forbidden response code
54
     *
55
     * @return int
56
     */
57
    protected function statusCodeUserNotFound(): int
58
    {
59
        return $this->statusCodeUserNotFound ?: 401;
60
    }
61
62
    /**
63
     * @return string
64
     */
65
    protected function messageUserNotFound(): string
66
    {
67
        return $this->messageUserNotFound ?: 'Unable to establish identity.';
68
    }
69
70
    /**
71
     * @throws HttpException
72
     * @return mixed
73
     */
74
    protected function handleUserNotFoundResponse()
75
    {
76
        throw new HttpException(
77
            $this->statusCodeUserNotFound(),
78
            $this->messageUserNotFound()
79
        );
80
    }
81
}
82