Completed
Pull Request — master (#1803)
by Maciej
18:23 queued 15:20
created

HydratorFactory::setUnitOfWork()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ODM\MongoDB\Hydrator;
6
7
use Doctrine\Common\EventManager;
8
use Doctrine\ODM\MongoDB\Configuration;
9
use Doctrine\ODM\MongoDB\DocumentManager;
10
use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
11
use Doctrine\ODM\MongoDB\Event\PreLoadEventArgs;
12
use Doctrine\ODM\MongoDB\Events;
13
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
14
use Doctrine\ODM\MongoDB\Proxy\Proxy;
15
use Doctrine\ODM\MongoDB\Types\Type;
16
use Doctrine\ODM\MongoDB\UnitOfWork;
17
use const DIRECTORY_SEPARATOR;
18
use function array_key_exists;
19
use function chmod;
20
use function class_exists;
21
use function dirname;
22
use function file_exists;
23
use function file_put_contents;
24
use function get_class;
25
use function is_dir;
26
use function is_writable;
27
use function mkdir;
28
use function rename;
29
use function rtrim;
30
use function sprintf;
31
use function str_replace;
32
use function substr;
33
use function uniqid;
34
35
/**
36
 * The HydratorFactory class is responsible for instantiating a correct hydrator
37
 * type based on document's ClassMetadata
38
 *
39
 */
40
class HydratorFactory
41
{
42
    /**
43
     * The DocumentManager this factory is bound to.
44
     *
45
     * @var DocumentManager
46
     */
47
    private $dm;
48
49
    /**
50
     * The UnitOfWork used to coordinate object-level transactions.
51
     *
52
     * @var UnitOfWork
53
     */
54
    private $unitOfWork;
55
56
    /**
57
     * The EventManager associated with this Hydrator
58
     *
59
     * @var EventManager
60
     */
61
    private $evm;
62
63
    /**
64
     * Which algorithm to use to automatically (re)generate hydrator classes.
65
     *
66
     * @var int
67
     */
68
    private $autoGenerate;
69
70
    /**
71
     * The namespace that contains all hydrator classes.
72
     *
73
     * @var string
74
     */
75
    private $hydratorNamespace;
76
77
    /**
78
     * The directory that contains all hydrator classes.
79
     *
80
     * @var string
81
     */
82
    private $hydratorDir;
83
84
    /**
85
     * Array of instantiated document hydrators.
86
     *
87
     * @var array
88
     */
89
    private $hydrators = [];
90
91
    /**
92
     * @param string $hydratorDir
93
     * @param string $hydratorNs
94
     * @param int    $autoGenerate
95
     * @throws HydratorException
96
     */
97 1584
    public function __construct(DocumentManager $dm, EventManager $evm, $hydratorDir, $hydratorNs, $autoGenerate)
98
    {
99 1584
        if (! $hydratorDir) {
100
            throw HydratorException::hydratorDirectoryRequired();
101
        }
102 1584
        if (! $hydratorNs) {
103
            throw HydratorException::hydratorNamespaceRequired();
104
        }
105 1584
        $this->dm = $dm;
106 1584
        $this->evm = $evm;
107 1584
        $this->hydratorDir = $hydratorDir;
108 1584
        $this->hydratorNamespace = $hydratorNs;
109 1584
        $this->autoGenerate = $autoGenerate;
110 1584
    }
111
112
    /**
113
     * Sets the UnitOfWork instance.
114
     *
115
     */
116 1584
    public function setUnitOfWork(UnitOfWork $uow)
117
    {
118 1584
        $this->unitOfWork = $uow;
119 1584
    }
120
121
    /**
122
     * Gets the hydrator object for the given document class.
123
     *
124
     * @param string $className
125
     * @return HydratorInterface $hydrator
126
     */
127 367
    public function getHydratorFor($className)
128
    {
129 367
        if (isset($this->hydrators[$className])) {
130 196
            return $this->hydrators[$className];
131
        }
132 367
        $hydratorClassName = str_replace('\\', '', $className) . 'Hydrator';
133 367
        $fqn = $this->hydratorNamespace . '\\' . $hydratorClassName;
134 367
        $class = $this->dm->getClassMetadata($className);
135
136 367
        if (! class_exists($fqn, false)) {
137 175
            $fileName = $this->hydratorDir . DIRECTORY_SEPARATOR . $hydratorClassName . '.php';
138 175
            switch ($this->autoGenerate) {
139
                case Configuration::AUTOGENERATE_NEVER:
140
                    require $fileName;
141
                    break;
142
143
                case Configuration::AUTOGENERATE_ALWAYS:
144 175
                    $this->generateHydratorClass($class, $hydratorClassName, $fileName);
145 175
                    require $fileName;
146 175
                    break;
147
148
                case Configuration::AUTOGENERATE_FILE_NOT_EXISTS:
149
                    if (! file_exists($fileName)) {
150
                        $this->generateHydratorClass($class, $hydratorClassName, $fileName);
151
                    }
152
                    require $fileName;
153
                    break;
154
155
                case Configuration::AUTOGENERATE_EVAL:
156
                    $this->generateHydratorClass($class, $hydratorClassName, null);
157
                    break;
158
            }
159
        }
160 367
        $this->hydrators[$className] = new $fqn($this->dm, $this->unitOfWork, $class);
161 367
        return $this->hydrators[$className];
162
    }
163
164
    /**
165
     * Generates hydrator classes for all given classes.
166
     *
167
     * @param array  $classes The classes (ClassMetadata instances) for which to generate hydrators.
168
     * @param string $toDir   The target directory of the hydrator classes. If not specified, the
169
     *                        directory configured on the Configuration of the DocumentManager used
170
     *                        by this factory is used.
171
     */
172
    public function generateHydratorClasses(array $classes, $toDir = null)
173
    {
174
        $hydratorDir = $toDir ?: $this->hydratorDir;
175
        $hydratorDir = rtrim($hydratorDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
176
        foreach ($classes as $class) {
177
            $hydratorClassName = str_replace('\\', '', $class->name) . 'Hydrator';
178
            $hydratorFileName = $hydratorDir . $hydratorClassName . '.php';
179
            $this->generateHydratorClass($class, $hydratorClassName, $hydratorFileName);
180
        }
181
    }
182
183 175
    private function generateHydratorClass(ClassMetadata $class, string $hydratorClassName, ?string $fileName)
184
    {
185 175
        $code = '';
186
187 175
        foreach ($class->fieldMappings as $fieldName => $mapping) {
188 175
            if (isset($mapping['alsoLoadFields'])) {
189 5
                foreach ($mapping['alsoLoadFields'] as $name) {
190 5
                    $code .= sprintf(
191
                        <<<EOF
192
193 5
        /** @AlsoLoad("$name") */
194 5
        if (!array_key_exists('%1\$s', \$data) && array_key_exists('$name', \$data)) {
195 5
            \$data['%1\$s'] = \$data['$name'];
196
        }
197
198
EOF
199
                        ,
200 5
                        $mapping['name']
201
                    );
202
                }
203
            }
204
205 175
            if ($mapping['type'] === 'date') {
206 8
                $code .= sprintf(
207
                    <<<EOF
208
209
        /** @Field(type="date") */
210
        if (isset(\$data['%1\$s'])) {
211
            \$value = \$data['%1\$s'];
212
            %3\$s
213
            \$this->class->reflFields['%2\$s']->setValue(\$document, clone \$return);
214
            \$hydratedData['%2\$s'] = \$return;
215
        }
216
217
EOF
218
                    ,
219 8
                    $mapping['name'],
220 8
                    $mapping['fieldName'],
221 8
                    Type::getType($mapping['type'])->closureToPHP()
222
                );
223 175
            } elseif (! isset($mapping['association'])) {
224 175
                $code .= sprintf(
225
                    <<<EOF
226
227 175
        /** @Field(type="{$mapping['type']}") */
228
        if (isset(\$data['%1\$s']) || (! empty(\$this->class->fieldMappings['%2\$s']['nullable']) && array_key_exists('%1\$s', \$data))) {
229
            \$value = \$data['%1\$s'];
230
            if (\$value !== null) {
231
                \$typeIdentifier = \$this->class->fieldMappings['%2\$s']['type'];
232
                %3\$s
233
            } else {
234
                \$return = null;
235
            }
236
            \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
237
            \$hydratedData['%2\$s'] = \$return;
238
        }
239
240
EOF
241
                    ,
242 175
                    $mapping['name'],
243 175
                    $mapping['fieldName'],
244 175
                    Type::getType($mapping['type'])->closureToPHP()
245
                );
246 113
            } elseif ($mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isOwningSide']) {
247 49
                $code .= sprintf(
248
                    <<<EOF
249
250
        /** @ReferenceOne */
251
        if (isset(\$data['%1\$s'])) {
252
            \$reference = \$data['%1\$s'];
253
            \$className = \$this->unitOfWork->getClassNameForAssociation(\$this->class->fieldMappings['%2\$s'], \$reference);
254
            \$identifier = ClassMetadata::getReferenceId(\$reference, \$this->class->fieldMappings['%2\$s']['storeAs']);
255
            \$targetMetadata = \$this->dm->getClassMetadata(\$className);
256
            \$id = \$targetMetadata->getPHPIdentifierValue(\$identifier);
257
            \$return = \$this->dm->getReference(\$className, \$id);
258
            \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
259
            \$hydratedData['%2\$s'] = \$return;
260
        }
261
262
EOF
263
                    ,
264 49
                    $mapping['name'],
265 49
                    $mapping['fieldName']
266
                );
267 95
            } elseif ($mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isInverseSide']) {
268 5
                if (isset($mapping['repositoryMethod']) && $mapping['repositoryMethod']) {
269 1
                    $code .= sprintf(
270
                        <<<EOF
271
272
        \$className = \$this->class->fieldMappings['%2\$s']['targetDocument'];
273
        \$return = \$this->dm->getRepository(\$className)->%3\$s(\$document);
274
        \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
275
        \$hydratedData['%2\$s'] = \$return;
276
277
EOF
278
                        ,
279 1
                        $mapping['name'],
280 1
                        $mapping['fieldName'],
281 1
                        $mapping['repositoryMethod']
282
                    );
283
                } else {
284 5
                    $code .= sprintf(
285
                        <<<EOF
286
287
        \$mapping = \$this->class->fieldMappings['%2\$s'];
288
        \$className = \$mapping['targetDocument'];
289
        \$targetClass = \$this->dm->getClassMetadata(\$mapping['targetDocument']);
290
        \$mappedByMapping = \$targetClass->fieldMappings[\$mapping['mappedBy']];
291
        \$mappedByFieldName = ClassMetadata::getReferenceFieldName(\$mappedByMapping['storeAs'], \$mapping['mappedBy']);
292
        \$criteria = array_merge(
293
            array(\$mappedByFieldName => \$data['_id']),
294
            isset(\$this->class->fieldMappings['%2\$s']['criteria']) ? \$this->class->fieldMappings['%2\$s']['criteria'] : array()
295
        );
296
        \$sort = isset(\$this->class->fieldMappings['%2\$s']['sort']) ? \$this->class->fieldMappings['%2\$s']['sort'] : array();
297
        \$return = \$this->unitOfWork->getDocumentPersister(\$className)->load(\$criteria, null, array(), 0, \$sort);
298
        \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
299
        \$hydratedData['%2\$s'] = \$return;
300
301
EOF
302
                        ,
303 5
                        $mapping['name'],
304 5
                        $mapping['fieldName']
305
                    );
306
                }
307 94
            } elseif ($mapping['association'] === ClassMetadata::REFERENCE_MANY || $mapping['association'] === ClassMetadata::EMBED_MANY) {
308 74
                $code .= sprintf(
309
                    <<<EOF
310
311
        /** @Many */
312
        \$mongoData = isset(\$data['%1\$s']) ? \$data['%1\$s'] : null;
313
        \$return = \$this->dm->getConfiguration()->getPersistentCollectionFactory()->create(\$this->dm, \$this->class->fieldMappings['%2\$s']);
314
        \$return->setHints(\$hints);
315
        \$return->setOwner(\$document, \$this->class->fieldMappings['%2\$s']);
316
        \$return->setInitialized(false);
317
        if (\$mongoData) {
318
            \$return->setMongoData(\$mongoData);
319
        }
320
        \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
321
        \$hydratedData['%2\$s'] = \$return;
322
323
EOF
324
                    ,
325 74
                    $mapping['name'],
326 74
                    $mapping['fieldName']
327
                );
328 42
            } elseif ($mapping['association'] === ClassMetadata::EMBED_ONE) {
329 42
                $code .= sprintf(
330
                    <<<EOF
331
332
        /** @EmbedOne */
333
        if (isset(\$data['%1\$s'])) {
334
            \$embeddedDocument = \$data['%1\$s'];
335
            \$className = \$this->unitOfWork->getClassNameForAssociation(\$this->class->fieldMappings['%2\$s'], \$embeddedDocument);
336
            \$embeddedMetadata = \$this->dm->getClassMetadata(\$className);
337
            \$return = \$embeddedMetadata->newInstance();
338
339
            \$this->unitOfWork->setParentAssociation(\$return, \$this->class->fieldMappings['%2\$s'], \$document, '%1\$s');
340
341
            \$embeddedData = \$this->dm->getHydratorFactory()->hydrate(\$return, \$embeddedDocument, \$hints);
342
            \$embeddedId = \$embeddedMetadata->identifier && isset(\$embeddedData[\$embeddedMetadata->identifier]) ? \$embeddedData[\$embeddedMetadata->identifier] : null;
343
344
            if (empty(\$hints[Query::HINT_READ_ONLY])) {
345
                \$this->unitOfWork->registerManaged(\$return, \$embeddedId, \$embeddedData);
346
            }
347
348
            \$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
349
            \$hydratedData['%2\$s'] = \$return;
350
        }
351
352
EOF
353
                    ,
354 42
                    $mapping['name'],
355 175
                    $mapping['fieldName']
356
                );
357
            }
358
        }
359
360 175
        $namespace = $this->hydratorNamespace;
361 175
        $code = sprintf(
362
            <<<EOF
363
<?php
364
365 175
namespace $namespace;
366
367
use Doctrine\ODM\MongoDB\DocumentManager;
368
use Doctrine\ODM\MongoDB\Hydrator\HydratorInterface;
369
use Doctrine\ODM\MongoDB\Query\Query;
370
use Doctrine\ODM\MongoDB\UnitOfWork;
371
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
372
373
/**
374
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ODM. DO NOT EDIT THIS FILE.
375
 */
376 175
class $hydratorClassName implements HydratorInterface
377
{
378
    private \$dm;
379
    private \$unitOfWork;
380
    private \$class;
381
382
    public function __construct(DocumentManager \$dm, UnitOfWork \$uow, ClassMetadata \$class)
383
    {
384
        \$this->dm = \$dm;
385
        \$this->unitOfWork = \$uow;
386
        \$this->class = \$class;
387
    }
388
389
    public function hydrate(\$document, \$data, array \$hints = array())
390
    {
391
        \$hydratedData = array();
392
%s        return \$hydratedData;
393
    }
394
}
395
EOF
396
            ,
397 175
            $code
398
        );
399
400 175
        if ($fileName === null) {
401
            if (! class_exists($namespace . '\\' . $hydratorClassName)) {
402
                eval(substr($code, 5));
403
            }
404
405
            return;
406
        }
407
408 175
        $parentDirectory = dirname($fileName);
409
410 175
        if (! is_dir($parentDirectory) && (@mkdir($parentDirectory, 0775, true) === false)) {
411
            throw HydratorException::hydratorDirectoryNotWritable();
412
        }
413
414 175
        if (! is_writable($parentDirectory)) {
415
            throw HydratorException::hydratorDirectoryNotWritable();
416
        }
417
418 175
        $tmpFileName = $fileName . '.' . uniqid('', true);
419 175
        file_put_contents($tmpFileName, $code);
420 175
        rename($tmpFileName, $fileName);
421 175
        chmod($fileName, 0664);
422 175
    }
423
424
    /**
425
     * Hydrate array of MongoDB document data into the given document object.
426
     *
427
     * @param object $document The document object to hydrate the data into.
428
     * @param array  $data     The array of document data.
429
     * @param array  $hints    Any hints to account for during reconstitution/lookup of the document.
430
     * @return array $values The array of hydrated values.
431
     */
432 367
    public function hydrate($document, $data, array $hints = [])
433
    {
434 367
        $metadata = $this->dm->getClassMetadata(get_class($document));
435
        // Invoke preLoad lifecycle events and listeners
436 367
        if (! empty($metadata->lifecycleCallbacks[Events::preLoad])) {
437 14
            $args = [new PreLoadEventArgs($document, $this->dm, $data)];
438 14
            $metadata->invokeLifecycleCallbacks(Events::preLoad, $document, $args);
439
        }
440 367
        if ($this->evm->hasListeners(Events::preLoad)) {
441 3
            $this->evm->dispatchEvent(Events::preLoad, new PreLoadEventArgs($document, $this->dm, $data));
442
        }
443
444
        // alsoLoadMethods may transform the document before hydration
445 367
        if (! empty($metadata->alsoLoadMethods)) {
446 12
            foreach ($metadata->alsoLoadMethods as $method => $fieldNames) {
447 12
                foreach ($fieldNames as $fieldName) {
448
                    // Invoke the method only once for the first field we find
449 12
                    if (array_key_exists($fieldName, $data)) {
450 8
                        $document->$method($data[$fieldName]);
451 12
                        continue 2;
452
                    }
453
                }
454
            }
455
        }
456
457 367
        if ($document instanceof Proxy) {
458 72
            $document->__isInitialized__ = true;
0 ignored issues
show
Bug introduced by
Accessing __isInitialized__ on the interface Doctrine\ODM\MongoDB\Proxy\Proxy 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...
459 72
            $document->__setInitializer(null);
460 72
            $document->__setCloner(null);
461
        }
462
463 367
        $data = $this->getHydratorFor($metadata->name)->hydrate($document, $data, $hints);
464
465 367
        if ($document instanceof Proxy) {
466
            // lazy properties may be left uninitialized
467 72
            $properties = $document->__getLazyProperties();
468 72
            foreach ($properties as $propertyName => $property) {
469 30
                if (isset($document->$propertyName)) {
470 25
                    continue;
471
                }
472
473 9
                $document->$propertyName = $properties[$propertyName];
474
            }
475
        }
476
477
        // Invoke the postLoad lifecycle callbacks and listeners
478 367
        if (! empty($metadata->lifecycleCallbacks[Events::postLoad])) {
479 13
            $metadata->invokeLifecycleCallbacks(Events::postLoad, $document, [new LifecycleEventArgs($document, $this->dm)]);
480
        }
481 367
        if ($this->evm->hasListeners(Events::postLoad)) {
482 4
            $this->evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($document, $this->dm));
483
        }
484
485 367
        return $data;
486
    }
487
}
488