CurrentUserTrait::getUser()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
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
 * @property int $statusCodeUserNotFound
20
 * @property string $messageUserNotFound
21
 */
22
trait CurrentUserTrait
23
{
24
    /**
25
     * @return UserElement|null
26
     */
27
    protected function findUser()
28
    {
29
        return Craft::$app->getUser()->getIdentity();
30
    }
31
32
    /**
33
     * @return UserElement
34
     * @throws HttpException
35
     */
36
    protected function getUser()
37
    {
38
        if (($currentUser = $this->findUser()) === null) {
39
            return $this->handleUserNotFoundResponse();
40
        };
41
42
        return $currentUser;
43
    }
44
45
    /**
46
     * HTTP forbidden response code
47
     *
48
     * @return int
49
     */
50
    protected function statusCodeUserNotFound(): int
51
    {
52
        return $this->statusCodeUserNotFound ?? 401;
53
    }
54
55
    /**
56
     * @return string
57
     */
58
    protected function messageUserNotFound(): string
59
    {
60
        return $this->messageUserNotFound ?? 'Unable to establish identity.';
61
    }
62
63
    /**
64
     * @throws HttpException
65
     * @return mixed
66
     */
67
    protected function handleUserNotFoundResponse()
68
    {
69
        throw new HttpException(
70
            $this->statusCodeUserNotFound(),
71
            $this->messageUserNotFound()
72
        );
73
    }
74
}
75