Completed
Push — master ( f56284...d558ad )
by Andrii
05:55
created

CertificateTariffForm::extractResources()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 31
Code Lines 12

Duplication

Lines 3
Ratio 9.68 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 3
loc 31
ccs 0
cts 19
cp 0
rs 8.439
c 0
b 0
f 0
cc 6
eloc 12
nc 9
nop 2
crap 42
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-2017, 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;
16
use yii\web\UnprocessableEntityHttpException;
17
18
/**
19
 * Class CertificateTariffForm
20
 *
21
 * @author Dmytro Naumenko <[email protected]>
22
 */
23
class CertificateTariffForm extends AbstractTariffForm
24
{
25
    protected $certificateTypes = [];
26
27
    public function __construct(array $config = [])
28
    {
29
        parent::__construct($config);
30
    }
31
32 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...
33
    {
34
        $this->setAttributes($data[$this->formName()]);
35
        $this->setResources($data[(new CertificateResource())->formName()]);
36
37
        $this->initTariff();
38
39
        return true;
40
    }
41
42
    /**
43
     * @return array
44
     */
45
    public static function getPeriods()
46
    {
47
        return CertificateResource::getPeriods();
48
    }
49
50
    public function setResources($resources)
51
    {
52
        $result = [];
53
        foreach ($resources as $resource) {
54
            $result[] = $this->createResource($resource);
55
        }
56
57
        $this->_resources = $result;
58
59
        return $this;
60
    }
61
62
    protected function createResource($resource)
63
    {
64
        if ($resource instanceof CertificateResource) {
65
            return $resource;
66
        }
67
68
        $model = new CertificateResource(['scenario' => $this->scenario ?: 'default']);
69
        if ($model->load($resource, '') && $model->validate()) {
70
            return $model;
71
        } else {
72
            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...
73
        }
74
    }
75
76
    public function getCertificateTypes()
77
    {
78
        $result = [];
79
80
        foreach ($this->tariff->resources as $resource) {
81
            if (isset($this->certificateTypes[$resource->object_id])) {
82
                $result[$resource->object_id] = $this->certificateTypes[$resource->object_id];
83
            }
84
        }
85
86
        return $result;
87
    }
88
89
    protected function getCertificateTypeId($type)
90
    {
91
        return array_search($type, $this->certificateTypes, true);
92
    }
93
94
    /**
95
     * @param $type
96
     * @return CertificateResource[]
97
     * @throws IntegrityException
98
     */
99
    public function getTypeResources($type)
100
    {
101
        return $this->extractResources($type, $this->tariff->resources);
102
    }
103
104
    /**
105
     * @param array $certificateTypes
106
     */
107
    public function setCertificateTypes($certificateTypes)
108
    {
109
        $this->certificateTypes = $certificateTypes;
110
    }
111
112
    /**
113
     * @param $type
114
     * @return CertificateResource[]
115
     * @throws IntegrityException
116
     */
117
    public function getTypeParentResources($type)
118
    {
119
        return $this->extractResources($type, $this->parentTariff->resources);
120
    }
121
122
    protected function extractResources($certificateType, $resources)
123
    {
124
        $id = $this->getCertificateTypeId($certificateType);
125
126
        $tmpres = [];
127
128
        foreach ($resources as $resource) {
129 View Code Duplication
            if (strcmp($resource->object_id, $id) === 0 && $resource->isTypeCorrect()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
130
                $tmpres[$resource->type] = $resource;
131
            }
132
        }
133
134
        $types = $resource->getTypes();
0 ignored issues
show
Bug introduced by
The variable $resource seems to be defined by a foreach iteration on line 128. 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...
135
        /* XXX why die? let's try with empty resource
136
         * if (count($tmpres) !== count($types)) {
137
            throw new IntegrityException('Found ' . count($tmpres) . ' resources for certificate "' . $type . '". Must be exactly ' . count($types));
138
        }
139
140
        // sorts $tmpres by order of $resource->getTypes()
141
        $tmpres = array_merge($types, $tmpres);
142
         */
143
144
        foreach (array_keys($types) as $type) {
145
            $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...
146
                'object_id' => $id,
147
                'type' => $type,
148
            ]);
149
        }
150
151
        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...
152
    }
153
}
154