Completed
Push — master ( 84ec5d...fda3a0 )
by Simonas
02:47
created

Converter   B

Complexity

Total Complexity 37

Size/Duplication

Total Lines 232
Duplicated Lines 4.31 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 9
Bugs 1 Features 3
Metric Value
wmc 37
c 9
b 1
f 3
lcom 1
cbo 3
dl 10
loc 232
rs 8.6

7 Methods

Rating   Name   Duplication   Size   Complexity  
C assignArrayToObject() 5 45 11
A __construct() 0 4 1
B convertToDocument() 0 26 4
C convertToArray() 5 58 14
A checkVariableType() 0 12 3
A isCollection() 0 10 3
A getAlias() 0 7 1

How to fix   Duplicated Code   

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:

1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\ElasticsearchBundle\Result;
13
14
use ONGR\ElasticsearchBundle\Collection\Collection;
15
use ONGR\ElasticsearchBundle\Mapping\MetadataCollector;
16
use ONGR\ElasticsearchBundle\Service\Manager;
17
18
/**
19
 * This class converts array to document object.
20
 */
21
class Converter
22
{
23
    /**
24
     * @var MetadataCollector
25
     */
26
    private $metadataCollector;
27
28
    /**
29
     * Constructor.
30
     *
31
     * @param MetadataCollector $metadataCollector
32
     */
33
    public function __construct($metadataCollector)
34
    {
35
        $this->metadataCollector = $metadataCollector;
36
    }
37
38
    /**
39
     * Converts raw array to document.
40
     *
41
     * @param array   $rawData
42
     * @param Manager $manager
43
     *
44
     * @return object
45
     *
46
     * @throws \LogicException
47
     */
48
    public function convertToDocument($rawData, Manager $manager)
49
    {
50
        $types = $this->metadataCollector->getMappings($manager->getConfig()['mappings']);
51
52
        if (isset($types[$rawData['_type']])) {
53
            $metadata = $types[$rawData['_type']];
54
        } else {
55
            throw new \LogicException("Got document of unknown type '{$rawData['_type']}'.");
56
        }
57
58
        switch (true) {
59
            case isset($rawData['_source']):
60
                $rawData = array_merge($rawData, $rawData['_source']);
61
                break;
62
            case isset($rawData['fields']):
63
                $rawData = array_merge($rawData, $rawData['fields']);
64
                break;
65
            default:
66
                // Do nothing.
67
                break;
68
        }
69
70
        $object = $this->assignArrayToObject($rawData, new $metadata['namespace'](), $metadata['aliases']);
71
72
        return $object;
73
    }
74
75
    /**
76
     * Assigns all properties to object.
77
     *
78
     * @param array            $array
79
     * @param \ReflectionClass $object
80
     * @param array            $aliases
81
     *
82
     * @return object
83
     */
84
    public function assignArrayToObject(array $array, $object, array $aliases)
85
    {
86
        foreach ($array as $name => $value) {
87
            if (!isset($aliases[$name])) {
88
                continue;
89
            }
90
91
            if (isset($aliases[$name]['type'])) {
92
                switch ($aliases[$name]['type']) {
93
                    case 'date':
94
                        $value = \DateTime::createFromFormat(
95
                            isset($aliases[$name]['format']) ? $aliases[$name]['format'] : \DateTime::ISO8601,
96
                            $value
97
                        );
98
                        break;
99
                    case 'object':
100
                    case 'nested':
101
                        if ($aliases[$name]['multiple']) {
102
                            $value = new ObjectIterator($this, $value, $aliases[$name]);
103
                        } else {
104
                            if (!isset($value)) {
105
                                break;
106
                            }
107
                            $value = $this->assignArrayToObject(
108
                                $value,
109
                                new $aliases[$name]['namespace'](),
110
                                $aliases[$name]['aliases']
111
                            );
112
                        }
113
                        break;
114
                    default:
115
                        // Do nothing here. Default cas is required by our code style standard.
116
                        break;
117
                }
118
            }
119
120 View Code Duplication
            if ($aliases[$name]['propertyType'] == 'private') {
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...
121
                $object->{$aliases[$name]['methods']['setter']}($value);
122
            } else {
123
                $object->{$aliases[$name]['propertyName']} = $value;
124
            }
125
        }
126
127
        return $object;
128
    }
129
130
    /**
131
     * Converts object to an array.
132
     *
133
     * @param mixed $object
134
     * @param array $aliases
135
     * @param array $fields
136
     *
137
     * @return array
138
     */
139
    public function convertToArray($object, $aliases = [], $fields = [])
140
    {
141
        if (empty($aliases)) {
142
            $aliases = $this->getAlias($object);
143
            if (count($fields) > 0) {
144
                $aliases = array_intersect_key($aliases, array_flip($fields));
145
            }
146
        }
147
148
        $array = [];
149
150
        // Variable $name defined in client.
151
        foreach ($aliases as $name => $alias) {
152 View Code Duplication
            if ($aliases[$name]['propertyType'] == 'private') {
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...
153
                $value = $object->{$aliases[$name]['methods']['getter']}();
154
            } else {
155
                $value = $object->{$aliases[$name]['propertyName']};
156
            }
157
158
            if (isset($value)) {
159
                if (array_key_exists('aliases', $alias)) {
160
                    $new = [];
161
                    if ($alias['multiple']) {
162
                        $this->isCollection($aliases[$name]['propertyName'], $value);
163
                        foreach ($value as $item) {
164
                            $this->checkVariableType($item, [$alias['namespace']]);
165
                            $new[] = $this->convertToArray($item, $alias['aliases']);
166
                        }
167
                    } else {
168
                        $this->checkVariableType($value, [$alias['namespace']]);
169
                        $new = $this->convertToArray($value, $alias['aliases']);
170
                    }
171
                    $value = $new;
172
                }
173
174
                if ($value instanceof \DateTime) {
175
                    $value = $value->format(isset($alias['format']) ? $alias['format'] : \DateTime::ISO8601);
176
                }
177
178
                if (isset($alias['type'])) {
179
                    switch ($alias['type']) {
180
                        case 'float':
181
                            $value = (float)$value;
182
                            break;
183
                        case 'integer':
184
                            $value = (int)$value;
185
                            break;
186
                        default:
187
                            break;
188
                    }
189
                }
190
191
                $array[$name] = $value;
192
            }
193
        }
194
195
        return $array;
196
    }
197
198
    /**
199
     * Check if class matches the expected one.
200
     *
201
     * @param object $object
202
     * @param array  $expectedClasses
203
     *
204
     * @throws \InvalidArgumentException
205
     */
206
    private function checkVariableType($object, array $expectedClasses)
207
    {
208
        if (!is_object($object)) {
209
            $msg = 'Expected variable of type object, got ' . gettype($object) . ". (field isn't multiple)";
210
            throw new \InvalidArgumentException($msg);
211
        }
212
213
        $class = get_class($object);
214
        if (!in_array($class, $expectedClasses)) {
215
            throw new \InvalidArgumentException("Expected object of type {$expectedClasses[0]}, got {$class}.");
216
        }
217
    }
218
219
    /**
220
     * Check if value is instance of Collection.
221
     *
222
     * @param string $property
223
     * @param mixed  $value
224
     *
225
     * @throws \InvalidArgumentException
226
     */
227
    private function isCollection($property, $value)
228
    {
229
        if (!$value instanceof Collection) {
230
            $got = is_object($value) ? get_class($value) : gettype($value);
231
232
            throw new \InvalidArgumentException(
233
                sprintf('Value of "%s" property must be an instance of Collection, got %s.', $property, $got)
234
            );
235
        }
236
    }
237
238
    /**
239
     * Returns aliases for certain document.
240
     *
241
     * @param object $document
242
     *
243
     * @return array
244
     */
245
    private function getAlias($document)
246
    {
247
        $class = get_class($document);
248
        $documentMapping = $this->metadataCollector->getMapping($class);
249
250
        return $documentMapping['aliases'];
251
    }
252
}
253