Completed
Pull Request — master (#162)
by
unknown
08:31
created

Model::toJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
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
        return $this;
103
    }
104
105
    /**
106 42
     * Set from array
107
     *
108 42
     * @param array $data
109
     * @return $this
110
     */
111
    public function fromArray($data)
112
    {
113
        foreach ($data as $key => $val) {
114
            if (is_int($key)) {
115
                if (method_exists($this, "add")) {
116 1
                    $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
                }
118 1
            }
119
120
            $propertyName = $key;
121
            $ourPropertyName = array_search($propertyName, $this->propNameMap);
122
123
            if ($ourPropertyName && isset($data[$ourPropertyName])) {
124
                $propertyName = $ourPropertyName;
125
            }
126
127 40
            if (!empty($this->propNameMap)) {
128
                if (array_key_exists($key, $this->propNameMap)) {
129 40
                    $propertyName = $this->propNameMap[$key];
130 40
                }
131 40
            }
132 38
133 38
            if (property_exists($this, $propertyName)) {
134 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 38
                    $this->{$propertyName} = new $this->mappingClasses[$propertyName]($val);
136 38
                } else {
137 38
                    $this->{$propertyName} = $val;
138 38
                }
139 38
            }
140
        }
141 38
142 38
        return $this;
143
    }
144 38
145 28
    /**
146 28
     * Set from json
147 38
     *
148
     * @param string $json
149 38
     * @return $this
150 9
     */
151 9
    public function fromJson($json)
152 9
    {
153 38
        $this->fromArray(json_decode($json, true));
154 18
155 18
        return $this;
156 18
    }
157 18
158 40
    /**
159 40
     * Get array from object
160
     *
161 18
     * @return array
162
     */
163
    public function toArray()
164
    {
165
        return $this->toArrayRecursive($this);
166
    }
167
168
    /**
169
     * Get array from object
170
     *
171
     * @return string
172
     */
173
    public function toJson()
174
    {
175
        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
    protected function toArrayRecursive($data)
185
    {
186
        if (is_array($data) || is_object($data)) {
187
            $result = [];
188
            foreach ($data as $key => $value) {
189
                if ($key === "mappingClasses" || $key === "propNameMap") {
190
                    continue;
191
                }
192
                $propNameMap = $key;
193
                $obj = $this;
194
                if (is_object($data)) {
195
                    $obj = $data;
196
                }
197
198
                if (property_exists($obj, $propNameMap)) {
199
                    $ourPropertyName = array_search($propNameMap, $obj->propNameMap);
200
201
                    if ($ourPropertyName) {
202
                        $propNameMap = $ourPropertyName;
203
                    }
204
                }
205
206
                if (is_object($value) && method_exists($value, "getAll")) {
207
                    if (method_exists($obj, 'toArrayRecursive')) {
208
                        $result[$propNameMap] = $obj->toArrayRecursive($value->getAll());
209
                    }
210
                } elseif ($value !== null) {
211
                    if (method_exists($obj, 'toArrayRecursive')) {
212
                        $result[$propNameMap] = $obj->toArrayRecursive($value);
213
                    }
214
                }
215
            }
216
217
            return $result;
218
        }
219
220
        return $data;
221
    }
222
}
223