Completed
Push — master ( ca3bac...db7ab3 )
by David de
26:54 queued 16:58
created

DoctrineWriter   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 317
Duplicated Lines 5.36 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 42
lcom 1
cbo 8
dl 17
loc 317
rs 8.295
c 0
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 3
A ensureSupportedObjectManager() 0 8 3
A getTruncate() 0 4 1
A setTruncate() 0 6 1
A disableTruncate() 0 6 1
A prepare() 0 8 2
A getNewInstance() 0 10 2
A setValue() 0 6 2
A finish() 0 5 1
A writeItem() 0 9 1
C updateObject() 0 24 7
B loadAssociationObjectsToObject() 0 17 5
A truncateTable() 0 11 3
A disableLogging() 9 9 2
A reEnableLogging() 8 8 2
B findOrCreateItem() 0 25 5
A flush() 0 5 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DoctrineWriter often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DoctrineWriter, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Port\Doctrine;
4
5
use Port\Doctrine\Exception\UnsupportedDatabaseTypeException;
6
use Port\Writer;
7
use Doctrine\Common\Util\Inflector;
8
use Doctrine\DBAL\Logging\SQLLogger;
9
use Doctrine\Common\Persistence\ObjectManager;
10
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
11
12
/**
13
 * A bulk Doctrine writer
14
 *
15
 * See also the {@link http://www.doctrine-project.org/docs/orm/2.1/en/reference/batch-processing.html Doctrine documentation}
16
 * on batch processing.
17
 *
18
 * @author David de Boer <[email protected]>
19
 */
20
class DoctrineWriter implements Writer, Writer\FlushableWriter
21
{
22
    /**
23
     * Doctrine object manager
24
     *
25
     * @var ObjectManager
26
     */
27
    protected $objectManager;
28
29
    /**
30
     * Fully qualified model name
31
     *
32
     * @var string
33
     */
34
    protected $objectName;
35
36
    /**
37
     * Doctrine object repository
38
     *
39
     * @var ObjectRepository
40
     */
41
    protected $objectRepository;
42
43
    /**
44
     * @var ClassMetadata
45
     */
46
    protected $objectMetadata;
47
48
    /**
49
     * Original Doctrine logger
50
     *
51
     * @var SQLLogger
52
     */
53
    protected $originalLogger;
54
55
    /**
56
     * Whether to truncate the table first
57
     *
58
     * @var boolean
59
     */
60
    protected $truncate = true;
61
62
    /**
63
     * List of fields used to lookup an object
64
     *
65
     * @var array
66
     */
67
    protected $lookupFields = array();
68
69
    /**
70
     * Constructor
71
     *
72
     * @param ObjectManager $objectManager
73
     * @param string        $objectName
74
     * @param string|array        $index         Field or fields to find current entities by
75
     */
76
    public function __construct(ObjectManager $objectManager, $objectName, $index = null)
77
    {
78
        $this->ensureSupportedObjectManager($objectManager);
79
        $this->objectManager = $objectManager;
80
        $this->objectRepository = $objectManager->getRepository($objectName);
0 ignored issues
show
Documentation Bug introduced by
It seems like $objectManager->getRepository($objectName) of type object<Doctrine\Common\P...tence\ObjectRepository> is incompatible with the declared type object<Port\Doctrine\ObjectRepository> of property $objectRepository.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
81
        $this->objectMetadata = $objectManager->getClassMetadata($objectName);
82
        //translate objectName in case a namespace alias is used
83
        $this->objectName = $this->objectMetadata->getName();
84
        if($index) {
85
            if(is_array($index)) {
86
                $this->lookupFields = $index;
87
            } else {
88
                $this->lookupFields = [$index];
89
            }
90
        }
91
    }
92
    
93
    protected function ensureSupportedObjectManager(ObjectManager $objectManager)
94
    {
95
        if (!($objectManager instanceof \Doctrine\ORM\EntityManager
96
            || $objectManager instanceof \Doctrine\ODM\MongoDB\DocumentManager)
97
        ) {
98
            throw new UnsupportedDatabaseTypeException($objectManager);
99
        }
100
    }
101
102
    /**
103
     * @return boolean
104
     */
105
    public function getTruncate()
106
    {
107
        return $this->truncate;
108
    }
109
110
    /**
111
     * Set whether to truncate the table first
112
     *
113
     * @param boolean $truncate
114
     *
115
     * @return $this
116
     */
117
    public function setTruncate($truncate)
118
    {
119
        $this->truncate = $truncate;
120
121
        return $this;
122
    }
123
124
    /**
125
     * Disable truncation
126
     *
127
     * @return $this
128
     */
129
    public function disableTruncate()
130
    {
131
        $this->truncate = false;
132
133
        return $this;
134
    }
135
136
    /**
137
     * Disable Doctrine logging
138
     *
139
     * @return $this
140
     */
141
    public function prepare()
142
    {
143
        $this->disableLogging();
144
145
        if (true === $this->truncate) {
146
            $this->truncateTable();
147
        }
148
    }
149
150
    /**
151
     * Return a new instance of the object
152
     *
153
     * @return object
154
     */
155
    protected function getNewInstance()
156
    {
157
        $className = $this->objectMetadata->getName();
158
159
        if (class_exists($className) === false) {
160
            throw new \RuntimeException('Unable to create new instance of ' . $className);
161
        }
162
163
        return new $className;
164
    }
165
166
    /**
167
     * Call a setter of the object
168
     *
169
     * @param object $object
170
     * @param mixed  $value
171
     * @param string $setter
172
     */
173
    protected function setValue($object, $value, $setter)
174
    {
175
        if (method_exists($object, $setter)) {
176
            $object->$setter($value);
177
        }
178
    }
179
180
    /**
181
     * Re-enable Doctrine logging
182
     *
183
     * @return $this
184
     */
185
    public function finish()
186
    {
187
        $this->flush();
188
        $this->reEnableLogging();
189
    }
190
191
    /**
192
     * {@inheritdoc}
193
     */
194
    public function writeItem(array $item)
195
    {
196
        $object = $this->findOrCreateItem($item);
197
198
        $this->loadAssociationObjectsToObject($item, $object);
199
        $this->updateObject($item, $object);
200
201
        $this->objectManager->persist($object);
202
    }
203
204
    /**
205
     * @param array  $item
206
     * @param object $object
207
     */
208
    protected function updateObject(array $item, $object)
209
    {
210
        $fieldNames = array_merge($this->objectMetadata->getFieldNames(), $this->objectMetadata->getAssociationNames());
211
        foreach ($fieldNames as $fieldName) {
212
            $value = null;
213
            $classifiedFieldName = Inflector::classify($fieldName);
214
            if (isset($item[$fieldName])) {
215
                $value = $item[$fieldName];
216
            } elseif (method_exists($item, 'get' . $classifiedFieldName)) {
217
                $value = $item->{'get' . $classifiedFieldName};
218
            }
219
220
            if (null === $value) {
221
                continue;
222
            }
223
224
            if (!($value instanceof \DateTime)
225
                || $value != $this->objectMetadata->getFieldValue($object, $fieldName)
226
            ) {
227
                $setter = 'set' . $classifiedFieldName;
228
                $this->setValue($object, $value, $setter);
229
            }
230
        }
231
    }
232
233
    /**
234
     * Add the associated objects in case the item have for persist its relation
235
     *
236
     * @param array  $item
237
     * @param object $object
238
     */
239
    protected function loadAssociationObjectsToObject(array $item, $object)
240
    {
241
        foreach ($this->objectMetadata->getAssociationMappings() as $associationMapping) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\Mapping\ClassMetadata as the method getAssociationMappings() does only exist in the following implementations of said interface: Doctrine\ORM\Mapping\ClassMetadata, Doctrine\ORM\Mapping\ClassMetadataInfo.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
242
243
            $value = null;
244
            if (isset($item[$associationMapping['fieldName']]) && !is_object($item[$associationMapping['fieldName']])) {
245
                $value = $this->objectManager->getReference($associationMapping['targetEntity'], $item[$associationMapping['fieldName']]);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\ObjectManager as the method getReference() does only exist in the following implementations of said interface: Doctrine\ODM\MongoDB\DocumentManager, Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
246
            }
247
248
            if (null === $value) {
249
                continue;
250
            }
251
252
            $setter = 'set' . ucfirst($associationMapping['fieldName']);
253
            $this->setValue($object, $value, $setter);
254
        }
255
    }
256
257
    /**
258
     * Truncate the database table for this writer
259
     */
260
    protected function truncateTable()
261
    {
262
        if ($this->objectManager instanceof \Doctrine\ORM\EntityManager) {
263
            $tableName = $this->objectMetadata->table['name'];
0 ignored issues
show
Bug introduced by
Accessing table on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
264
            $connection = $this->objectManager->getConnection();
265
            $query = $connection->getDatabasePlatform()->getTruncateTableSQL($tableName, true);
266
            $connection->executeQuery($query);
267
        } elseif ($this->objectManager instanceof \Doctrine\ODM\MongoDB\DocumentManager) {
268
            $this->objectManager->getDocumentCollection($this->objectName)->remove(array());
269
        }
270
    }
271
272
    /**
273
     * Disable Doctrine logging
274
     */
275 View Code Duplication
    protected function disableLogging()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
276
    {
277
        //TODO: do we need to add support for MongoDB logging?
278
        if (!($this->objectManager instanceof \Doctrine\ORM\EntityManager)) return;
279
280
        $config = $this->objectManager->getConnection()->getConfiguration();
281
        $this->originalLogger = $config->getSQLLogger();
282
        $config->setSQLLogger(null);
283
    }
284
285
    /**
286
     * Re-enable Doctrine logging
287
     */
288 View Code Duplication
    protected function reEnableLogging()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
289
    {
290
        //TODO: do we need to add support for MongoDB logging?
291
        if (!($this->objectManager instanceof \Doctrine\ORM\EntityManager)) return;
292
293
        $config = $this->objectManager->getConnection()->getConfiguration();
294
        $config->setSQLLogger($this->originalLogger);
295
    }
296
297
    /**
298
     * Finds existing object or create a new instance
299
     *
300
     * @param array $item
301
     */
302
    protected function findOrCreateItem(array $item)
303
    {
304
        $object = null;
305
        // If the table was not truncated to begin with, find current object
306
        // first
307
        if (false === $this->truncate) {
308
            if (!empty($this->lookupFields)) {
309
                $lookupConditions = array();
310
                foreach ($this->lookupFields as $fieldName) {
311
                    $lookupConditions[$fieldName] = $item[$fieldName];
312
}
313
                $object = $this->objectRepository->findOneBy(
314
                    $lookupConditions
315
                );
316
            } else {
317
                $object = $this->objectRepository->find(current($item));
318
            }
319
        }
320
321
        if (!$object) {
322
            return $this->getNewInstance();
323
        }
324
325
        return $object;
326
    }
327
328
    /**
329
     * Flush and clear the object manager
330
     */
331
    public function flush()
332
    {
333
        $this->objectManager->flush();
334
        $this->objectManager->clear($this->objectName);
335
    }
336
}
337