CertificateTariffForm   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 131
Duplicated Lines 6.87 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 4
dl 9
loc 131
ccs 0
cts 80
cp 0
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A load() 9 9 1
A getPeriods() 0 4 1
A setResources() 0 11 2
A createResource() 0 13 5
A getCertificateTypes() 0 12 3
A getCertificateTypeId() 0 4 1
A getTypeResources() 0 4 1
A setCertificateTypes() 0 4 1
A getTypeParentResources() 0 4 1
B extractResources() 0 31 6

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
 * Finance module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-finance
6
 * @package   hipanel-module-finance
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\finance\forms;
12
13
use hipanel\modules\finance\logic\IntegrityException;
14
use hipanel\modules\finance\models\CertificateResource;
15
use yii\web\UnprocessableEntityHttpException;
16
17
/**
18
 * Class CertificateTariffForm.
19
 *
20
 * @author Dmytro Naumenko <[email protected]>
21
 */
22
class CertificateTariffForm extends AbstractTariffForm
23
{
24
    protected $certificateTypes = [];
25
26
    public function __construct(array $config = [])
27
    {
28
        parent::__construct($config);
29
    }
30
31 View Code Duplication
    public function load($data, $formName = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
32
    {
33
        $this->setAttributes($data[$this->formName()]);
34
        $this->setResources($data[(new CertificateResource())->formName()]);
0 ignored issues
show
Deprecated Code introduced by
The class hipanel\modules\finance\models\CertificateResource has been deprecated with message: Is implemented in plan module

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
35
36
        $this->initTariff();
37
38
        return true;
39
    }
40
41
    /**
42
     * @return array
43
     */
44
    public static function getPeriods()
45
    {
46
        return CertificateResource::getPeriods();
47
    }
48
49
    public function setResources($resources)
50
    {
51
        $result = [];
52
        foreach ($resources as $resource) {
53
            $result[] = $this->createResource($resource);
54
        }
55
56
        $this->_resources = $result;
57
58
        return $this;
59
    }
60
61
    protected function createResource($resource)
62
    {
63
        if ($resource instanceof CertificateResource) {
64
            return $resource;
65
        }
66
67
        $model = new CertificateResource(['scenario' => $this->scenario ?: 'default']);
0 ignored issues
show
Deprecated Code introduced by
The class hipanel\modules\finance\models\CertificateResource has been deprecated with message: Is implemented in plan module

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
68
        if ($model->load($resource, '') && $model->validate()) {
69
            return $model;
70
        } else {
71
            throw new UnprocessableEntityHttpException('Failed to load resource model: ' . reset($model->getFirstErrors()));
0 ignored issues
show
Bug introduced by
$model->getFirstErrors() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
72
        }
73
    }
74
75
    public function getCertificateTypes()
76
    {
77
        $result = [];
78
79
        foreach ($this->tariff->resources as $resource) {
80
            if (isset($this->certificateTypes[$resource->object_id])) {
81
                $result[$resource->object_id] = $this->certificateTypes[$resource->object_id];
82
            }
83
        }
84
85
        return $result;
86
    }
87
88
    protected function getCertificateTypeId($type)
89
    {
90
        return array_search($type, $this->certificateTypes, true);
91
    }
92
93
    /**
94
     * @param $type
95
     * @throws IntegrityException
96
     * @return CertificateResource[]
97
     */
98
    public function getTypeResources($type)
99
    {
100
        return $this->extractResources($type, $this->tariff->resources);
101
    }
102
103
    /**
104
     * @param array $certificateTypes
105
     */
106
    public function setCertificateTypes($certificateTypes)
107
    {
108
        $this->certificateTypes = $certificateTypes;
109
    }
110
111
    /**
112
     * @param $type
113
     * @throws IntegrityException
114
     * @return CertificateResource[]
115
     */
116
    public function getTypeParentResources($type)
117
    {
118
        return $this->extractResources($type, $this->parentTariff->resources);
119
    }
120
121
    protected function extractResources($certificateType, $resources)
122
    {
123
        $id = $this->getCertificateTypeId($certificateType);
124
125
        $tmpres = [];
126
127
        foreach ($resources as $resource) {
128
            if (strcmp($resource->object_id, $id) === 0 && $resource->isTypeCorrect()) {
129
                $tmpres[$resource->type] = $resource;
130
            }
131
        }
132
133
        $types = $resource->getTypes();
0 ignored issues
show
Bug introduced by
The variable $resource seems to be defined by a foreach iteration on line 127. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
134
        /* XXX why die? let's try with empty resource
135
         * if (count($tmpres) !== count($types)) {
136
            throw new IntegrityException('Found ' . count($tmpres) . ' resources for certificate "' . $type . '". Must be exactly ' . count($types));
137
        }
138
139
        // sorts $tmpres by order of $resource->getTypes()
140
        $tmpres = array_merge($types, $tmpres);
141
         */
142
143
        foreach (array_keys($types) as $type) {
144
            $res[$type] = isset($tmpres[$type]) ? $tmpres[$type] : $this->createResource([
0 ignored issues
show
Coding Style Comprehensibility introduced by
$res was never initialized. Although not strictly required by PHP, it is generally a good practice to add $res = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
145
                'object_id' => $id,
146
                'type' => $type,
147
            ]);
148
        }
149
150
        return $res;
0 ignored issues
show
Bug introduced by
The variable $res does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
151
    }
152
}
153