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

ManageTrait   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 84
ccs 0
cts 28
cp 0
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
performAction() 0 1 ?
A runInternal() 0 13 3
A statusCodeSuccess() 0 4 2
A statusCodeFail() 0 4 2
A handleSuccessResponse() 0 6 1
A handleFailResponse() 0 5 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
13
/**
14
 * @author Flipbox Factory <[email protected]>
15
 * @since 2.0.0
16
 */
17
trait ManageTrait
18
{
19
    use CheckAccessTrait;
20
21
    /**
22
     * HTTP success response code
23
     *
24
     * @var int|null
25
     */
26
    public $statusCodeSuccess;
27
28
    /**
29
     * HTTP fail response code
30
     *
31
     * @var int|null
32
     */
33
    public $statusCodeFail;
34
35
    /**
36
     * @param mixed $data
37
     * @return bool
38
     */
39
    abstract protected function performAction($data): bool;
40
41
    /**
42
     * @param $data
43
     * @return mixed
44
     * @throws \yii\web\HttpException
45
     */
46
    protected function runInternal($data)
47
    {
48
        // Check access
49
        if (($access = $this->checkAccess($data)) !== true) {
50
            return $access;
51
        }
52
53
        if (!$this->performAction($data)) {
54
            return $this->handleFailResponse($data);
55
        }
56
57
        return $this->handleSuccessResponse($data);
58
    }
59
60
    /**
61
     * HTTP success response code
62
     *
63
     * @return int
64
     */
65
    protected function statusCodeSuccess(): int
66
    {
67
        return $this->statusCodeSuccess ?: 200;
68
    }
69
70
    /**
71
     * HTTP fail response code
72
     *
73
     * @return int
74
     */
75
    protected function statusCodeFail(): int
76
    {
77
        return $this->statusCodeFail ?: 400;
78
    }
79
80
    /**
81
     * @param $data
82
     * @return mixed
83
     */
84
    protected function handleSuccessResponse($data)
85
    {
86
        // Success status code
87
        Craft::$app->getResponse()->setStatusCode($this->statusCodeSuccess());
88
        return $data;
89
    }
90
91
    /**
92
     * @param $data
93
     * @return mixed
94
     */
95
    protected function handleFailResponse($data)
96
    {
97
        Craft::$app->getResponse()->setStatusCode($this->statusCodeFail());
98
        return $data;
99
    }
100
}
101