Completed
Pull Request — master (#162)
by
unknown
06:39
created

Model::fromXml()   C

Complexity

Conditions 11
Paths 16

Size

Total Lines 47
Code Lines 24

Duplication

Lines 7
Ratio 14.89 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 11
eloc 24
c 1
b 0
f 1
nc 16
nop 1
dl 7
loc 47
ccs 0
cts 32
cp 0
crap 132
rs 5.2653

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
     */
46 152
    public function __construct($data = [])
47
    {
48 152
        $this->fromArray($data);
49 152
    }
50
51
    /**
52
     * Set from XML
53
     *
54
     * @param \SimpleXMLIterator $data
55
     * @return $this
56
     */
57
    public function fromXml(\SimpleXMLIterator $data)
58
    {
59
        //todo: refactor fromXml()
60
        if (method_exists($this, 'add')) {
61
            for ($data->rewind(); $data->valid(); $data->next()) {
62
                $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
            }
64
65
            return $this;
66
        }
67
68
        //collect attributes
69
        if ($data->attributes()->count() > 0) {
70
            foreach ($data->attributes() as $key => $attribute) {
71
                $propertyName = $key;
72
                $ourPropertyName = array_search($propertyName, $this->propNameMap, true);
73
74
                if (false !== $ourPropertyName) {
75
                    $propertyName = $ourPropertyName;
76
                }
77
78
                if (property_exists($this, $propertyName)) {
79
                    $this->{$propertyName} = (string)$attribute;
80
                }
81
            }
82
        }
83
84
        //collect node data
85
        for ($data->rewind(); $data->valid(); $data->next()) {
86
            $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
                    $this->{$propertyName} = new $this->mappingClasses[$propertyName]($data->current());
96
                } else {
97
                    $this->{$propertyName} = (string)$data->current();
98
                }
99
            }
100
        }
101
102
        return $this;
103
    }
104
105
    /**
106
     * Set from array
107
     *
108
     * @param array $data
109
     * @return $this
110
     */
111 150
    public function fromArray($data)
112
    {
113 150
        foreach ($data as $key => $val) {
114 114
            if (is_int($key)) {
115 67
                if (method_exists($this, "add")) {
116 67
                    $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...
117 67
                }
118 67
            }
119
120 114
            $propertyName = $key;
121 114
            $ourPropertyName = array_search($propertyName, $this->propNameMap);
122
123 114
            if ($ourPropertyName && isset($data[$ourPropertyName])) {
124
                $propertyName = $ourPropertyName;
125
            }
126
127 114
            if (!empty($this->propNameMap)) {
128 79
                if (array_key_exists($key, $this->propNameMap)) {
129 73
                    $propertyName = $this->propNameMap[$key];
130 73
                }
131 79
            }
132
133 114
            if (property_exists($this, $propertyName)) {
134 106 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...
135 78
                    $this->{$propertyName} = new $this->mappingClasses[$propertyName]($val);
136 78
                } else {
137 106
                    $this->{$propertyName} = $val;
138
                }
139 106
            }
140 150
        }
141
142 150
        return $this;
143
    }
144
145
    /**
146
     * Set from json
147
     *
148
     * @param string $json
149
     * @return $this
150
     */
151 1
    public function fromJson($json)
152
    {
153 1
        $this->fromArray(json_decode($json, true));
154
155 1
        return $this;
156
    }
157
158
    /**
159
     * Get array from object
160
     *
161
     * @return array
162
     */
163 42
    public function toArray()
164
    {
165 42
        return $this->toArrayRecursive($this);
166
    }
167
168
    /**
169
     * Get array from object
170
     *
171
     * @return string
172
     */
173 1
    public function toJson()
174
    {
175 1
        return json_encode($this->toArrayRecursive($this));
176
    }
177
178
    /**
179
     * Get array from object
180
     *
181
     * @param array|object $data
182
     * @return array
183
     */
184 40
    protected function toArrayRecursive($data)
185
    {
186 40
        if (is_array($data) || is_object($data)) {
187 40
            $result = [];
188 40
            foreach ($data as $key => $value) {
189 38
                if ($key === "mappingClasses" || $key === "propNameMap") {
190 38
                    continue;
191
                }
192 38
                $propNameMap = $key;
193 38
                $obj = $this;
194 38
                if (is_object($data)) {
195 38
                    $obj = $data;
196 38
                }
197
198 38
                if (property_exists($obj, $propNameMap)) {
199 38
                    $ourPropertyName = array_search($propNameMap, $obj->propNameMap);
200
201 38
                    if ($ourPropertyName) {
202 28
                        $propNameMap = $ourPropertyName;
203 28
                    }
204 38
                }
205
206 38
                if (is_object($value) && method_exists($value, "getAll")) {
207 9
                    if (method_exists($obj, 'toArrayRecursive')) {
208 9
                        $result[$propNameMap] = $obj->toArrayRecursive($value->getAll());
209 9
                    }
210 38
                } elseif ($value !== null) {
211 18
                    if (method_exists($obj, 'toArrayRecursive')) {
212 18
                        $result[$propNameMap] = $obj->toArrayRecursive($value);
213 18
                    }
214 18
                }
215 40
            }
216
217 40
            return $result;
218
        }
219
220 18
        return $data;
221
    }
222
}
223