Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like Order often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Order, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
58 | class Order extends \yii\db\ActiveRecord |
||
59 | { |
||
60 | const IMMUTABLE_NONE = 0; |
||
61 | const IMMUTABLE_USER = 1; |
||
62 | const IMMUTABLE_MANAGER = 2; |
||
63 | const IMMUTABLE_ASSIGNED = 4; |
||
64 | const IMMUTABLE_ALL = 128; |
||
65 | const ORDER_STATE_FINISH = 0; |
||
66 | const ORDER_STATE_IN_PROCESS = 1; |
||
67 | |||
68 | /** |
||
69 | * @var Order $order |
||
70 | */ |
||
71 | protected static $order; |
||
72 | /** @var OrderStage $orderStage */ |
||
73 | protected $orderStage = null; |
||
74 | |||
75 | /** |
||
76 | * @inheritdoc |
||
77 | */ |
||
78 | public function behaviors() |
||
79 | { |
||
80 | return [ |
||
81 | [ |
||
82 | 'class' => HasProperties::className(), |
||
83 | ], |
||
84 | [ |
||
85 | 'class' => \devgroup\TagDependencyHelper\ActiveRecordHelper::className(), |
||
86 | ], |
||
87 | [ |
||
88 | 'class' => TimestampBehavior::className(), |
||
89 | 'createdAtAttribute' => 'start_date', |
||
90 | 'updatedAtAttribute' => 'update_date', |
||
91 | 'value' => new Expression('NOW()'), |
||
92 | ], |
||
93 | ]; |
||
94 | } |
||
95 | |||
96 | /** |
||
97 | * @inheritdoc |
||
98 | */ |
||
99 | public static function tableName() |
||
103 | |||
104 | /** |
||
105 | * @inheritdoc |
||
106 | */ |
||
107 | public function rules() |
||
108 | { |
||
109 | return [ |
||
110 | [ |
||
111 | [ |
||
112 | 'user_id', |
||
113 | 'customer_id', |
||
114 | 'contragent_id', |
||
115 | 'order_stage_id', |
||
116 | 'total_price', |
||
117 | 'payment_type_id', |
||
118 | 'in_cart', |
||
119 | ], |
||
120 | 'required' |
||
121 | ], |
||
122 | [ |
||
123 | [ |
||
124 | 'user_id', |
||
125 | 'customer_id', |
||
126 | 'contragent_id', |
||
127 | 'order_stage_id', |
||
128 | 'payment_type_id', |
||
129 | 'assigned_id', |
||
130 | 'tax_id' |
||
131 | ], |
||
132 | 'integer' |
||
133 | ], |
||
134 | [['start_date', 'end_date', 'update_date'], 'safe'], |
||
135 | [['total_price', 'items_count', 'total_payed'], 'number'], |
||
136 | [['external_id'], 'string', 'max' => 38], |
||
137 | [['is_deleted', 'temporary', 'show_price_changed_notification', 'in_cart'], 'boolean'], |
||
138 | [['user_id', 'customer_id', 'contragent_id', 'in_cart'], 'default', 'value' => 0], |
||
139 | [['temporary'], 'default', 'value' => 1], |
||
140 | ]; |
||
141 | } |
||
142 | |||
143 | /** |
||
144 | * @inheritdoc |
||
145 | */ |
||
146 | public function scenarios() |
||
147 | { |
||
148 | return [ |
||
149 | 'default' => [ |
||
150 | 'user_id', |
||
151 | 'cart_forming_time', |
||
152 | 'order_stage_id', |
||
153 | 'items_count', |
||
154 | 'total_price', |
||
155 | 'hash', |
||
156 | 'in_cart', |
||
157 | ], |
||
158 | 'search' => [ |
||
159 | 'id', |
||
160 | 'user_id', |
||
161 | 'manager_id', |
||
162 | 'start_date', |
||
163 | 'end_date', |
||
164 | 'order_stage_id', |
||
165 | 'payment_type_id', |
||
166 | 'items_count', |
||
167 | 'total_price', |
||
168 | 'hash', |
||
169 | ], |
||
170 | 'shippingOption' => ['order_stage_id'], |
||
171 | 'paymentType' => ['payment_type_id', 'order_stage_id'], |
||
172 | 'changeManager' => ['manager_id'], |
||
173 | 'backend' => [ |
||
174 | 'user_id', |
||
175 | 'customer_id', |
||
176 | 'contragent_id', |
||
177 | ], |
||
178 | ]; |
||
179 | } |
||
180 | |||
181 | /** |
||
182 | * @inheritdoc |
||
183 | */ |
||
184 | public function attributeLabels() |
||
185 | { |
||
186 | return [ |
||
187 | 'id' => Yii::t('app', 'ID'), |
||
188 | 'user_id' => Yii::t('app', 'User'), |
||
189 | 'customer_id' => Yii::t('app', 'Customer'), |
||
190 | 'contragent_id' => Yii::t('app', 'Contragent'), |
||
191 | 'manager_id' => Yii::t('app', 'Manager'), |
||
192 | 'start_date' => Yii::t('app', 'Start Date'), |
||
193 | 'update_date' => Yii::t('app', 'Update date'), |
||
194 | 'end_date' => Yii::t('app', 'End Date'), |
||
195 | 'cart_forming_time' => Yii::t('app', 'Cart Forming Time'), |
||
196 | 'order_stage_id' => Yii::t('app', 'Stage'), |
||
197 | 'payment_type_id' => Yii::t('app', 'Payment Type'), |
||
198 | 'assigned_id' => Yii::t('app', 'Assigned'), |
||
199 | 'tax_id' => Yii::t('app', 'Tax'), |
||
200 | 'external_id' => Yii::t('app', 'External ID'), |
||
201 | 'items_count' => Yii::t('app', 'Items Count'), |
||
202 | 'total_price' => Yii::t('app', 'Total Price'), |
||
203 | 'total_payed' => Yii::t('app', 'Total payed'), |
||
204 | 'hash' => Yii::t('app', 'Hash'), |
||
205 | 'is_deleted' => Yii::t('app', 'Is deleted'), |
||
206 | 'temporary' => Yii::t('app', 'Temporary'), |
||
207 | 'show_price_changed_notification' => Yii::t('app', 'Show price changed notification'), |
||
208 | 'in_cart' => Yii::t('app', 'In Cart'), |
||
209 | ]; |
||
210 | } |
||
211 | |||
212 | public function getItems() |
||
216 | |||
217 | /** |
||
218 | * @return OrderStage|null |
||
|
|||
219 | */ |
||
220 | public function getStage() |
||
221 | { |
||
222 | if (null === $this->orderStage) { |
||
223 | $this->orderStage = $this->hasOne(OrderStage::className(), ['id' => 'order_stage_id']); |
||
224 | } |
||
225 | return $this->orderStage; |
||
226 | } |
||
227 | |||
228 | public function getShippingOption() |
||
229 | { |
||
230 | $orderDelivery = OrderDeliveryInformation::getByOrderId($this->id); |
||
231 | return empty($orderDelivery) ? null : $orderDelivery->shippingOption; |
||
232 | } |
||
233 | |||
234 | public function getPaymentType() |
||
238 | |||
239 | public function getTransactions() |
||
243 | |||
244 | public function getUser() |
||
248 | |||
249 | public function getCode() |
||
253 | |||
254 | /** |
||
255 | * @return Customer|null |
||
256 | */ |
||
257 | public function getCustomer() |
||
261 | |||
262 | public function getContragent() |
||
266 | |||
267 | public function getManager() |
||
271 | |||
272 | public function getSpecialPriceObjects() |
||
273 | { |
||
274 | return SpecialPriceObject::find() |
||
275 | ->leftJoin( |
||
276 | SpecialPriceList::tableName(), |
||
277 | SpecialPriceList::tableName() . '.id =' . SpecialPriceObject::tableName() . '.special_price_list_id' |
||
278 | ) |
||
279 | ->where( |
||
280 | [ |
||
281 | SpecialPriceObject::tableName() . '.object_model_id' => $this->id, |
||
282 | SpecialPriceList::tableName() . '.object_id' => $this->object->id |
||
283 | ] |
||
284 | ) |
||
285 | ->all(); |
||
286 | } |
||
287 | |||
288 | public function getFullPrice() |
||
289 | { |
||
290 | $fullPrice = $this->total_price; |
||
291 | if (!is_null($this->shippingOption)) { |
||
292 | $fullPrice += $this->shippingOption->cost; |
||
293 | } |
||
294 | return $fullPrice; |
||
295 | } |
||
296 | |||
297 | /** |
||
298 | * @return OrderDeliveryInformation|null |
||
299 | */ |
||
300 | public function getOrderDeliveryInformation() |
||
304 | |||
305 | /** |
||
306 | * Первое удаление в корзину, второе из БД |
||
307 | * |
||
308 | * @return bool |
||
309 | */ |
||
310 | public function beforeDelete() |
||
311 | { |
||
312 | if (Yii::$app->getModule('shop')->deleteOrdersAbility === 0) { |
||
313 | return false; |
||
314 | } |
||
315 | if (!parent::beforeDelete()) { |
||
316 | return false; |
||
317 | } |
||
318 | if (0 === intval($this->is_deleted)) { |
||
319 | $this->is_deleted = 1; |
||
320 | $this->save(); |
||
321 | return false; |
||
322 | } |
||
323 | $customer = $this->getCustomer(); |
||
324 | if (0 === intval($customer->user_id)) { |
||
325 | $customer->delete(); |
||
326 | } |
||
327 | |||
328 | return true; |
||
329 | } |
||
330 | |||
331 | /** |
||
332 | * Search tasks |
||
333 | * @param $params |
||
334 | * @return ActiveDataProvider |
||
335 | */ |
||
336 | View Code Duplication | public function search($params) |
|
337 | { |
||
338 | /** @var $query \yii\db\ActiveQuery */ |
||
339 | $query = self::find(); |
||
340 | |||
341 | $dataProvider = new ActiveDataProvider( |
||
342 | [ |
||
343 | 'query' => $query, |
||
344 | 'pagination' => [ |
||
345 | 'pageSize' => 10, |
||
346 | ], |
||
347 | ] |
||
348 | ); |
||
349 | if (!($this->load($params))) { |
||
350 | return $dataProvider; |
||
351 | } |
||
352 | $query->andFilterWhere(['id' => $this->id]); |
||
353 | $query->andFilterWhere(['is_deleted' => $this->is_deleted]); |
||
354 | return $dataProvider; |
||
355 | } |
||
356 | |||
357 | /** |
||
358 | * Create a new order. |
||
359 | * @param bool $throwException Throw an exception if a order has not been saved |
||
360 | * @param bool $assignToUser Assign to a current user |
||
361 | * @return Order |
||
362 | * @throws Exception |
||
363 | */ |
||
364 | public static function create($throwException = true, $assignToUser = true, $dummyObject = false) |
||
365 | { |
||
366 | TagDependency::invalidate(Yii::$app->cache, ['Session:' . Yii::$app->session->id]); |
||
367 | $initialOrderStage = OrderStage::getInitialStage(); |
||
368 | if (is_null($initialOrderStage)) { |
||
369 | throw new Exception('Initial order stage not found'); |
||
370 | } |
||
371 | $model = new static; |
||
372 | $model->loadDefaultValues(false); |
||
373 | $model->user_id = !Yii::$app->user->isGuest && $assignToUser ? Yii::$app->user->id : 0; |
||
374 | $model->order_stage_id = $initialOrderStage->id; |
||
375 | $model->in_cart = 1; |
||
376 | $model->customer_id = 0; |
||
377 | $model->contragent_id = 0; |
||
378 | mt_srand(); |
||
379 | $model->hash = md5(mt_rand() . uniqid()); |
||
380 | if (false === $dummyObject) { |
||
381 | if (!$model->save()) { |
||
382 | if ($throwException) { |
||
383 | throw new Exception('Cannot create a new order.'); |
||
384 | } else { |
||
385 | return null; |
||
386 | } |
||
387 | } |
||
388 | } |
||
389 | return $model; |
||
390 | } |
||
391 | |||
392 | /** |
||
393 | * Get current order. |
||
394 | * @param bool $create Create order if it does not exist |
||
395 | * @return Order |
||
396 | * @throws Exception |
||
397 | */ |
||
398 | public static function getOrder($create = false) |
||
399 | { |
||
400 | Yii::beginProfile("GetOrder"); |
||
401 | if (is_null(self::$order) && Yii::$app->session->has('orderId')) { |
||
402 | self::$order = self::find() |
||
403 | ->where(['id' => Yii::$app->session->get('orderId')]) |
||
404 | ->one(); |
||
405 | } |
||
406 | if (is_null(self::$order) && !Yii::$app->user->isGuest) { |
||
407 | self::$order = self::find() |
||
408 | ->where(['user_id' => Yii::$app->user->id, 'in_cart' => 1]) |
||
409 | ->orderBy(['start_date' => SORT_DESC, 'id' => SORT_DESC]) |
||
410 | ->one(); |
||
411 | } |
||
412 | if ((is_null(self::$order) || is_null(self::$order->stage) || self::$order->in_cart == 0) |
||
413 | && $create === true |
||
414 | ) { |
||
415 | $model = self::create(); |
||
416 | self::$order = $model; |
||
417 | Yii::$app->session->set('orderId', $model->id); |
||
418 | |||
419 | $sessionOrders = Yii::$app->session->get('orders', []); |
||
420 | $sessionOrders[] = $model->id; |
||
421 | Yii::$app->session->set('orders', $sessionOrders); |
||
422 | |||
423 | } |
||
424 | Yii::endProfile("GetOrder"); |
||
425 | return self::$order; |
||
426 | } |
||
427 | |||
428 | public static function clearStaticOrder() |
||
432 | |||
433 | /** |
||
434 | * Calculate order total price and items count with all additional markups. |
||
435 | * @param bool $callSave Call save method after calculating. |
||
436 | * @param bool $deleteNotActiveProducts Delete Order Item if product is not active or is not exist. |
||
437 | * @return bool |
||
438 | */ |
||
439 | public function calculate($callSave = false, $deleteNotActiveProducts = true) |
||
440 | { |
||
441 | $itemsCount = 0; |
||
442 | foreach ($this->items as $item) { |
||
443 | if (null === OrderItem::findOne(['id' => $item->id])) { |
||
444 | $item->delete(); |
||
474 | |||
475 | /** |
||
476 | * @inheritdoc |
||
477 | */ |
||
478 | public function beforeSave($insert) |
||
483 | |||
484 | /** |
||
485 | * @inheritdoc |
||
486 | */ |
||
487 | public function afterSave($insert, $changedAttributes) |
||
500 | |||
501 | public function afterDelete() |
||
506 | |||
507 | public static function deleteOrderElements(Order $order) |
||
517 | |||
518 | /** |
||
519 | * @param integer|null $checkWith |
||
520 | * @return int |
||
521 | */ |
||
522 | public function getImmutability($checkWith = null) |
||
531 | |||
532 | /** |
||
533 | * @return int |
||
534 | */ |
||
535 | public function getOrderState() |
||
542 | } |
||
543 |
This check compares the return type specified in the
@return
annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.