Completed
Pull Request — master (#917)
by Dmitry
08:52
created

ModelToElasticaAutoTransformer   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 187
Duplicated Lines 6.42 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 95.52%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 32
c 3
b 0
f 0
lcom 1
cbo 4
dl 12
loc 187
ccs 64
cts 67
cp 0.9552
rs 9.6

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setPropertyAccessor() 0 4 1
A __construct() 0 5 1
B transformNested() 0 18 6
C transformObjectToDocument() 12 63 15
A transform() 0 7 1
B normalizeValue() 0 19 8

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
namespace FOS\ElasticaBundle\Transformer;
4
5
use FOS\ElasticaBundle\Event\TransformEvent;
6
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
7
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
8
use Elastica\Document;
9
10
/**
11
 * Maps Elastica documents with Doctrine objects
12
 * This mapper assumes an exact match between
13
 * elastica documents ids and doctrine object ids.
14
 */
15
class ModelToElasticaAutoTransformer implements ModelToElasticaTransformerInterface
16
{
17
    /**
18
     * @var EventDispatcherInterface
19
     */
20
    protected $dispatcher;
21
22
    /**
23
     * Optional parameters.
24
     *
25
     * @var array
26
     */
27
    protected $options = array(
28
        'identifier' => 'id',
29
    );
30
31
    /**
32
     * PropertyAccessor instance.
33
     *
34
     * @var PropertyAccessorInterface
35
     */
36
    protected $propertyAccessor;
37
38
    /**
39
     * Instanciates a new Mapper.
40
     *
41
     * @param array                    $options
42
     * @param EventDispatcherInterface $dispatcher
43
     */
44 34
    public function __construct(array $options = array(), EventDispatcherInterface $dispatcher = null)
45
    {
46 34
        $this->options = array_merge($this->options, $options);
47 34
        $this->dispatcher = $dispatcher;
48 34
    }
49
50
    /**
51
     * Set the PropertyAccessor.
52
     *
53
     * @param PropertyAccessorInterface $propertyAccessor
54
     */
55 34
    public function setPropertyAccessor(PropertyAccessorInterface $propertyAccessor)
56
    {
57 34
        $this->propertyAccessor = $propertyAccessor;
58 34
    }
59
60
    /**
61
     * Transforms an object into an elastica object having the required keys.
62
     *
63
     * @param object $object the object to convert
64
     * @param array  $fields the keys we want to have in the returned array
65
     *
66
     * @return Document
67
     **/
68 24
    public function transform($object, array $fields)
69
    {
70 24
        $identifier = $this->propertyAccessor->getValue($object, $this->options['identifier']);
71 24
        $document = $this->transformObjectToDocument($object, $fields, $identifier);
72
73 23
        return $document;
74
    }
75
76
    /**
77
     * transform a nested document or an object property into an array of ElasticaDocument.
78
     *
79
     * @param array|\Traversable|\ArrayAccess $objects the object to convert
80
     * @param array                           $fields  the keys we want to have in the returned array
81
     *
82
     * @return array
83
     */
84 4
    protected function transformNested($objects, array $fields)
85
    {
86 4
        if (is_array($objects) || $objects instanceof \Traversable || $objects instanceof \ArrayAccess) {
87 3
            $documents = array();
88 3
            foreach ($objects as $object) {
89 3
                $document = $this->transformObjectToDocument($object, $fields);
90 3
                $documents[] = $document->getData();
91
            }
92
93 3
            return $documents;
94 1
        } elseif (null !== $objects) {
95 1
            $document = $this->transformObjectToDocument($objects, $fields);
96
97 1
            return $document->getData();
98
        }
99
100
        return array();
101
    }
102
103
    /**
104
     * Attempts to convert any type to a string or an array of strings.
105
     *
106
     * @param mixed $value
107
     *
108
     * @return string|array
109
     */
110
    protected function normalizeValue($value)
111
    {
112 16
        $normalizeValue = function (&$v) {
113 16
            if ($v instanceof \DateTime) {
114 2
                $v = $v->format('c');
115 16
            } elseif (!is_scalar($v) && !is_null($v)) {
116
                $v = (string) $v;
117
            }
118 16
        };
119
120 16
        if (is_array($value) || $value instanceof \Traversable || $value instanceof \ArrayAccess) {
121 5
            $value = is_array($value) ? $value : iterator_to_array($value, false);
122 5
            array_walk_recursive($value, $normalizeValue);
123
        } else {
124 12
            $normalizeValue($value);
125
        }
126
127 16
        return $value;
128
    }
129
130
    /**
131
     * Transforms the given object to an elastica document
132
     *
133
     * @param object $object the object to convert
134
     * @param array  $fields the keys we want to have in the returned array
135
     * @param string $identifier the identifier for the new document
136
     * @return Document
137
     */
138 24
    protected function transformObjectToDocument($object, array $fields, $identifier = '')
139
    {
140 24
        $document = new Document($identifier);
141
142 24 View Code Duplication
        if ($this->dispatcher) {
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...
143 1
            $event = new TransformEvent($document, $fields, $object);
144 1
            $this->dispatcher->dispatch(TransformEvent::PRE_TRANSFORM, $event);
145
146 1
            $document = $event->getDocument();
147
        }
148
149 24
        foreach ($fields as $key => $mapping) {
150 23
            if ($key == '_parent') {
151 4
                $property = (null !== $mapping['property']) ? $mapping['property'] : $mapping['type'];
152 4
                $value = $this->propertyAccessor->getValue($object, $property);
153 4
                $document->setParent($this->propertyAccessor->getValue($value, $mapping['identifier']));
154
155 4
                continue;
156
            }
157
158 19
            $path = isset($mapping['property_path']) ?
159 1
                $mapping['property_path'] :
160 19
                $key;
161 19
            if (false === $path) {
162 1
                continue;
163
            }
164 19
            $value = $this->propertyAccessor->getValue($object, $path);
165
166 18
            if (isset($mapping['type']) && in_array(
167 18
                    $mapping['type'], array('nested', 'object')
168 18
                ) && isset($mapping['properties']) && !empty($mapping['properties'])
169
            ) {
170
                /* $value is a nested document or object. Transform $value into
171
                 * an array of documents, respective the mapped properties.
172
                 */
173 4
                $document->set($key, $this->transformNested($value, $mapping['properties']));
174
175 4
                continue;
176
            }
177
178 18
            if (isset($mapping['type']) && $mapping['type'] == 'attachment') {
179
                // $value is an attachment. Add it to the document.
180 2
                if ($value instanceof \SplFileInfo) {
181 2
                    $document->addFile($key, $value->getPathName());
182
                } else {
183
                    $document->addFileContent($key, $value);
184
                }
185
186 2
                continue;
187
            }
188
189 16
            $document->set($key, $this->normalizeValue($value));
190
        }
191
192 23 View Code Duplication
        if ($this->dispatcher) {
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...
193 1
            $event = new TransformEvent($document, $fields, $object);
194 1
            $this->dispatcher->dispatch(TransformEvent::POST_TRANSFORM, $event);
195
196 1
            $document = $event->getDocument();
197
        }
198
199 23
        return $document;
200
    }
201
}
202