Completed
Push — master ( 38d8a4...aea7cd )
by Dmitry
05:51
created

ServerOrderProduct   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 176
Duplicated Lines 5.11 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 17
lcom 1
cbo 9
dl 9
loc 176
ccs 0
cts 98
cp 0
rs 10
c 1
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 8 2
A ensureRelatedData() 0 15 3
A rules() 9 9 1
A validateClusterId() 0 4 1
A attributeLabels() 0 8 1
A attributeHints() 0 7 1
A renderDescription() 0 4 1
A getImage() 0 4 1
A getId() 0 8 2
A getCalculationModel() 0 7 1
A getPurchaseModel() 0 19 2
A serializationMap() 0 12 1

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
 * Server module for HiPanel.
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-server
6
 * @package   hipanel-module-server
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\server\cart;
12
13
use hipanel\modules\finance\cart\Calculation;
14
use hipanel\modules\server\helpers\ServerHelper;
15
use hipanel\modules\server\models\Osimage;
16
use hipanel\modules\server\models\Package;
17
use hipanel\modules\server\widgets\cart\OrderPositionDescriptionWidget;
18
use Yii;
19
use yii\base\InvalidConfigException;
20
use yii\helpers\ArrayHelper;
21
22
class ServerOrderProduct extends AbstractServerProduct
23
{
24
    /** {@inheritdoc} */
25
    protected $_purchaseModel = ServerOrderPurchase::class;
26
27
    /** @var Package */
28
    protected $_model;
29
30
    /** {@inheritdoc} */
31
    protected $_calculationModel = Calculation::class;
32
33
    /**
34
     * @var Osimage the selected OS image detailed information
35
     */
36
    protected $_image;
37
38
    /**
39
     * @var integer
40
     */
41
    public $tariff_id;
42
43
    /**
44
     * @var integer id of cluster. See [[hipanel\modules\server\models\Package::getLocations()]] for details
45
     * @see \hipanel\modules\server\models\Package::getLocations()
46
     */
47
    public $cluster_id;
48
49
    /**
50
     * @var string the purpose for the server
51
     */
52
    public $purpose;
53
54
    /**
55
     * @var string link to any kind of social network
56
     */
57
    public $social;
58
59
    /**
60
     * @var string osimage name. Is used to load [[_image]] on product initialisation
61
     */
62
    public $osimage;
63
64
    /**
65
     * @var string software package name
66
     */
67
    public $panel_soft;
68
69
    /** {@inheritdoc} */
70
    public function load($data, $formName = null)
71
    {
72
        if ($result = parent::load($data, '')) {
73
            $this->ensureRelatedData();
74
        }
75
76
        return $result;
77
    }
78
79
    /** {@inheritdoc} */
80
    private function ensureRelatedData()
81
    {
82
        $this->_model = ServerHelper::getAvailablePackages(null, $this->tariff_id);
0 ignored issues
show
Documentation Bug introduced by
It seems like \hipanel\modules\server\...null, $this->tariff_id) can also be of type array. However, the property $_model is declared as type object<hipanel\modules\server\models\Package>. 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...
83
        if ($this->_model === null) {
84
            throw new InvalidConfigException('Failed to find tariff');
85
        }
86
87
        $this->_image = Osimage::find()->where(['osimage' => $this->osimage, 'type' => $this->_model->getType()])->one();
0 ignored issues
show
Documentation Bug introduced by
It seems like \hipanel\modules\server\...del->getType()))->one() can also be of type object<hiqdev\hiart\ActiveRecord> or array. However, the property $_image is declared as type object<hipanel\modules\server\models\Osimage>. 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...
88
        if ($this->_image === null) {
89
            throw new InvalidConfigException('Failed to find osimage');
90
        }
91
92
        $this->name = $this->_model->getName();
0 ignored issues
show
Documentation introduced by
The property name does not exist on object<hipanel\modules\s...art\ServerOrderProduct>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
93
        $this->description = Yii::t('hipanel:server:order', 'Order');
0 ignored issues
show
Documentation introduced by
The property description does not exist on object<hipanel\modules\s...art\ServerOrderProduct>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
94
    }
95
96
    /** {@inheritdoc} */
97
    public function getId()
98
    {
99
        if ($this->_id === null) {
100
            $this->_id = hash('crc32b', implode('_', ['server', 'order', $this->_model->id]));
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Package>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
101
        }
102
103
        return $this->_id;
104
    }
105
106
    /** {@inheritdoc} */
107
    public function getCalculationModel($options = [])
108
    {
109
        return parent::getCalculationModel(array_merge([
110
            'tariff_id' => $this->tariff_id,
111
            'object' => 'server',
112
        ], $options));
113
    }
114
115
    /** {@inheritdoc} */
116
    public function getPurchaseModel($options = [])
117
    {
118
        $this->ensureRelatedData(); // To get fresh domain expiration date
119
120
        $options = array_merge([
121
            'osimage' => $this->osimage,
122
            'panel' => $this->_image->getPanelName(),
123
            'cluster_id' => $this->cluster_id,
124
            'social' => $this->social,
125
            'purpose' => $this->purpose,
126
            'tariff_id' => $this->tariff_id,
127
        ], $options);
128
129
        if ($options['panel'] === Osimage::NO_PANEL) {
130
            unset($options['panel']);
131
        }
132
133
        return parent::getPurchaseModel($options);
134
    }
135
136
    /** {@inheritdoc} */
137 View Code Duplication
    public function rules()
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...
138
    {
139
        return array_merge(parent::rules(), [
140
            [['cluster_id', 'tariff_id'], 'integer'],
141
            [['social', 'osimage'], 'safe'],
142
            [['tariff_id', 'purpose', 'osimage'], 'required'],
143
            [['cluster_id'], 'validateClusterId'],
144
        ]);
145
    }
146
147
    public function validateClusterId($value)
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
148
    {
149
        return in_array($this->cluster_id, array_keys($this->_model->getLocations()), true);
150
    }
151
152
    /** {@inheritdoc} */
153
    public function attributeLabels()
154
    {
155
        return ArrayHelper::merge(parent::attributeLabels(), [
156
            'cluster_id' => Yii::t('hipanel:server:order', 'Server location'),
157
            'purpose' => Yii::t('hipanel:server:order', 'Purpose'),
158
            'social' => Yii::t('hipanel:server:order', 'Social network'),
159
        ]);
160
    }
161
162
    /** {@inheritdoc} */
163
    public function attributeHints()
164
    {
165
        return ArrayHelper::merge(parent::attributeHints(), [
166
            'purpose' => Yii::t('hipanel:server:order', 'How are you going to use the server?'),
167
            'social' => Yii::t('hipanel:server:order', 'Any social network link. Will be used in case of emergency contact'),
168
        ]);
169
    }
170
171
    /** {@inheritdoc} */
172
    public function renderDescription()
173
    {
174
        return OrderPositionDescriptionWidget::widget(['position' => $this]);
175
    }
176
177
    /**
178
     * @return Osimage
179
     */
180
    public function getImage()
181
    {
182
        return $this->_image;
183
    }
184
185
    protected function serializationMap()
186
    {
187
        $parent = parent::serializationMap();
188
        $parent['cluster_id'] = $this->cluster_id;
189
        $parent['osimage'] = $this->osimage;
190
        $parent['panel_soft'] = $this->panel_soft;
191
        $parent['purpose'] = $this->purpose;
192
        $parent['social'] = $this->social;
193
        $parent['tariff_id'] = $this->tariff_id;
194
        $parent['_image'] = $this->_image;
195
        return $parent;
0 ignored issues
show
Best Practice introduced by
The expression return $parent; seems to be an array, but some of its elements' types (integer|string|hipanel\m...s\server\models\Osimage) are incompatible with the return type of the parent method hipanel\modules\server\c...oduct::serializationMap of type array<string,hipanel\mod...s\server\models\Server>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
196
    }
197
}
198