Completed
Pull Request — master (#162)
by
unknown
11:16
created

Model::fromJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 1
b 0
f 0
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 157
    public function __construct($data = [])
47
    {
48 157
        $this->fromArray($data);
49 157
    }
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 155
    public function fromArray($data)
112
    {
113 155
        foreach ($data as $key => $val) {
114 119
            if (is_int($key)) {
115 72
                if (method_exists($this, "add")) {
116 72
                    $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 72
                }
118 72
            }
119
120 119
            $propertyName = $key;
121 119
            $ourPropertyName = array_search($propertyName, $this->propNameMap);
122
123 119
            if ($ourPropertyName && isset($data[$ourPropertyName])) {
124
                $propertyName = $ourPropertyName;
125
            }
126
127 119
            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 119
            if (property_exists($this, $propertyName)) {
134 111 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 83
                    $this->{$propertyName} = new $this->mappingClasses[$propertyName]($val);
136 83
                } else {
137 111
                    $this->{$propertyName} = $val;
138
                }
139 111
            }
140 155
        }
141
142 155
        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 43
    public function toArray()
164
    {
165 43
        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 41
    protected function toArrayRecursive($data)
185
    {
186 41
        if (is_array($data) || is_object($data)) {
187 41
            $result = [];
188 41
            foreach ($data as $key => $value) {
189 39
                if ($key === "mappingClasses" || $key === "propNameMap") {
190 39
                    continue;
191
                }
192 39
                $propNameMap = $key;
193 39
                $obj = $this;
194 39
                if (is_object($data)) {
195 39
                    $obj = $data;
196 39
                }
197
198 39
                if (property_exists($obj, $propNameMap)) {
199 39
                    $ourPropertyName = array_search($propNameMap, $obj->propNameMap);
200
201 39
                    if ($ourPropertyName) {
202 28
                        $propNameMap = $ourPropertyName;
203 28
                    }
204 39
                }
205
206 39
                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 39
                } elseif ($value !== null) {
211 18
                    if (method_exists($obj, 'toArrayRecursive')) {
212 18
                        $result[$propNameMap] = $obj->toArrayRecursive($value);
213 18
                    }
214 18
                }
215 41
            }
216
217 41
            return $result;
218
        }
219
220 18
        return $data;
221
    }
222
}
223