Completed
Pull Request — master (#139)
by
unknown
04:18
created

Model::toArrayRecursive()   C

Complexity

Conditions 11
Paths 9

Size

Total Lines 29
Code Lines 17

Duplication

Lines 7
Ratio 24.14 %

Code Coverage

Tests 14
CRAP Score 15.4801

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 7
loc 29
ccs 14
cts 21
cp 0.6667
rs 5.2653
cc 11
eloc 17
nc 9
nop 1
crap 15.4801

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
 * @package Yandex\Common
17
 */
18
abstract class Model
19
{
20
    protected $mappingClasses = [];
21
22
    /**
23
     * Contains property name mappings.
24
     *
25
     * [
26
     *  'data_array_property1' => 'objectProperty1',
27
     *  'data_array_property2' => 'objectProperty2',
28
     * ]
29
     *
30
     * Data array property uses as keys
31
     * because there is can be more then one rule per object property
32
     *
33
     * f.g. $data['nmodels'] and ['modelsnum'] should map in modelsCount property.
34
     * Otherwise not unique array keys cause remapping of properties.
35
     *
36
     * @var array
37
     */
38
    protected $propNameMap = [];
39
40
    /**
41
     * Constructor
42
     *
43
     * @param array $data
44
     */
45 71
    public function __construct($data = [])
46
    {
47 71
        $this->fromArray($data);
48 71
    }
49
50
    /**
51
     * Set from array
52
     *
53
     * @param array $data
54
     * @return $this
55
     */
56 71
    public function fromArray($data)
57
    {
58 71
        foreach ($data as $key => $val) {
59 47
            if (is_int($key)) {
60 37
                if (method_exists($this, "add")) {
61 37
                    $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\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. 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...
62 37
                }
63 37
            }
64
65 47
            $propertyName = $key;
66 47
            $ourPropertyName = array_search($propertyName, $this->propNameMap);
67
68 47
            if ($ourPropertyName && isset($data[$ourPropertyName])) {
69
                $propertyName = $ourPropertyName;
70
            }
71
72 47
            if (!empty($this->propNameMap)) {
73 37
                if (array_key_exists($key, $this->propNameMap)) {
74 36
                    $propertyName = $this->propNameMap[$key];
75 36
                }
76 37
            }
77
78 47
            if (property_exists($this, $propertyName)) {
79 47
                if (isset($this->mappingClasses[$propertyName])) {
80 46
                    $this->{$propertyName} = new $this->mappingClasses[$propertyName]($val);
81 46
                } else {
82 47
                    $this->{$propertyName} = $val;
83
                }
84 47
            }
85 71
        }
86 71
        return $this;
87
    }
88
89
    /**
90
     * Set from json
91
     *
92
     * @param string $json
93
     * @return $this
94
     */
95
    public function fromJson($json)
96
    {
97
        $this->fromArray(json_decode($json, true));
98
        return $this;
99
    }
100
101
    /**
102
     * Get array from object
103
     *
104
     * @return array
105
     */
106 8
    public function toArray()
107
    {
108 8
        return $this->toArrayRecursive($this);
109
    }
110
111
    /**
112
     * Get array from object
113
     *
114
     * @return string
115
     */
116
    public function toJson()
117
    {
118
        return json_encode($this->toArrayRecursive($this));
119
    }
120
121
    /**
122
     * Get array from object
123
     *
124
     * @param array|object $data
125
     * @return array
126
     */
127 8
    protected function toArrayRecursive($data)
128
    {
129 8
        if (is_array($data) || is_object($data)) {
130 8
            $result = [];
131 8
            foreach ($data as $key => $value) {
132 8
                if ($key === "mappingClasses" || $key === "propNameMap") {
133 8
                    continue;
134
                }
135
136 8
                $propNameMap = $key;
137
138 8
                if (!empty($this->propNameMap)
139 8
                    && array_key_exists($key, $this->propNameMap)
140 8
                ) {
141
                    $propNameMap = $this->propNameMap[$key];
142
                }
143
144 8 View Code Duplication
                if (is_object($value) && method_exists($value, "getAll")) {
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...
145
                    $result[$propNameMap] = $this->toArrayRecursive($value->getAll());
146
                } else {
147 8
                    if ($value !== null) {
148
                        $result[$propNameMap] = $this->toArrayRecursive($value);
149
                    }
150
                }
151 8
            }
152 8
            return $result;
153
        }
154
        return $data;
155
    }
156
}
157