FindModelTrait   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 43.24 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 1
dl 16
loc 37
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A findModel() 8 8 2
A findModelOrCreate() 8 8 2

How to fix   Duplicated Code   

Duplicated Code

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:

1
<?php
2
3
namespace app\traits;
4
5
use yii\db\ActiveRecord;
6
use yii\web\NotFoundHttpException;
7
8
/**
9
 * Class FindModelTrait
10
 *
11
 * @author Igor Chepurnoy <[email protected]>
12
 *
13
 * @since 1.0
14
 */
15
trait FindModelTrait
16
{
17
    /**
18
     * Finds model
19
     *
20
     * @param mixed $modelClass
21
     * @param mixed $condition primary key value or a set of column values
22
     * @param string $notFoundMessage
23
     *
24
     * @throws NotFoundHttpException
25
     *
26
     * @return ActiveRecord
27
     */
28 View Code Duplication
    protected function findModel($modelClass, $condition, string $notFoundMessage = 'The requested page does not exist.')
29
    {
30
        if (($model = $modelClass::findOne($condition)) !== null) {
31
            return $model;
32
        } else {
33
            throw new NotFoundHttpException($notFoundMessage);
34
        }
35
    }
36
37
    /**
38
     * @param mixed $modelClass
39
     * @param mixed $condition primary key value or a set of column values
40
     *
41
     * @return ActiveRecord
42
     */
43 View Code Duplication
    protected function findModelOrCreate($modelClass, $condition)
44
    {
45
        if (($model = $modelClass::findOne($condition)) !== null) {
46
            return $model;
47
        } else {
48
            return new $modelClass($condition);
49
        }
50
    }
51
}
52