Completed
Pull Request — master (#161)
by
unknown
07:58
created

Model   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 220
Duplicated Lines 8.64 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 96.88%

Importance

Changes 6
Bugs 1 Features 2
Metric Value
c 6
b 1
f 2
dl 19
loc 220
ccs 62
cts 64
cp 0.9688
rs 8.295
wmc 42
lcom 1
cbo 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C fromXml() 14 63 14
D fromArray() 5 33 10
A fromJson() 0 6 1
A toArray() 0 4 1
A toJson() 0 4 1
C toArrayRecursive() 0 38 14

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Model 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 Model, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Yandex PHP Library
4
 *
5
 * @copyright NIX Solutions Ltd.
6
 * @link      https://github.com/nixsolutions/yandex-php-library
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Yandex\Common;
13
14
/**
15
 * Class Model
16
 *
17
 * @package Yandex\Common
18
 */
19
abstract class Model
20
{
21
    protected $mappingClasses = [];
22
23
    /**
24
     * Contains property name mappings.
25
     *
26
     * [
27
     *  'data_array_property1' => 'objectProperty1',
28
     *  'data_array_property2' => 'objectProperty2',
29
     * ]
30
     *
31
     * Data array property uses as keys
32
     * because there is can be more then one rule per object property
33
     *
34
     * f.g. $data['nmodels'] and ['modelsnum'] should map in modelsCount property.
35
     * Otherwise not unique array keys cause remapping of properties.
36
     *
37
     * @var array
38
     */
39
    protected $propNameMap = [];
40
41
    /**
42
     * Constructor
43
     *
44
     * @param array $data
45 152
     */
46
    public function __construct($data)
47 152
    {
48 152
        $this->fromArray($data);
49
    }
50
51
    /**
52
     * Set from XML
53
     *
54
     * @param \SimpleXMLIterator $data
55
     * @return $this
56 150
     */
57
    public function fromXml(\SimpleXMLIterator $data)
58 150
    {
59 114
        //todo: refactor fromXml()
60 67
        if (method_exists($this, 'add')) {
61 67
            for ($data->rewind(); $data->valid(); $data->next()) {
62 67
                $this->add($data->current());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Yandex\Common\Model as the method add() does only exist in the following sub-classes of Yandex\Common\Model: Yandex\DataSync\Models\Database\Delta\RecordFields, Yandex\DataSync\Models\Database\Delta\Records, Yandex\DataSync\Models\Database\Deltas, Yandex\DataSync\Models\Databases, Yandex\Market\Content\Models\Base\Models, Yandex\Market\Content\Models\Categories, Yandex\Market\Content\Models\Children, Yandex\Market\Content\Models\Comments, Yandex\Market\Content\Models\Contras, Yandex\Market\Content\Models\DeliveryMethods, Yandex\Market\Content\Models\Filters, Yandex\Market\Content\Models\GeoRegions, Yandex\Market\Content\Models\ModelOpinions, Yandex\Market\Content\Models\ModelVisualPhotos, Yandex\Market\Content\Models\OfferPhotos, Yandex\Market\Content\Models\Offers, Yandex\Market\Content\Models\Options, Yandex\Market\Content\Models\Outlets, Yandex\Market\Content\Models\Photos, Yandex\Market\Content\Models\Pros, Yandex\Market\Content\Models\Reviews, Yandex\Market\Content\Models\Schedules, Yandex\Market\Content\Models\SearchResults, Yandex\Market\Content\Models\ShopOpinions, Yandex\Market\Content\Models\Shops, Yandex\Market\Content\Models\Vendors, Yandex\Market\Partner\Models\Campaigns, Yandex\Market\Partner\Models\DeliveryOptions, Yandex\Market\Partner\Models\Items, Yandex\Market\Partner\Models\Orders, Yandex\Market\Partner\Models\Outlets, Yandex\Market\Partner\Models\StateReasons, Yandex\Metrica\Analytics\Models\ColumnHeaders, Yandex\Metrica\Management\Models\Accounts, Yandex\Metrica\Management\Models\Conditions, Yandex\Metrica\Management\Models\Counters, Yandex\Metrica\Management\Models\Delegates, Yandex\Metrica\Management\Models\Filters, Yandex\Metrica\Management\Models\Goals, Yandex\Metrica\Management\Models\Grants, Yandex\Metrica\Management\Models\Operations, Yandex\Metrica\Stat\Models\ComparisonData, Yandex\Metrica\Stat\Models\Data, Yandex\Metrica\Stat\Models\Dimensions, Yandex\Metrica\Stat\Models\DrillDownComparisonData, Yandex\Metrica\Stat\Models\DrillDownData, Yandex\Webmaster\Models\Hosts. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
63 67
            }
64
65 114
            return $this;
66 114
        }
67
68 114
        //collect attributes
69
        if ($data->attributes()->count() > 0) {
70
            foreach ($data->attributes() as $key => $attribute) {
71
                $propertyName = $key;
72 114
                $ourPropertyName = array_search($propertyName, $this->propNameMap, true);
73 79
74 73
                if (false !== $ourPropertyName) {
75 73
                    $propertyName = $ourPropertyName;
76 79
                }
77
78 114
                if (property_exists($this, $propertyName)) {
79 106
                    $this->{$propertyName} = (string)$attribute;
80 78
                }
81 78
            }
82 106
        }
83
84 106
        //collect node data
85 150
        for ($data->rewind(); $data->valid(); $data->next()) {
86 150
            $propertyName = $data->key();
87
            $ourPropertyName = array_search($propertyName, $this->propNameMap, true);
88
89
            if (false !== $ourPropertyName) {
90
                $propertyName = $ourPropertyName;
91
            }
92
93 View Code Duplication
            if (property_exists($this, $propertyName)) {
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...
94
                if (array_key_exists($propertyName, $this->mappingClasses)) {
95 1
                    $this->{$propertyName} = new $this->mappingClasses[$propertyName]($data->current());
96
                } else {
97 1
                    $this->{$propertyName} = (string)$data->current();
98 1
                }
99
            }
100
        }
101
102
        //collect root element
103
        $propertyName = $data->getName();
104
        $ourPropertyName = array_search($propertyName, $this->propNameMap, true);
105
106 42
        if (false !== $ourPropertyName) {
107
            $propertyName = $ourPropertyName;
108 42
        }
109
110 View Code Duplication
        if (property_exists($this, $propertyName)) {
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...
111
            if (array_key_exists($propertyName, $this->mappingClasses)) {
112
                $this->{$propertyName} = new $this->mappingClasses[$propertyName]($data);
113
            } else {
114
                $this->{$propertyName} = (string)$data;
115
            }
116 1
        }
117
118 1
        return $this;
119
    }
120
121
    /**
122
     * Set from array
123
     *
124
     * @param array $data
125
     * @return $this
126
     */
127 40
    public function fromArray($data)
128
    {
129 40
        foreach ($data as $key => $val) {
130 40
            if (is_int($key)) {
131 40
                if (method_exists($this, "add")) {
132 38
                    $this->add($val);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Yandex\Common\Model as the method add() does only exist in the following sub-classes of Yandex\Common\Model: Yandex\DataSync\Models\Database\Delta\RecordFields, Yandex\DataSync\Models\Database\Delta\Records, Yandex\DataSync\Models\Database\Deltas, Yandex\DataSync\Models\Databases, Yandex\Market\Content\Models\Base\Models, Yandex\Market\Content\Models\Categories, Yandex\Market\Content\Models\Children, Yandex\Market\Content\Models\Comments, Yandex\Market\Content\Models\Contras, Yandex\Market\Content\Models\DeliveryMethods, Yandex\Market\Content\Models\Filters, Yandex\Market\Content\Models\GeoRegions, Yandex\Market\Content\Models\ModelOpinions, Yandex\Market\Content\Models\ModelVisualPhotos, Yandex\Market\Content\Models\OfferPhotos, Yandex\Market\Content\Models\Offers, Yandex\Market\Content\Models\Options, Yandex\Market\Content\Models\Outlets, Yandex\Market\Content\Models\Photos, Yandex\Market\Content\Models\Pros, Yandex\Market\Content\Models\Reviews, Yandex\Market\Content\Models\Schedules, Yandex\Market\Content\Models\SearchResults, Yandex\Market\Content\Models\ShopOpinions, Yandex\Market\Content\Models\Shops, Yandex\Market\Content\Models\Vendors, Yandex\Market\Partner\Models\Campaigns, Yandex\Market\Partner\Models\DeliveryOptions, Yandex\Market\Partner\Models\Items, Yandex\Market\Partner\Models\Orders, Yandex\Market\Partner\Models\Outlets, Yandex\Market\Partner\Models\StateReasons, Yandex\Metrica\Analytics\Models\ColumnHeaders, Yandex\Metrica\Management\Models\Accounts, Yandex\Metrica\Management\Models\Conditions, Yandex\Metrica\Management\Models\Counters, Yandex\Metrica\Management\Models\Delegates, Yandex\Metrica\Management\Models\Filters, Yandex\Metrica\Management\Models\Goals, Yandex\Metrica\Management\Models\Grants, Yandex\Metrica\Management\Models\Operations, Yandex\Metrica\Stat\Models\ComparisonData, Yandex\Metrica\Stat\Models\Data, Yandex\Metrica\Stat\Models\Dimensions, Yandex\Metrica\Stat\Models\DrillDownComparisonData, Yandex\Metrica\Stat\Models\DrillDownData, Yandex\Webmaster\Models\Hosts. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
133 38
                }
134
            }
135 38
136 38
            $propertyName = $key;
137 38
            $ourPropertyName = array_search($propertyName, $this->propNameMap);
138 38
139 38
            if ($ourPropertyName && isset($data[$ourPropertyName])) {
140
                $propertyName = $ourPropertyName;
141 38
            }
142 38
143
            if (!empty($this->propNameMap)) {
144 38
                if (array_key_exists($key, $this->propNameMap)) {
145 28
                    $propertyName = $this->propNameMap[$key];
146 28
                }
147 38
            }
148
149 38
            if (property_exists($this, $propertyName)) {
150 9 View Code Duplication
                if (isset($this->mappingClasses[$propertyName])) {
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...
151 9
                    $this->{$propertyName} = new $this->mappingClasses[$propertyName]($val);
152 9
                } else {
153 38
                    $this->{$propertyName} = $val;
154 18
                }
155 18
            }
156 18
        }
157 18
158 40
        return $this;
159 40
    }
160
161 18
    /**
162
     * Set from json
163
     *
164
     * @param string $json
165
     * @return $this
166
     */
167
    public function fromJson($json)
168
    {
169
        $this->fromArray(json_decode($json, true));
170
171
        return $this;
172
    }
173
174
    /**
175
     * Get array from object
176
     *
177
     * @return array
178
     */
179
    public function toArray()
180
    {
181
        return $this->toArrayRecursive($this);
182
    }
183
184
    /**
185
     * Get array from object
186
     *
187
     * @return string
188
     */
189
    public function toJson()
190
    {
191
        return json_encode($this->toArrayRecursive($this));
192
    }
193
194
    /**
195
     * Get array from object
196
     *
197
     * @param array|object $data
198
     * @return array
199
     */
200
    protected function toArrayRecursive($data)
201
    {
202
        if (is_array($data) || is_object($data)) {
203
            $result = [];
204
            foreach ($data as $key => $value) {
205
                if ($key === "mappingClasses" || $key === "propNameMap") {
206
                    continue;
207
                }
208
                $propNameMap = $key;
209
                $obj = $this;
210
                if (is_object($data)) {
211
                    $obj = $data;
212
                }
213
214
                if (property_exists($obj, $propNameMap)) {
215
                    $ourPropertyName = array_search($propNameMap, $obj->propNameMap);
216
217
                    if ($ourPropertyName) {
218
                        $propNameMap = $ourPropertyName;
219
                    }
220
                }
221
222
                if (is_object($value) && method_exists($value, "getAll")) {
223
                    if (method_exists($obj, 'toArrayRecursive')) {
224
                        $result[$propNameMap] = $obj->toArrayRecursive($value->getAll());
225
                    }
226
                } elseif ($value !== null) {
227
                    if (method_exists($obj, 'toArrayRecursive')) {
228
                        $result[$propNameMap] = $obj->toArrayRecursive($value);
229
                    }
230
                }
231
            }
232
233
            return $result;
234
        }
235
236
        return $data;
237
    }
238
}
239