OrderAjaxController::actionRemoveFromBasket()   A
last analyzed

Complexity

Conditions 3
Paths 6

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 6
nop 0
dl 0
loc 16
rs 9.9666
1
<?php
2
3
namespace app\controllers\ajax;
4
5
use Yii;
6
use yii\filters\{ContentNegotiator, VerbFilter};
7
use yii\web\{Controller, Response, BadRequestHttpException};
8
use app\traits\ResponseTrait;
9
use app\components\BasketComponent;
10
use app\models\Order;
11
12
/**
13
 * Class OrderAjaxController
14
 *
15
 * @package app\controllers
16
 */
17
class OrderAjaxController extends Controller
18
{
19
    use ResponseTrait;
20
21
    /**
22
     * @var string|array the configuration for creating the serializer that formats the response data.
23
     */
24
    public $serializer = 'yii\rest\Serializer';
25
26
    /**
27
     * @var BasketComponent
28
     */
29
    protected $basketManager;
30
31
    /**
32
     * Initialize.
33
     */
34
    public function init()
35
    {
36
        parent::init();
37
38
        $this->basketManager = Yii::$app->get('basket');
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->get('basket') can also be of type mixed. However, the property $basketManager is declared as type app\components\BasketComponent. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
39
    }
40
41
    /**
42
     * @return array
43
     */
44
    public function behaviors()
45
    {
46
        return [
47
            'contentNegotiator' => [
48
                'class' => ContentNegotiator::class,
49
                'formats' => [
50
                    'application/json' => Response::FORMAT_JSON,
51
                ],
52
            ],
53
            'verbFilter' => [
54
                'class' => VerbFilter::class,
55
                'actions' => $this->verbs(),
56
            ],
57
        ];
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function afterAction($action, $result)
64
    {
65
        $result = parent::afterAction($action, $result);
66
        return $this->serializeData($result);
67
    }
68
69
    /**
70
     * @return array
71
     */
72
    public function verbs()
73
    {
74
        return [
75
            'put-to-basket' => ['POST'],
76
            'set-count-in-basket' => ['POST'],
77
            'remove-from-basket' => ['POST'],
78
            'send-order' => ['POST'],
79
        ];
80
    }
81
82
    /**
83
     * @return array
84
     * @throws BadRequestHttpException
85
     */
86
    public function actionPutToBasket()
87
    {
88
        try {
89
            $id = Yii::$app->request->post('id');
90
            $count = Yii::$app->request->post('count');
91
92
            if ($this->basketManager->putToBasket($id, empty($count) ? 1 : $count)) {
0 ignored issues
show
Bug introduced by
It seems like empty($count) ? 1 : $count can also be of type array; however, parameter $count of app\components\BasketComponent::putToBasket() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

92
            if ($this->basketManager->putToBasket($id, /** @scrutinizer ignore-type */ empty($count) ? 1 : $count)) {
Loading history...
Bug introduced by
It seems like $id can also be of type array; however, parameter $modelId of app\components\BasketComponent::putToBasket() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

92
            if ($this->basketManager->putToBasket(/** @scrutinizer ignore-type */ $id, empty($count) ? 1 : $count)) {
Loading history...
93
                return $this->getSuccessResponse('', [
94
                    'total_amount' => $this->basketManager->getTotalAmount(),
95
                    'total_count' => $this->basketManager->getTotalCount(),
96
                ]);
97
            }
98
99
            return $this->getFailResponse('Failed put to basket');
100
101
        } catch (\Exception $e) {
102
            throw new BadRequestHttpException($e->getMessage(), $e->getCode());
103
        }
104
    }
105
106
    /**
107
     * @return array
108
     * @throws BadRequestHttpException
109
     */
110
    public function actionSetCountInBasket()
111
    {
112
        try {
113
            $id = Yii::$app->request->post('id');
114
            $count = Yii::$app->request->post('count');
115
116
            if ($this->basketManager->setCountInBasket($id, $count)) {
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type array; however, parameter $modelId of app\components\BasketComponent::setCountInBasket() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

116
            if ($this->basketManager->setCountInBasket(/** @scrutinizer ignore-type */ $id, $count)) {
Loading history...
Bug introduced by
It seems like $count can also be of type array; however, parameter $count of app\components\BasketComponent::setCountInBasket() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

116
            if ($this->basketManager->setCountInBasket($id, /** @scrutinizer ignore-type */ $count)) {
Loading history...
117
                $modelItems = $this->basketManager->getModelItems();
118
119
                return $this->getSuccessResponse('', [
120
                    'total_amount' => $this->basketManager->calculateTotalAmount($modelItems),
121
                    'total_count' => $this->basketManager->getTotalCount(),
122
                    'item_price' => $modelItems[$id]->price
123
                ]);
124
            }
125
126
            return $this->getFailResponse('Failed set count in a basket');
127
128
        } catch (\Exception $e) {
129
            throw new BadRequestHttpException($e->getMessage(), $e->getCode());
130
        }
131
    }
132
133
    /**
134
     * @return array
135
     * @throws BadRequestHttpException
136
     */
137
    public function actionRemoveFromBasket()
138
    {
139
        try {
140
            $id = Yii::$app->request->post('id');
141
142
            if ($this->basketManager->removeFromBasket($id)) {
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type array; however, parameter $modelId of app\components\BasketComponent::removeFromBasket() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

142
            if ($this->basketManager->removeFromBasket(/** @scrutinizer ignore-type */ $id)) {
Loading history...
143
                return $this->getSuccessResponse('', [
144
                    'total_amount' => $this->basketManager->getTotalAmount(),
145
                    'total_count' => $this->basketManager->getTotalCount(),
146
                ]);
147
            }
148
149
            return $this->getFailResponse('Failed remove from basket');
150
151
        } catch (\Exception $e) {
152
            throw new BadRequestHttpException($e->getMessage(), $e->getCode());
153
        }
154
    }
155
156
    /**
157
     * @return array
158
     * @throws BadRequestHttpException
159
     */
160
    public function actionSendOrder()
161
    {
162
        try {
163
            $order = new Order();
164
            $order->setAttributes(Yii::$app->request->post(), false);
165
166
            if ($order->handle(Yii::$app->params['adminEmail'])) {
167
                $this->basketManager->clearBasket();
168
                return $this->getSuccessResponse(Yii::t('order', 'You have successfully sent your order message.').' '.Yii::t('order', 'The manager will contact you.'));
169
170
            } else {
171
                return $this->getFailResponse(Yii::t('feedback', 'Error send data.'), [
172
                    'errors' => $order->getErrors()
173
                ]);
174
            }
175
176
        } catch (\Exception $e) {
177
            throw new BadRequestHttpException($e->getMessage(), $e->getCode());
178
        }
179
    }
180
181
    /**
182
     * Serializes the specified data.
183
     * The default implementation will create a serializer based on the configuration given by [[serializer]].
184
     * It then uses the serializer to serialize the given data.
185
     * @param mixed $data the data to be serialized
186
     * @return mixed the serialized data.
187
     */
188
    private function serializeData($data)
189
    {
190
        return Yii::createObject($this->serializer)->serialize($data);
191
    }
192
}
193