Completed
Pull Request — master (#1348)
by
unknown
13:12
created

ClassMetadataInfo::getReflectionProperty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ODM\MongoDB\Mapping;
21
22
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
23
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
24
use Doctrine\ODM\MongoDB\LockException;
25
use Doctrine\ODM\MongoDB\Mapping\MappingException;
26
use Doctrine\ODM\MongoDB\Proxy\Proxy;
27
use Doctrine\ODM\MongoDB\Types\Type;
28
use InvalidArgumentException;
29
30
/**
31
 * A <tt>ClassMetadata</tt> instance holds all the object-document mapping metadata
32
 * of a document and it's references.
33
 *
34
 * Once populated, ClassMetadata instances are usually cached in a serialized form.
35
 *
36
 * <b>IMPORTANT NOTE:</b>
37
 *
38
 * The fields of this class are only public for 2 reasons:
39
 * 1) To allow fast READ access.
40
 * 2) To drastically reduce the size of a serialized instance (private/protected members
41
 *    get the whole class name, namespace inclusive, prepended to every property in
42
 *    the serialized representation).
43
 *
44
 * @since       1.0
45
 */
46
class ClassMetadataInfo implements \Doctrine\Common\Persistence\Mapping\ClassMetadata
47
{
48
    /* The Id generator types. */
49
    /**
50
     * AUTO means Doctrine will automatically create a new \MongoId instance for us.
51
     */
52
    const GENERATOR_TYPE_AUTO = 1;
53
54
    /**
55
     * INCREMENT means a separate collection is used for maintaining and incrementing id generation.
56
     * Offers full portability.
57
     */
58
    const GENERATOR_TYPE_INCREMENT = 2;
59
60
    /**
61
     * UUID means Doctrine will generate a uuid for us.
62
     */
63
    const GENERATOR_TYPE_UUID = 3;
64
65
    /**
66
     * ALNUM means Doctrine will generate Alpha-numeric string identifiers, using the INCREMENT
67
     * generator to ensure identifier uniqueness
68
     */
69
    const GENERATOR_TYPE_ALNUM = 4;
70
71
    /**
72
     * CUSTOM means Doctrine expect a class parameter. It will then try to initiate that class
73
     * and pass other options to the generator. It will throw an Exception if the class
74
     * does not exist or if an option was passed for that there is not setter in the new
75
     * generator class.
76
     *
77
     * The class  will have to be a subtype of AbstractIdGenerator.
78
     */
79
    const GENERATOR_TYPE_CUSTOM = 5;
80
81
    /**
82
     * NONE means Doctrine will not generate any id for us and you are responsible for manually
83
     * assigning an id.
84
     */
85
    const GENERATOR_TYPE_NONE = 6;
86
87
    /**
88
     * Default discriminator field name.
89
     *
90
     * This is used for associations value for associations where a that do not define a "targetDocument" or
91
     * "discriminatorField" option in their mapping.
92
     */
93
    const DEFAULT_DISCRIMINATOR_FIELD = '_doctrine_class_name';
94
95
    const REFERENCE_ONE = 1;
96
    const REFERENCE_MANY = 2;
97
    const EMBED_ONE = 3;
98
    const EMBED_MANY = 4;
99
    const MANY = 'many';
100
    const ONE = 'one';
101
102
    /* The inheritance mapping types */
103
    /**
104
     * NONE means the class does not participate in an inheritance hierarchy
105
     * and therefore does not need an inheritance mapping type.
106
     */
107
    const INHERITANCE_TYPE_NONE = 1;
108
109
    /**
110
     * SINGLE_COLLECTION means the class will be persisted according to the rules of
111
     * <tt>Single Collection Inheritance</tt>.
112
     */
113
    const INHERITANCE_TYPE_SINGLE_COLLECTION = 2;
114
115
    /**
116
     * COLLECTION_PER_CLASS means the class will be persisted according to the rules
117
     * of <tt>Concrete Collection Inheritance</tt>.
118
     */
119
    const INHERITANCE_TYPE_COLLECTION_PER_CLASS = 3;
120
121
    /**
122
     * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time
123
     * by doing a property-by-property comparison with the original data. This will
124
     * be done for all entities that are in MANAGED state at commit-time.
125
     *
126
     * This is the default change tracking policy.
127
     */
128
    const CHANGETRACKING_DEFERRED_IMPLICIT = 1;
129
130
    /**
131
     * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time
132
     * by doing a property-by-property comparison with the original data. This will
133
     * be done only for entities that were explicitly saved (through persist() or a cascade).
134
     */
135
    const CHANGETRACKING_DEFERRED_EXPLICIT = 2;
136
137
    /**
138
     * NOTIFY means that Doctrine relies on the entities sending out notifications
139
     * when their properties change. Such entity classes must implement
140
     * the <tt>NotifyPropertyChanged</tt> interface.
141
     */
142
    const CHANGETRACKING_NOTIFY = 3;
143
144
    /**
145
     * READ-ONLY: The name of the mongo database the document is mapped to.
146
     */
147
    public $db;
148
149
    /**
150
     * READ-ONLY: The name of the mongo collection the document is mapped to.
151
     */
152
    public $collection;
153
154
    /**
155
     * READ-ONLY: If the collection should be a fixed size.
156
     */
157
    public $collectionCapped;
158
159
    /**
160
     * READ-ONLY: If the collection is fixed size, its size in bytes.
161
     */
162
    public $collectionSize;
163
164
    /**
165
     * READ-ONLY: If the collection is fixed size, the maximum number of elements to store in the collection.
166
     */
167
    public $collectionMax;
168
169
    /**
170
     * READ-ONLY: The field name of the document identifier.
171
     */
172
    public $identifier;
173
174
    /**
175
     * READ-ONLY: The field that stores a file reference and indicates the
176
     * document is a file and should be stored on the MongoGridFS.
177
     */
178
    public $file;
179
180
    /**
181
     * READ-ONLY: The field that stores the calculated distance when performing geo spatial
182
     * queries.
183
     */
184
    public $distance;
185
186
    /**
187
     * READ-ONLY: Whether or not reads for this class are okay to read from a slave.
188
     */
189
    public $slaveOkay;
190
191
    /**
192
     * READ-ONLY: The array of indexes for the document collection.
193
     */
194
    public $indexes = array();
195
196
    /**
197
     * READ-ONLY: Whether or not queries on this document should require indexes.
198
     */
199
    public $requireIndexes = false;
200
201
    /**
202
     * READ-ONLY: The name of the document class.
203
     */
204
    public $name;
205
206
    /**
207
     * READ-ONLY: The namespace the document class is contained in.
208
     *
209
     * @var string
210
     * @todo Not really needed. Usage could be localized.
211
     */
212
    public $namespace;
213
214
    /**
215
     * READ-ONLY: The name of the document class that is at the root of the mapped document inheritance
216
     * hierarchy. If the document is not part of a mapped inheritance hierarchy this is the same
217
     * as {@link $documentName}.
218
     *
219
     * @var string
220
     */
221
    public $rootDocumentName;
222
223
    /**
224
     * The name of the custom repository class used for the document class.
225
     * (Optional).
226
     *
227
     * @var string
228
     */
229
    public $customRepositoryClassName;
230
231
    /**
232
     * READ-ONLY: The names of the parent classes (ancestors).
233
     *
234
     * @var array
235
     */
236
    public $parentClasses = array();
237
238
    /**
239
     * READ-ONLY: The names of all subclasses (descendants).
240
     *
241
     * @var array
242
     */
243
    public $subClasses = array();
244
245
    /**
246
     * The ReflectionProperty instances of the mapped class.
247
     *
248
     * @var \ReflectionProperty[]
249
     */
250
    public $reflFields = array();
251
252
    /**
253
     * READ-ONLY: The inheritance mapping type used by the class.
254
     *
255
     * @var integer
256
     */
257
    public $inheritanceType = self::INHERITANCE_TYPE_NONE;
258
259
    /**
260
     * READ-ONLY: The Id generator type used by the class.
261
     *
262
     * @var string
263
     */
264
    public $generatorType = self::GENERATOR_TYPE_AUTO;
265
266
    /**
267
     * READ-ONLY: The Id generator options.
268
     *
269
     * @var array
270
     */
271
    public $generatorOptions = array();
272
273
    /**
274
     * READ-ONLY: The ID generator used for generating IDs for this class.
275
     *
276
     * @var \Doctrine\ODM\MongoDB\Id\AbstractIdGenerator
277
     */
278
    public $idGenerator;
279
280
    /**
281
     * READ-ONLY: The field mappings of the class.
282
     * Keys are field names and values are mapping definitions.
283
     *
284
     * The mapping definition array has the following values:
285
     *
286
     * - <b>fieldName</b> (string)
287
     * The name of the field in the Document.
288
     *
289
     * - <b>id</b> (boolean, optional)
290
     * Marks the field as the primary key of the document. Multiple fields of an
291
     * document can have the id attribute, forming a composite key.
292
     *
293
     * @var array
294
     */
295
    public $fieldMappings = array();
296
297
    /**
298
     * READ-ONLY: The association mappings of the class.
299
     * Keys are field names and values are mapping definitions.
300
     *
301
     * @var array
302
     */
303
    public $associationMappings = array();
304
305
    /**
306
     * READ-ONLY: Array of fields to also load with a given method.
307
     *
308
     * @var array
309
     */
310
    public $alsoLoadMethods = array();
311
312
    /**
313
     * READ-ONLY: The registered lifecycle callbacks for documents of this class.
314
     *
315
     * @var array
316
     */
317
    public $lifecycleCallbacks = array();
318
319
    /**
320
     * READ-ONLY: The discriminator value of this class.
321
     *
322
     * <b>This does only apply to the JOINED and SINGLE_COLLECTION inheritance mapping strategies
323
     * where a discriminator field is used.</b>
324
     *
325
     * @var mixed
326
     * @see discriminatorField
327
     */
328
    public $discriminatorValue;
329
330
    /**
331
     * READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
332
     *
333
     * <b>This does only apply to the SINGLE_COLLECTION inheritance mapping strategy
334
     * where a discriminator field is used.</b>
335
     *
336
     * @var mixed
337
     * @see discriminatorField
338
     */
339
    public $discriminatorMap = array();
340
341
    /**
342
     * READ-ONLY: The definition of the discriminator field used in SINGLE_COLLECTION
343
     * inheritance mapping.
344
     *
345
     * @var string
346
     */
347
    public $discriminatorField;
348
349
    /**
350
     * READ-ONLY: The default value for discriminatorField in case it's not set in the document
351
     *
352
     * @var string
353
     * @see discriminatorField
354
     */
355
    public $defaultDiscriminatorValue;
356
357
    /**
358
     * READ-ONLY: Whether this class describes the mapping of a mapped superclass.
359
     *
360
     * @var boolean
361
     */
362
    public $isMappedSuperclass = false;
363
364
    /**
365
     * READ-ONLY: Whether this class describes the mapping of a embedded document.
366
     *
367
     * @var boolean
368
     */
369
    public $isEmbeddedDocument = false;
370
371
    /**
372
     * READ-ONLY: The policy used for change-tracking on entities of this class.
373
     *
374
     * @var integer
375
     */
376
    public $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT;
377
378
    /**
379
     * READ-ONLY: A flag for whether or not instances of this class are to be versioned
380
     * with optimistic locking.
381
     *
382
     * @var boolean $isVersioned
383
     */
384
    public $isVersioned;
385
386
    /**
387
     * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any).
388
     *
389
     * @var mixed $versionField
390
     */
391
    public $versionField;
392
393
    /**
394
     * READ-ONLY: A flag for whether or not instances of this class are to allow pessimistic
395
     * locking.
396
     *
397
     * @var boolean $isLockable
398
     */
399
    public $isLockable;
400
401
    /**
402
     * READ-ONLY: The name of the field which is used for locking a document.
403
     *
404
     * @var mixed $lockField
405
     */
406
    public $lockField;
407
408
    /**
409
     * The ReflectionClass instance of the mapped class.
410
     *
411
     * @var \ReflectionClass
412
     */
413
    public $reflClass;
414
415
    /**
416
     * Initializes a new ClassMetadata instance that will hold the object-document mapping
417
     * metadata of the class with the given name.
418
     *
419
     * @param string $documentName The name of the document class the new instance is used for.
420
     */
421 855
    public function __construct($documentName)
422
    {
423 855
        $this->name = $documentName;
424 855
        $this->rootDocumentName = $documentName;
425 855
    }
426
427
    /**
428
     * {@inheritDoc}
429
     */
430 806
    public function getReflectionClass()
431
    {
432 806
        if ( ! $this->reflClass) {
433 2
            $this->reflClass = new \ReflectionClass($this->name);
434 2
        }
435
436 806
        return $this->reflClass;
437
    }
438
439
    /**
440
     * {@inheritDoc}
441
     */
442 292
    public function isIdentifier($fieldName)
443
    {
444 292
        return $this->identifier === $fieldName;
445
    }
446
447
    /**
448
     * INTERNAL:
449
     * Sets the mapped identifier field of this class.
450
     *
451
     * @param string $identifier
452
     */
453 330
    public function setIdentifier($identifier)
454
    {
455 330
        $this->identifier = $identifier;
456 330
    }
457
458
    /**
459
     * {@inheritDoc}
460
     *
461
     * Since MongoDB only allows exactly one identifier field
462
     * this will always return an array with only one value
463
     */
464 25
    public function getIdentifier()
465
    {
466 25
        return array($this->identifier);
467
    }
468
469
    /**
470
     * {@inheritDoc}
471
     *
472
     * Since MongoDB only allows exactly one identifier field
473
     * this will always return an array with only one value
474
     */
475 88
    public function getIdentifierFieldNames()
476
    {
477 88
        return array($this->identifier);
478
    }
479
480
    /**
481
     * {@inheritDoc}
482
     */
483 511
    public function hasField($fieldName)
484
    {
485 511
        return isset($this->fieldMappings[$fieldName]);
486
    }
487
488
    /**
489
     * Sets the inheritance type used by the class and it's subclasses.
490
     *
491
     * @param integer $type
492
     */
493 341
    public function setInheritanceType($type)
494
    {
495 341
        $this->inheritanceType = $type;
496 341
    }
497
498
    /**
499
     * Checks whether a mapped field is inherited from an entity superclass.
500
     *
501
     * @param  string $fieldName
502
     *
503
     * @return boolean TRUE if the field is inherited, FALSE otherwise.
504
     */
505 806
    public function isInheritedField($fieldName)
506
    {
507 806
        return isset($this->fieldMappings[$fieldName]['inherited']);
508
    }
509
510
    /**
511
     * Registers a custom repository class for the document class.
512
     *
513
     * @param string $repositoryClassName The class name of the custom repository.
514
     */
515 285 View Code Duplication
    public function setCustomRepositoryClass($repositoryClassName)
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...
516
    {
517 285
        if ($this->isEmbeddedDocument) {
518
            return;
519
        }
520
        
521 285
        if ($repositoryClassName && strpos($repositoryClassName, '\\') === false && strlen($this->namespace)) {
522 3
            $repositoryClassName = $this->namespace . '\\' . $repositoryClassName;
523 3
        }
524
525 285
        $this->customRepositoryClassName = $repositoryClassName;
526 285
    }
527
528
    /**
529
     * Dispatches the lifecycle event of the given document by invoking all
530
     * registered callbacks.
531
     *
532
     * @param string $event     Lifecycle event
533
     * @param object $document  Document on which the event occurred
534
     * @param array  $arguments Arguments to pass to all callbacks
535
     * @throws \InvalidArgumentException if document class is not this class or
536
     *                                   a Proxy of this class
537
     */
538 588
    public function invokeLifecycleCallbacks($event, $document, array $arguments = null)
539
    {
540 588
        if ( ! $document instanceof $this->name) {
541 1
            throw new \InvalidArgumentException(sprintf('Expected document class "%s"; found: "%s"', $this->name, get_class($document)));
542
        }
543
544 587
        if (empty($this->lifecycleCallbacks[$event])) {
545 574
            return;
546
        }
547
548 176
        foreach ($this->lifecycleCallbacks[$event] as $callback) {
549 176
            if ($arguments !== null) {
550 175
                call_user_func_array(array($document, $callback), $arguments);
551 175
            } else {
552 2
                $document->$callback();
553
            }
554 176
        }
555 176
    }
556
557
    /**
558
     * Checks whether the class has callbacks registered for a lifecycle event.
559
     *
560
     * @param string $event Lifecycle event
561
     *
562
     * @return boolean
563
     */
564
    public function hasLifecycleCallbacks($event)
565
    {
566
        return ! empty($this->lifecycleCallbacks[$event]);
567
    }
568
569
    /**
570
     * Gets the registered lifecycle callbacks for an event.
571
     *
572
     * @param string $event
573
     * @return array
574
     */
575
    public function getLifecycleCallbacks($event)
576
    {
577
        return isset($this->lifecycleCallbacks[$event]) ? $this->lifecycleCallbacks[$event] : array();
578
    }
579
580
    /**
581
     * Adds a lifecycle callback for documents of this class.
582
     *
583
     * If the callback is already registered, this is a NOOP.
584
     *
585
     * @param string $callback
586
     * @param string $event
587
     */
588 266
    public function addLifecycleCallback($callback, $event)
589
    {
590 266
        if (isset($this->lifecycleCallbacks[$event]) && in_array($callback, $this->lifecycleCallbacks[$event])) {
591 1
            return;
592
        }
593
594 266
        $this->lifecycleCallbacks[$event][] = $callback;
595 266
    }
596
597
    /**
598
     * Sets the lifecycle callbacks for documents of this class.
599
     *
600
     * Any previously registered callbacks are overwritten.
601
     *
602
     * @param array $callbacks
603
     */
604 329
    public function setLifecycleCallbacks(array $callbacks)
605
    {
606 329
        $this->lifecycleCallbacks = $callbacks;
607 329
    }
608
609
    /**
610
     * Registers a method for loading document data before field hydration.
611
     *
612
     * Note: A method may be registered multiple times for different fields.
613
     * it will be invoked only once for the first field found.
614
     *
615
     * @param string       $method Method name
616
     * @param array|string $fields Database field name(s)
617
     */
618 15
    public function registerAlsoLoadMethod($method, $fields)
619
    {
620 15
        $this->alsoLoadMethods[$method] = is_array($fields) ? $fields : array($fields);
621 15
    }
622
623
    /**
624
     * Sets the AlsoLoad methods for documents of this class.
625
     *
626
     * Any previously registered methods are overwritten.
627
     *
628
     * @param array $methods
629
     */
630 329
    public function setAlsoLoadMethods(array $methods)
631
    {
632 329
        $this->alsoLoadMethods = $methods;
633 329
    }
634
635
    /**
636
     * Sets the discriminator field.
637
     *
638
     * The field name is the the unmapped database field. Discriminator values
639
     * are only used to discern the hydration class and are not mapped to class
640
     * properties.
641
     *
642
     * @param string $discriminatorField
643
     *
644
     * @throws MappingException If the discriminator field conflicts with the
645
     *                          "name" attribute of a mapped field.
646
     */
647 350
    public function setDiscriminatorField($discriminatorField)
648
    {
649 350
        if ($discriminatorField === null) {
650 290
            $this->discriminatorField = null;
651
652 290
            return;
653
        }
654
655
        // Handle array argument with name/fieldName keys for BC
656 115
        if (is_array($discriminatorField)) {
657
            if (isset($discriminatorField['name'])) {
658
                $discriminatorField = $discriminatorField['name'];
659
            } elseif (isset($discriminatorField['fieldName'])) {
660
                $discriminatorField = $discriminatorField['fieldName'];
661
            }
662
        }
663
664 115
        foreach ($this->fieldMappings as $fieldMapping) {
665 4
            if ($discriminatorField == $fieldMapping['name']) {
666 1
                throw MappingException::discriminatorFieldConflict($this->name, $discriminatorField);
667
            }
668 114
        }
669
670 114
        $this->discriminatorField = $discriminatorField;
671 114
    }
672
673
    /**
674
     * Sets the discriminator values used by this class.
675
     * Used for JOINED and SINGLE_TABLE inheritance mapping strategies.
676
     *
677
     * @param array $map
678
     *
679
     * @throws MappingException
680
     */
681 346
    public function setDiscriminatorMap(array $map)
682
    {
683 346
        foreach ($map as $value => $className) {
684 113
            if (strpos($className, '\\') === false && strlen($this->namespace)) {
685 81
                $className = $this->namespace . '\\' . $className;
686 81
            }
687 113
            $this->discriminatorMap[$value] = $className;
688 113
            if ($this->name == $className) {
689 105
                $this->discriminatorValue = $value;
690 105
            } else {
691 105
                if ( ! class_exists($className)) {
692
                    throw MappingException::invalidClassInDiscriminatorMap($className, $this->name);
693
                }
694 105
                if (is_subclass_of($className, $this->name)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if $this->name can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
695 91
                    $this->subClasses[] = $className;
696 91
                }
697
            }
698 346
        }
699 346
    }
700
701
    /**
702
     * Sets the default discriminator value to be used for this class
703
     * Used for JOINED and SINGLE_TABLE inheritance mapping strategies if the document has no discriminator value
704
     *
705
     * @param string $defaultDiscriminatorValue
706
     *
707
     * @throws MappingException
708
     */
709 335
    public function setDefaultDiscriminatorValue($defaultDiscriminatorValue)
710
    {
711 335
        if ($defaultDiscriminatorValue === null) {
712 329
            $this->defaultDiscriminatorValue = null;
713
714 329
            return;
715
        }
716
717 53
        if (!array_key_exists($defaultDiscriminatorValue, $this->discriminatorMap)) {
718
            throw MappingException::invalidDiscriminatorValue($defaultDiscriminatorValue, $this->name);
719
        }
720
721 53
        $this->defaultDiscriminatorValue = $defaultDiscriminatorValue;
722 53
    }
723
724
    /**
725
     * Sets the discriminator value for this class.
726
     * Used for JOINED/SINGLE_TABLE inheritance and multiple document types in a single
727
     * collection.
728
     *
729
     * @param string $value
730
     */
731
    public function setDiscriminatorValue($value)
732
    {
733
        $this->discriminatorMap[$value] = $this->name;
734
        $this->discriminatorValue = $value;
735
    }
736
737
    /**
738
     * Sets the slaveOkay option applied to collections for this class.
739
     *
740
     * @param boolean|null $slaveOkay
741
     */
742 3
    public function setSlaveOkay($slaveOkay)
743
    {
744 3
        $this->slaveOkay = $slaveOkay === null ? null : (boolean) $slaveOkay;
745 3
    }
746
747
    /**
748
     * Add a index for this Document.
749
     *
750
     * @param array $keys Array of keys for the index.
751
     * @param array $options Array of options for the index.
752
     */
753 218
    public function addIndex($keys, array $options = array())
754
    {
755 218
        $this->indexes[] = array(
756
            'keys' => array_map(function($value) {
757 218
                if ($value == 1 || $value == -1) {
758 55
                    return (int) $value;
759
                }
760 210
                if (is_string($value)) {
761 210
                    $lower = strtolower($value);
762 210
                    if ($lower === 'asc') {
763 203
                        return 1;
764 10
                    } elseif ($lower === 'desc') {
765 3
                        return -1;
766
                    }
767 7
                }
768 7
                return $value;
769 218
            }, $keys),
770
            'options' => $options
771 218
        );
772 218
    }
773
774
    /**
775
     * Set whether or not queries on this document should require indexes.
776
     *
777
     * @param bool $requireIndexes
778
     */
779 798
    public function setRequireIndexes($requireIndexes)
780
    {
781 798
        $this->requireIndexes = $requireIndexes;
782 798
    }
783
784
    /**
785
     * Returns the array of indexes for this Document.
786
     *
787
     * @return array $indexes The array of indexes.
788
     */
789 53
    public function getIndexes()
790
    {
791 53
        return $this->indexes;
792
    }
793
794
    /**
795
     * Checks whether this document has indexes or not.
796
     *
797
     * @return boolean
798
     */
799
    public function hasIndexes()
800
    {
801
        return $this->indexes ? true : false;
802
    }
803
804
    /**
805
     * Sets the change tracking policy used by this class.
806
     *
807
     * @param integer $policy
808
     */
809 333
    public function setChangeTrackingPolicy($policy)
810
    {
811 333
        $this->changeTrackingPolicy = $policy;
812 333
    }
813
814
    /**
815
     * Whether the change tracking policy of this class is "deferred explicit".
816
     *
817
     * @return boolean
818
     */
819 56
    public function isChangeTrackingDeferredExplicit()
820
    {
821 56
        return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_EXPLICIT;
822
    }
823
824
    /**
825
     * Whether the change tracking policy of this class is "deferred implicit".
826
     *
827
     * @return boolean
828
     */
829 563
    public function isChangeTrackingDeferredImplicit()
830
    {
831 563
        return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_IMPLICIT;
832
    }
833
834
    /**
835
     * Whether the change tracking policy of this class is "notify".
836
     *
837
     * @return boolean
838
     */
839 328
    public function isChangeTrackingNotify()
840
    {
841 328
        return $this->changeTrackingPolicy == self::CHANGETRACKING_NOTIFY;
842
    }
843
844
    /**
845
     * Gets the ReflectionProperties of the mapped class.
846
     *
847
     * @return array An array of ReflectionProperty instances.
848
     */
849 88
    public function getReflectionProperties()
850
    {
851 88
        return $this->reflFields;
852
    }
853
854
    /**
855
     * Gets a ReflectionProperty for a specific field of the mapped class.
856
     *
857
     * @param string $name
858
     *
859
     * @return \ReflectionProperty
860
     */
861 4
    public function getReflectionProperty($name)
862
    {
863 4
        return $this->reflFields[$name];
864
    }
865
866
    /**
867
     * {@inheritDoc}
868
     */
869 803
    public function getName()
870
    {
871 803
        return $this->name;
872
    }
873
874
    /**
875
     * The namespace this Document class belongs to.
876
     *
877
     * @return string $namespace The namespace name.
878
     */
879
    public function getNamespace()
880
    {
881
        return $this->namespace;
882
    }
883
884
    /**
885
     * Returns the database this Document is mapped to.
886
     *
887
     * @return string $db The database name.
888
     */
889 741
    public function getDatabase()
890
    {
891 741
        return $this->db;
892
    }
893
894
    /**
895
     * Set the database this Document is mapped to.
896
     *
897
     * @param string $db The database name
898
     */
899 93
    public function setDatabase($db)
900
    {
901 93
        $this->db = $db;
902 93
    }
903
904
    /**
905
     * Get the collection this Document is mapped to.
906
     *
907
     * @return string $collection The collection name.
908
     */
909 745
    public function getCollection()
910
    {
911 745
        return $this->collection;
912
    }
913
914
    /**
915
     * Sets the collection this Document is mapped to.
916
     *
917
     * @param array|string $name
918
     *
919
     * @throws \InvalidArgumentException
920
     */
921 836
    public function setCollection($name)
922
    {
923 836
        if (is_array($name)) {
924
            if ( ! isset($name['name'])) {
925
                throw new \InvalidArgumentException('A name key is required when passing an array to setCollection()');
926
            }
927
            $this->collectionCapped = isset($name['capped']) ? $name['capped'] : false;
928
            $this->collectionSize = isset($name['size']) ? $name['size'] : 0;
929
            $this->collectionMax = isset($name['max']) ? $name['max'] : 0;
930
            $this->collection = $name['name'];
931
        } else {
932 836
            $this->collection = $name;
933
        }
934 836
    }
935
936
    /**
937
     * Get whether or not the documents collection is capped.
938
     *
939
     * @return boolean
940
     */
941 4
    public function getCollectionCapped()
942
    {
943 4
        return $this->collectionCapped;
944
    }
945
946
    /**
947
     * Set whether or not the documents collection is capped.
948
     *
949
     * @param boolean $bool
950
     */
951 1
    public function setCollectionCapped($bool)
952
    {
953 1
        $this->collectionCapped = $bool;
954 1
    }
955
956
    /**
957
     * Get the collection size
958
     *
959
     * @return integer
960
     */
961 4
    public function getCollectionSize()
962
    {
963 4
        return $this->collectionSize;
964
    }
965
966
    /**
967
     * Set the collection size.
968
     *
969
     * @param integer $size
970
     */
971 1
    public function setCollectionSize($size)
972
    {
973 1
        $this->collectionSize = $size;
974 1
    }
975
976
    /**
977
     * Get the collection max.
978
     *
979
     * @return integer
980
     */
981 4
    public function getCollectionMax()
982
    {
983 4
        return $this->collectionMax;
984
    }
985
986
    /**
987
     * Set the collection max.
988
     *
989
     * @param integer $max
990
     */
991 1
    public function setCollectionMax($max)
992
    {
993 1
        $this->collectionMax = $max;
994 1
    }
995
996
    /**
997
     * Returns TRUE if this Document is mapped to a collection FALSE otherwise.
998
     *
999
     * @return boolean
1000
     */
1001
    public function isMappedToCollection()
1002
    {
1003
        return $this->collection ? true : false;
1004
    }
1005
1006
    /**
1007
     * Returns TRUE if this Document is a file to be stored on the MongoGridFS FALSE otherwise.
1008
     *
1009
     * @return boolean
1010
     */
1011 694
    public function isFile()
1012
    {
1013 694
        return $this->file ? true : false;
1014
    }
1015
1016
    /**
1017
     * Returns the file field name.
1018
     *
1019
     * @return string $file The file field name.
1020
     */
1021 329
    public function getFile()
1022
    {
1023 329
        return $this->file;
1024
    }
1025
1026
    /**
1027
     * Set the field name that stores the grid file.
1028
     *
1029
     * @param string $file
1030
     */
1031 330
    public function setFile($file)
1032
    {
1033 330
        $this->file = $file;
1034 330
    }
1035
1036
    /**
1037
     * Returns the distance field name.
1038
     *
1039
     * @return string $distance The distance field name.
1040
     */
1041
    public function getDistance()
1042
    {
1043
        return $this->distance;
1044
    }
1045
1046
    /**
1047
     * Set the field name that stores the distance.
1048
     *
1049
     * @param string $distance
1050
     */
1051 1
    public function setDistance($distance)
1052
    {
1053 1
        $this->distance = $distance;
1054 1
    }
1055
1056
    /**
1057
     * Map a field.
1058
     *
1059
     * @param array $mapping The mapping information.
1060
     *
1061
     * @return array
1062
     *
1063
     * @throws MappingException
1064
     */
1065 841
    public function mapField(array $mapping)
1066
    {
1067 841
        if ( ! isset($mapping['fieldName']) && isset($mapping['name'])) {
1068 8
            $mapping['fieldName'] = $mapping['name'];
1069 8
        }
1070 841
        if ( ! isset($mapping['fieldName'])) {
1071
            throw MappingException::missingFieldName($this->name);
1072
        }
1073 841
        if ( ! isset($mapping['name'])) {
1074 833
            $mapping['name'] = $mapping['fieldName'];
1075 833
        }
1076 841
        if ($this->identifier === $mapping['name'] && empty($mapping['id'])) {
1077 1
            throw MappingException::mustNotChangeIdentifierFieldsType($this->name, $mapping['name']);
1078
        }
1079 840
        if (isset($this->fieldMappings[$mapping['fieldName']])) {
1080
            //throw MappingException::duplicateFieldMapping($this->name, $mapping['fieldName']);
1081 53
        }
1082 840
        if ($this->discriminatorField !== null && $this->discriminatorField == $mapping['name']) {
1083 1
            throw MappingException::discriminatorFieldConflict($this->name, $this->discriminatorField);
1084
        }
1085 839
        if (isset($mapping['targetDocument']) && strpos($mapping['targetDocument'], '\\') === false && strlen($this->namespace)) {
1086 532
            $mapping['targetDocument'] = $this->namespace . '\\' . $mapping['targetDocument'];
1087 532
        }
1088
1089 839
        if (isset($mapping['discriminatorMap'])) {
1090 103
            foreach ($mapping['discriminatorMap'] as $key => $class) {
1091 103
                if (strpos($class, '\\') === false && strlen($this->namespace)) {
1092 68
                    $mapping['discriminatorMap'][$key] = $this->namespace . '\\' . $class;
1093 68
                }
1094 103
            }
1095 103
        }
1096
1097 839
        if (isset($mapping['cascade']) && isset($mapping['embedded'])) {
1098 1
            throw MappingException::cascadeOnEmbeddedNotAllowed($this->name, $mapping['fieldName']);
1099
        }
1100
1101 838
        $cascades = isset($mapping['cascade']) ? array_map('strtolower', (array) $mapping['cascade']) : array();
1102
1103 838
        if (in_array('all', $cascades) || isset($mapping['embedded'])) {
1104 561
            $cascades = array('remove', 'persist', 'refresh', 'merge', 'detach');
1105 561
        }
1106
1107 838
        if (isset($mapping['embedded'])) {
1108 527
            unset($mapping['cascade']);
1109 838
        } elseif (isset($mapping['cascade'])) {
1110 364
            $mapping['cascade'] = $cascades;
1111 364
        }
1112
1113 838
        $mapping['isCascadeRemove'] = in_array('remove', $cascades);
1114 838
        $mapping['isCascadePersist'] = in_array('persist', $cascades);
1115 838
        $mapping['isCascadeRefresh'] = in_array('refresh', $cascades);
1116 838
        $mapping['isCascadeMerge'] = in_array('merge', $cascades);
1117 838
        $mapping['isCascadeDetach'] = in_array('detach', $cascades);
1118
        
1119 838
        if (isset($mapping['type']) && $mapping['type'] === 'file') {
1120 56
            $mapping['file'] = true;
1121 56
        }
1122 838 View Code Duplication
        if (isset($mapping['file']) && $mapping['file'] === true) {
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...
1123 56
            $this->file = $mapping['fieldName'];
1124 56
            $mapping['name'] = 'file';
1125 56
        }
1126 838 View Code Duplication
        if (isset($mapping['distance']) && $mapping['distance'] === true) {
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...
1127 7
            $this->distance = $mapping['fieldName'];
1128 7
        }
1129 838
        if (isset($mapping['id']) && $mapping['id'] === true) {
1130 819
            $mapping['name'] = '_id';
1131 819
            $this->identifier = $mapping['fieldName'];
1132 819 View Code Duplication
            if (isset($mapping['strategy'])) {
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...
1133 804
                $this->generatorType = constant(ClassMetadata::class . '::GENERATOR_TYPE_' . strtoupper($mapping['strategy']));
1134 804
            }
1135 819
            $this->generatorOptions = isset($mapping['options']) ? $mapping['options'] : array();
1136 819
            switch ($this->generatorType) {
1137 819
                case self::GENERATOR_TYPE_AUTO:
1138 748
                    $mapping['type'] = 'id';
1139 748
                    break;
1140 153
                default:
1141 153
                    if ( ! empty($this->generatorOptions['type'])) {
1142 52
                        $mapping['type'] = $this->generatorOptions['type'];
1143 153
                    } elseif (empty($mapping['type'])) {
1144 74
                        $mapping['type'] = $this->generatorType === self::GENERATOR_TYPE_INCREMENT ? 'int_id' : 'custom_id';
1145 74
                    }
1146 819
            }
1147 819
            unset($this->generatorOptions['type']);
1148 819
        }
1149 838
        if ( ! isset($mapping['nullable'])) {
1150 39
            $mapping['nullable'] = false;
1151 39
        }
1152
1153 838
        if (isset($mapping['reference']) && ! empty($mapping['simple']) && ! isset($mapping['targetDocument'])) {
1154 1
            throw MappingException::simpleReferenceRequiresTargetDocument($this->name, $mapping['fieldName']);
1155
        }
1156
1157 837
        if (isset($mapping['reference']) && empty($mapping['targetDocument']) && empty($mapping['discriminatorMap']) &&
1158 837
                (isset($mapping['mappedBy']) || isset($mapping['inversedBy']))) {
1159 4
            throw MappingException::owningAndInverseReferencesRequireTargetDocument($this->name, $mapping['fieldName']);
1160
        }
1161
        
1162 833
        if ($this->isEmbeddedDocument && $mapping['type'] === 'many' && CollectionHelper::isAtomic($mapping['strategy'])) {
1163 1
            throw MappingException::atomicCollectionStrategyNotAllowed($mapping['strategy'], $this->name, $mapping['fieldName']);
1164
        }
1165
1166 832 View Code Duplication
        if (isset($mapping['reference']) && $mapping['type'] === 'one') {
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...
1167 453
            $mapping['association'] = self::REFERENCE_ONE;
1168 453
        }
1169 832 View Code Duplication
        if (isset($mapping['reference']) && $mapping['type'] === 'many') {
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...
1170 395
            $mapping['association'] = self::REFERENCE_MANY;
1171 395
        }
1172 832 View Code Duplication
        if (isset($mapping['embedded']) && $mapping['type'] === 'one') {
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...
1173 404
            $mapping['association'] = self::EMBED_ONE;
1174 404
        }
1175 832 View Code Duplication
        if (isset($mapping['embedded']) && $mapping['type'] === 'many') {
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...
1176 458
            $mapping['association'] = self::EMBED_MANY;
1177 458
        }
1178
1179 832
        if (isset($mapping['association']) && ! isset($mapping['targetDocument']) && ! isset($mapping['discriminatorField'])) {
1180 105
            $mapping['discriminatorField'] = self::DEFAULT_DISCRIMINATOR_FIELD;
1181 105
        }
1182
1183
        /*
1184
        if (isset($mapping['type']) && ($mapping['type'] === 'one' || $mapping['type'] === 'many')) {
1185
            $mapping['type'] = $mapping['type'] === 'one' ? self::ONE : self::MANY;
1186
        }
1187
        */
1188 832
        if (isset($mapping['version'])) {
1189 93
            $mapping['notSaved'] = true;
1190 93
            $this->setVersionMapping($mapping);
1191 92
        }
1192 832
        if (isset($mapping['lock'])) {
1193 26
            $mapping['notSaved'] = true;
1194 26
            $this->setLockMapping($mapping);
1195 25
        }
1196 832
        $mapping['isOwningSide'] = true;
1197 832
        $mapping['isInverseSide'] = false;
1198 832
        if (isset($mapping['reference'])) {
1199 509 View Code Duplication
            if (isset($mapping['inversedBy']) && $mapping['inversedBy']) {
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...
1200 213
                $mapping['isOwningSide'] = true;
1201 213
                $mapping['isInverseSide'] = false;
1202 213
            }
1203 509 View Code Duplication
            if (isset($mapping['mappedBy']) && $mapping['mappedBy']) {
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...
1204 252
                $mapping['isInverseSide'] = true;
1205 252
                $mapping['isOwningSide'] = false;
1206 252
            }
1207 509 View Code Duplication
            if (isset($mapping['repositoryMethod'])) {
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...
1208 193
                $mapping['isInverseSide'] = true;
1209 193
                $mapping['isOwningSide'] = false;
1210 193
            }
1211 509
            if (!isset($mapping['orphanRemoval'])) {
1212 489
                $mapping['orphanRemoval'] = false;
1213 489
            }
1214 509
        }
1215
1216 832
        if (isset($mapping['reference']) && $mapping['type'] === 'many' && $mapping['isOwningSide']
1217 832
            && ! empty($mapping['sort']) && ! CollectionHelper::usesSet($mapping['strategy'])) {
1218 1
            throw MappingException::referenceManySortMustNotBeUsedWithNonSetCollectionStrategy($this->name, $mapping['fieldName'], $mapping['strategy']);
1219
        }
1220
1221 831
        $this->fieldMappings[$mapping['fieldName']] = $mapping;
1222 831
        if (isset($mapping['association'])) {
1223 651
            $this->associationMappings[$mapping['fieldName']] = $mapping;
1224 651
        }
1225
1226 831
        return $mapping;
1227
    }
1228
1229
    /**
1230
     * Map a MongoGridFSFile.
1231
     *
1232
     * @param array $mapping The mapping information.
1233
     */
1234
    public function mapFile(array $mapping)
1235
    {
1236
        $mapping['file'] = true;
1237
        $mapping['type'] = 'file';
1238
        $this->mapField($mapping);
1239
    }
1240
1241
    /**
1242
     * Map a single embedded document.
1243
     *
1244
     * @param array $mapping The mapping information.
1245
     */
1246 6
    public function mapOneEmbedded(array $mapping)
1247
    {
1248 6
        $mapping['embedded'] = true;
1249 6
        $mapping['type'] = 'one';
1250 6
        $this->mapField($mapping);
1251 5
    }
1252
1253
    /**
1254
     * Map a collection of embedded documents.
1255
     *
1256
     * @param array $mapping The mapping information.
1257
     */
1258 3
    public function mapManyEmbedded(array $mapping)
1259
    {
1260 3
        $mapping['embedded'] = true;
1261 3
        $mapping['type'] = 'many';
1262 3
        $this->mapField($mapping);
1263 3
    }
1264
1265
    /**
1266
     * Map a single document reference.
1267
     *
1268
     * @param array $mapping The mapping information.
1269
     */
1270 8
    public function mapOneReference(array $mapping)
1271
    {
1272 8
        $mapping['reference'] = true;
1273 8
        $mapping['type'] = 'one';
1274 8
        $this->mapField($mapping);
1275 8
    }
1276
1277
    /**
1278
     * Map a collection of document references.
1279
     *
1280
     * @param array $mapping The mapping information.
1281
     */
1282 8
    public function mapManyReference(array $mapping)
1283
    {
1284 8
        $mapping['reference'] = true;
1285 8
        $mapping['type'] = 'many';
1286 8
        $this->mapField($mapping);
1287 8
    }
1288
1289
    /**
1290
     * INTERNAL:
1291
     * Adds a field mapping without completing/validating it.
1292
     * This is mainly used to add inherited field mappings to derived classes.
1293
     *
1294
     * @param array $fieldMapping
1295
     */
1296 115
    public function addInheritedFieldMapping(array $fieldMapping)
1297
    {
1298 115
        $this->fieldMappings[$fieldMapping['fieldName']] = $fieldMapping;
1299
1300 115
        if (isset($fieldMapping['association'])) {
1301 76
            $this->associationMappings[$fieldMapping['fieldName']] = $fieldMapping;
1302 76
        }
1303 115
    }
1304
1305
    /**
1306
     * INTERNAL:
1307
     * Adds an association mapping without completing/validating it.
1308
     * This is mainly used to add inherited association mappings to derived classes.
1309
     *
1310
     * @param array $mapping
1311
     *
1312
     * @return void
1313
     *
1314
     * @throws MappingException
1315
     */
1316 77
    public function addInheritedAssociationMapping(array $mapping/*, $owningClassName = null*/)
1317
    {
1318 77
        $this->associationMappings[$mapping['fieldName']] = $mapping;
1319 77
    }
1320
1321
    /**
1322
     * Checks whether the class has a mapped association with the given field name.
1323
     *
1324
     * @param string $fieldName
1325
     * @return boolean
1326
     */
1327 7
    public function hasReference($fieldName)
1328
    {
1329 7
        return isset($this->fieldMappings[$fieldName]['reference']);
1330
    }
1331
1332
    /**
1333
     * Checks whether the class has a mapped embed with the given field name.
1334
     *
1335
     * @param string $fieldName
1336
     * @return boolean
1337
     */
1338 5
    public function hasEmbed($fieldName)
1339
    {
1340 5
        return isset($this->fieldMappings[$fieldName]['embedded']);
1341
    }
1342
1343
    /**
1344
     * {@inheritDoc}
1345
     *
1346
     * Checks whether the class has a mapped association (embed or reference) with the given field name.
1347
     */
1348 7
    public function hasAssociation($fieldName)
1349
    {
1350 7
        return $this->hasReference($fieldName) || $this->hasEmbed($fieldName);
1351
    }
1352
1353
    /**
1354
     * {@inheritDoc}
1355
     *
1356
     * Checks whether the class has a mapped reference or embed for the specified field and
1357
     * is a single valued association.
1358
     */
1359
    public function isSingleValuedAssociation($fieldName)
1360
    {
1361
        return $this->isSingleValuedReference($fieldName) || $this->isSingleValuedEmbed($fieldName);
1362
    }
1363
1364
    /**
1365
     * {@inheritDoc}
1366
     *
1367
     * Checks whether the class has a mapped reference or embed for the specified field and
1368
     * is a collection valued association.
1369
     */
1370
    public function isCollectionValuedAssociation($fieldName)
1371
    {
1372
        return $this->isCollectionValuedReference($fieldName) || $this->isCollectionValuedEmbed($fieldName);
1373
    }
1374
1375
    /**
1376
     * Checks whether the class has a mapped association for the specified field
1377
     * and if yes, checks whether it is a single-valued association (to-one).
1378
     *
1379
     * @param string $fieldName
1380
     * @return boolean TRUE if the association exists and is single-valued, FALSE otherwise.
1381
     */
1382
    public function isSingleValuedReference($fieldName)
1383
    {
1384
        return isset($this->fieldMappings[$fieldName]['association']) &&
1385
            $this->fieldMappings[$fieldName]['association'] === self::REFERENCE_ONE;
1386
    }
1387
1388
    /**
1389
     * Checks whether the class has a mapped association for the specified field
1390
     * and if yes, checks whether it is a collection-valued association (to-many).
1391
     *
1392
     * @param string $fieldName
1393
     * @return boolean TRUE if the association exists and is collection-valued, FALSE otherwise.
1394
     */
1395
    public function isCollectionValuedReference($fieldName)
1396
    {
1397
        return isset($this->fieldMappings[$fieldName]['association']) &&
1398
            $this->fieldMappings[$fieldName]['association'] === self::REFERENCE_MANY;
1399
    }
1400
1401
    /**
1402
     * Checks whether the class has a mapped embedded document for the specified field
1403
     * and if yes, checks whether it is a single-valued association (to-one).
1404
     *
1405
     * @param string $fieldName
1406
     * @return boolean TRUE if the association exists and is single-valued, FALSE otherwise.
1407
     */
1408
    public function isSingleValuedEmbed($fieldName)
1409
    {
1410
        return isset($this->fieldMappings[$fieldName]['association']) &&
1411
            $this->fieldMappings[$fieldName]['association'] === self::EMBED_ONE;
1412
    }
1413
1414
    /**
1415
     * Checks whether the class has a mapped embedded document for the specified field
1416
     * and if yes, checks whether it is a collection-valued association (to-many).
1417
     *
1418
     * @param string $fieldName
1419
     * @return boolean TRUE if the association exists and is collection-valued, FALSE otherwise.
1420
     */
1421
    public function isCollectionValuedEmbed($fieldName)
1422
    {
1423
        return isset($this->fieldMappings[$fieldName]['association']) &&
1424
            $this->fieldMappings[$fieldName]['association'] === self::EMBED_MANY;
1425
    }
1426
1427
    /**
1428
     * Sets the ID generator used to generate IDs for instances of this class.
1429
     *
1430
     * @param \Doctrine\ODM\MongoDB\Id\AbstractIdGenerator $generator
1431
     */
1432 746
    public function setIdGenerator($generator)
1433
    {
1434 746
        $this->idGenerator = $generator;
1435 746
    }
1436
1437
    /**
1438
     * Casts the identifier to its portable PHP type.
1439
     *
1440
     * @param mixed $id
1441
     * @return mixed $id
1442
     */
1443 580
    public function getPHPIdentifierValue($id)
1444
    {
1445 580
        $idType = $this->fieldMappings[$this->identifier]['type'];
1446 580
        return Type::getType($idType)->convertToPHPValue($id);
1447
    }
1448
1449
    /**
1450
     * Casts the identifier to its database type.
1451
     *
1452
     * @param mixed $id
1453
     * @return mixed $id
1454
     */
1455 642
    public function getDatabaseIdentifierValue($id)
1456
    {
1457 642
        $idType = $this->fieldMappings[$this->identifier]['type'];
1458 642
        return Type::getType($idType)->convertToDatabaseValue($id);
1459
    }
1460
1461
    /**
1462
     * Sets the document identifier of a document.
1463
     *
1464
     * The value will be converted to a PHP type before being set.
1465
     *
1466
     * @param object $document
1467
     * @param mixed $id
1468
     */
1469 512
    public function setIdentifierValue($document, $id)
1470
    {
1471 512
        $id = $this->getPHPIdentifierValue($id);
1472 512
        $this->reflFields[$this->identifier]->setValue($document, $id);
1473 512
    }
1474
1475
    /**
1476
     * Gets the document identifier as a PHP type.
1477
     *
1478
     * @param object $document
1479
     * @return mixed $id
1480
     */
1481 593
    public function getIdentifierValue($document)
1482
    {
1483 593
        return $this->reflFields[$this->identifier]->getValue($document);
1484
    }
1485
1486
    /**
1487
     * {@inheritDoc}
1488
     *
1489
     * Since MongoDB only allows exactly one identifier field this is a proxy
1490
     * to {@see getIdentifierValue()} and returns an array with the identifier
1491
     * field as a key.
1492
     */
1493
    public function getIdentifierValues($object)
1494
    {
1495
        return array($this->identifier => $this->getIdentifierValue($object));
1496
    }
1497
1498
    /**
1499
     * Get the document identifier object as a database type.
1500
     *
1501
     * @param object $document
1502
     *
1503
     * @return \MongoId $id The MongoID object.
1504
     */
1505 32
    public function getIdentifierObject($document)
1506
    {
1507 32
        return $this->getDatabaseIdentifierValue($this->getIdentifierValue($document));
1508
    }
1509
1510
    /**
1511
     * Sets the specified field to the specified value on the given document.
1512
     *
1513
     * @param object $document
1514
     * @param string $field
1515
     * @param mixed $value
1516
     */
1517 7
    public function setFieldValue($document, $field, $value)
1518
    {
1519 7
        if ($document instanceof Proxy && ! $document->__isInitialized()) {
1520
            //property changes to an uninitialized proxy will not be tracked or persisted,
1521
            //so the proxy needs to be loaded first.
1522 1
            $document->__load();
1523 1
        }
1524
        
1525 7
        $this->reflFields[$field]->setValue($document, $value);
1526 7
    }
1527
1528
    /**
1529
     * Gets the specified field's value off the given document.
1530
     *
1531
     * @param object $document
1532
     * @param string $field
1533
     *
1534
     * @return mixed
1535
     */
1536 25
    public function getFieldValue($document, $field)
1537
    {
1538 25
        if ($document instanceof Proxy && $field !== $this->identifier && ! $document->__isInitialized()) {
1539 1
            $document->__load();
1540 1
        }
1541
        
1542 25
        return $this->reflFields[$field]->getValue($document);
1543
    }
1544
1545
    /**
1546
     * Gets the mapping of a field.
1547
     *
1548
     * @param string $fieldName  The field name.
1549
     *
1550
     * @return array  The field mapping.
1551
     *
1552
     * @throws MappingException if the $fieldName is not found in the fieldMappings array
1553
     *
1554
     * @throws MappingException
1555
     */
1556 90
    public function getFieldMapping($fieldName)
1557
    {
1558 90
        if ( ! isset($this->fieldMappings[$fieldName])) {
1559 6
            throw MappingException::mappingNotFound($this->name, $fieldName);
1560
        }
1561 88
        return $this->fieldMappings[$fieldName];
1562
    }
1563
1564
    /**
1565
     * Gets mappings of fields holding embedded document(s).
1566
     *
1567
     * @return array of field mappings
1568
     */
1569 555
    public function getEmbeddedFieldsMappings()
1570
    {
1571 555
        return array_filter(
1572 555
            $this->associationMappings,
1573
            function($assoc) { return ! empty($assoc['embedded']); }
1574 555
        );
1575
    }
1576
1577
    /**
1578
     * Check if the field is not null.
1579
     *
1580
     * @param string $fieldName  The field name
1581
     *
1582
     * @return boolean  TRUE if the field is not null, FALSE otherwise.
1583
     */
1584 1
    public function isNullable($fieldName)
1585
    {
1586 1
        $mapping = $this->getFieldMapping($fieldName);
1587 1
        if ($mapping !== false) {
1588 1
            return isset($mapping['nullable']) && $mapping['nullable'] == true;
1589
        }
1590
        return false;
1591
    }
1592
1593
    /**
1594
     * Checks whether the document has a discriminator field and value configured.
1595
     *
1596
     * @return boolean
1597
     */
1598 474
    public function hasDiscriminator()
1599
    {
1600 474
        return isset($this->discriminatorField, $this->discriminatorValue);
1601
    }
1602
1603
    /**
1604
     * Sets the type of Id generator to use for the mapped class.
1605
     */
1606 335
    public function setIdGeneratorType($generatorType)
1607
    {
1608 335
        $this->generatorType = $generatorType;
1609 335
    }
1610
1611
    /**
1612
     * Sets the Id generator options.
1613
     */
1614
    public function setIdGeneratorOptions($generatorOptions)
1615
    {
1616
        $this->generatorOptions = $generatorOptions;
1617
    }
1618
1619
    /**
1620
     * @return boolean
1621
     */
1622 561
    public function isInheritanceTypeNone()
1623
    {
1624 561
        return $this->inheritanceType == self::INHERITANCE_TYPE_NONE;
1625
    }
1626
1627
    /**
1628
     * Checks whether the mapped class uses the SINGLE_COLLECTION inheritance mapping strategy.
1629
     *
1630
     * @return boolean
1631
     */
1632 329
    public function isInheritanceTypeSingleCollection()
1633
    {
1634 329
        return $this->inheritanceType == self::INHERITANCE_TYPE_SINGLE_COLLECTION;
1635
    }
1636
1637
    /**
1638
     * Checks whether the mapped class uses the COLLECTION_PER_CLASS inheritance mapping strategy.
1639
     *
1640
     * @return boolean
1641
     */
1642
    public function isInheritanceTypeCollectionPerClass()
1643
    {
1644
        return $this->inheritanceType == self::INHERITANCE_TYPE_COLLECTION_PER_CLASS;
1645
    }
1646
1647
    /**
1648
     * Sets the mapped subclasses of this class.
1649
     *
1650
     * @param string[] $subclasses The names of all mapped subclasses.
1651
     */
1652 2 View Code Duplication
    public function setSubclasses(array $subclasses)
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...
1653
    {
1654 2
        foreach ($subclasses as $subclass) {
1655 2
            if (strpos($subclass, '\\') === false && strlen($this->namespace)) {
1656 1
                $this->subClasses[] = $this->namespace . '\\' . $subclass;
1657 1
            } else {
1658 1
                $this->subClasses[] = $subclass;
1659
            }
1660 2
        }
1661 2
    }
1662
1663
    /**
1664
     * Sets the parent class names.
1665
     * Assumes that the class names in the passed array are in the order:
1666
     * directParent -> directParentParent -> directParentParentParent ... -> root.
1667
     *
1668
     * @param string[] $classNames
1669
     */
1670 801
    public function setParentClasses(array $classNames)
1671
    {
1672 801
        $this->parentClasses = $classNames;
1673
1674 801
        if (count($classNames) > 0) {
1675 101
            $this->rootDocumentName = array_pop($classNames);
1676 101
        }
1677 801
    }
1678
1679
    /**
1680
     * Checks whether the class will generate a new \MongoId instance for us.
1681
     *
1682
     * @return boolean TRUE if the class uses the AUTO generator, FALSE otherwise.
1683
     */
1684
    public function isIdGeneratorAuto()
1685
    {
1686
        return $this->generatorType == self::GENERATOR_TYPE_AUTO;
1687
    }
1688
1689
    /**
1690
     * Checks whether the class will use a collection to generate incremented identifiers.
1691
     *
1692
     * @return boolean TRUE if the class uses the INCREMENT generator, FALSE otherwise.
1693
     */
1694
    public function isIdGeneratorIncrement()
1695
    {
1696
        return $this->generatorType == self::GENERATOR_TYPE_INCREMENT;
1697
    }
1698
1699
    /**
1700
     * Checks whether the class will generate a uuid id.
1701
     *
1702
     * @return boolean TRUE if the class uses the UUID generator, FALSE otherwise.
1703
     */
1704
    public function isIdGeneratorUuid()
1705
    {
1706
        return $this->generatorType == self::GENERATOR_TYPE_UUID;
1707
    }
1708
1709
    /**
1710
     * Checks whether the class uses no id generator.
1711
     *
1712
     * @return boolean TRUE if the class does not use any id generator, FALSE otherwise.
1713
     */
1714
    public function isIdGeneratorNone()
1715
    {
1716
        return $this->generatorType == self::GENERATOR_TYPE_NONE;
1717
    }
1718
1719
    /**
1720
     * Sets the version field mapping used for versioning. Sets the default
1721
     * value to use depending on the column type.
1722
     *
1723
     * @param array $mapping   The version field mapping array
1724
     * 
1725
     * @throws LockException
1726
     */
1727 93
    public function setVersionMapping(array &$mapping)
1728
    {
1729 93
        if ($mapping['type'] !== 'int' && $mapping['type'] !== 'date') {
1730 1
            throw LockException::invalidVersionFieldType($mapping['type']);
1731
        }
1732
1733 92
        $this->isVersioned  = true;
1734 92
        $this->versionField = $mapping['fieldName'];
1735 92
    }
1736
1737
    /**
1738
     * Sets whether this class is to be versioned for optimistic locking.
1739
     *
1740
     * @param boolean $bool
1741
     */
1742 329
    public function setVersioned($bool)
1743
    {
1744 329
        $this->isVersioned = $bool;
1745 329
    }
1746
1747
    /**
1748
     * Sets the name of the field that is to be used for versioning if this class is
1749
     * versioned for optimistic locking.
1750
     *
1751
     * @param string $versionField
1752
     */
1753 329
    public function setVersionField($versionField)
1754
    {
1755 329
        $this->versionField = $versionField;
1756 329
    }
1757
1758
    /**
1759
     * Sets the version field mapping used for versioning. Sets the default
1760
     * value to use depending on the column type.
1761
     *
1762
     * @param array $mapping   The version field mapping array
1763
     *
1764
     * @throws \Doctrine\ODM\MongoDB\LockException
1765
     */
1766 26
    public function setLockMapping(array &$mapping)
1767
    {
1768 26
        if ($mapping['type'] !== 'int') {
1769 1
            throw LockException::invalidLockFieldType($mapping['type']);
1770
        }
1771
1772 25
        $this->isLockable = true;
1773 25
        $this->lockField = $mapping['fieldName'];
1774 25
    }
1775
1776
    /**
1777
     * Sets whether this class is to allow pessimistic locking.
1778
     *
1779
     * @param boolean $bool
1780
     */
1781
    public function setLockable($bool)
1782
    {
1783
        $this->isLockable = $bool;
1784
    }
1785
1786
    /**
1787
     * Sets the name of the field that is to be used for storing whether a document
1788
     * is currently locked or not.
1789
     *
1790
     * @param string $lockField
1791
     */
1792
    public function setLockField($lockField)
1793
    {
1794
        $this->lockField = $lockField;
1795
    }
1796
1797
    /**
1798
     * {@inheritDoc}
1799
     */
1800
    public function getFieldNames()
1801
    {
1802
        return array_keys($this->fieldMappings);
1803
    }
1804
1805
    /**
1806
     * {@inheritDoc}
1807
     */
1808
    public function getAssociationNames()
1809
    {
1810
        return array_keys($this->associationMappings);
1811
    }
1812
1813
    /**
1814
     * {@inheritDoc}
1815
     */
1816 21
    public function getTypeOfField($fieldName)
1817
    {
1818 21
        return isset($this->fieldMappings[$fieldName]) ?
1819 21
            $this->fieldMappings[$fieldName]['type'] : null;
1820
    }
1821
1822
    /**
1823
     * {@inheritDoc}
1824
     */
1825 6
    public function getAssociationTargetClass($assocName)
1826
    {
1827 6
        if ( ! isset($this->associationMappings[$assocName])) {
1828 3
            throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association.");
1829
        }
1830
1831 3
        return $this->associationMappings[$assocName]['targetDocument'];
1832
    }
1833
1834
    /**
1835
     * {@inheritDoc}
1836
     */
1837
    public function isAssociationInverseSide($fieldName)
1838
    {
1839
        throw new \BadMethodCallException(__METHOD__ . '() is not implemented yet.');
1840
    }
1841
1842
    /**
1843
     * {@inheritDoc}
1844
     */
1845
    public function getAssociationMappedByTargetField($fieldName)
1846
    {
1847
        throw new \BadMethodCallException(__METHOD__ . '() is not implemented yet.');
1848
    }
1849
}
1850