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

CurrentUserTrait::handleUserNotFoundResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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