Completed
Pull Request — master (#1527)
by Andreas
10:32
created

ClassMetadataInfo::setIdGenerator()   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
 * 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\Utility\CollectionHelper;
23
use Doctrine\ODM\MongoDB\LockException;
24
use Doctrine\ODM\MongoDB\Proxy\Proxy;
25
use Doctrine\ODM\MongoDB\Types\Type;
26
use InvalidArgumentException;
27
28
/**
29
 * A <tt>ClassMetadata</tt> instance holds all the object-document mapping metadata
30
 * of a document and it's references.
31
 *
32
 * Once populated, ClassMetadata instances are usually cached in a serialized form.
33
 *
34
 * <b>IMPORTANT NOTE:</b>
35
 *
36
 * The fields of this class are only public for 2 reasons:
37
 * 1) To allow fast READ access.
38
 * 2) To drastically reduce the size of a serialized instance (private/protected members
39
 *    get the whole class name, namespace inclusive, prepended to every property in
40
 *    the serialized representation).
41
 *
42
 * @since       1.0
43
 */
44
class ClassMetadataInfo implements \Doctrine\Common\Persistence\Mapping\ClassMetadata
45
{
46
    /* The Id generator types. */
47
    /**
48
     * AUTO means Doctrine will automatically create a new \MongoId instance for us.
49
     */
50
    const GENERATOR_TYPE_AUTO = 1;
51
52
    /**
53
     * INCREMENT means a separate collection is used for maintaining and incrementing id generation.
54
     * Offers full portability.
55
     */
56
    const GENERATOR_TYPE_INCREMENT = 2;
57
58
    /**
59
     * UUID means Doctrine will generate a uuid for us.
60
     */
61
    const GENERATOR_TYPE_UUID = 3;
62
63
    /**
64
     * ALNUM means Doctrine will generate Alpha-numeric string identifiers, using the INCREMENT
65
     * generator to ensure identifier uniqueness
66
     */
67
    const GENERATOR_TYPE_ALNUM = 4;
68
69
    /**
70
     * CUSTOM means Doctrine expect a class parameter. It will then try to initiate that class
71
     * and pass other options to the generator. It will throw an Exception if the class
72
     * does not exist or if an option was passed for that there is not setter in the new
73
     * generator class.
74
     *
75
     * The class  will have to be a subtype of AbstractIdGenerator.
76
     */
77
    const GENERATOR_TYPE_CUSTOM = 5;
78
79
    /**
80
     * NONE means Doctrine will not generate any id for us and you are responsible for manually
81
     * assigning an id.
82
     */
83
    const GENERATOR_TYPE_NONE = 6;
84
85
    /**
86
     * Default discriminator field name.
87
     *
88
     * This is used for associations value for associations where a that do not define a "targetDocument" or
89
     * "discriminatorField" option in their mapping.
90
     */
91
    const DEFAULT_DISCRIMINATOR_FIELD = '_doctrine_class_name';
92
93
    const REFERENCE_ONE = 1;
94
    const REFERENCE_MANY = 2;
95
    const EMBED_ONE = 3;
96
    const EMBED_MANY = 4;
97
    const MANY = 'many';
98
    const ONE = 'one';
99
100
    /**
101
     * The types of storeAs references
102
     */
103
    const REFERENCE_STORE_AS_ID = 'id';
104
    const REFERENCE_STORE_AS_DB_REF = 'dbRef';
105
    const REFERENCE_STORE_AS_DB_REF_WITH_DB = 'dbRefWithDb';
106
107
    /* The inheritance mapping types */
108
    /**
109
     * NONE means the class does not participate in an inheritance hierarchy
110
     * and therefore does not need an inheritance mapping type.
111
     */
112
    const INHERITANCE_TYPE_NONE = 1;
113
114
    /**
115
     * SINGLE_COLLECTION means the class will be persisted according to the rules of
116
     * <tt>Single Collection Inheritance</tt>.
117
     */
118
    const INHERITANCE_TYPE_SINGLE_COLLECTION = 2;
119
120
    /**
121
     * COLLECTION_PER_CLASS means the class will be persisted according to the rules
122
     * of <tt>Concrete Collection Inheritance</tt>.
123
     */
124
    const INHERITANCE_TYPE_COLLECTION_PER_CLASS = 3;
125
126
    /**
127
     * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time
128
     * by doing a property-by-property comparison with the original data. This will
129
     * be done for all entities that are in MANAGED state at commit-time.
130
     *
131
     * This is the default change tracking policy.
132
     */
133
    const CHANGETRACKING_DEFERRED_IMPLICIT = 1;
134
135
    /**
136
     * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time
137
     * by doing a property-by-property comparison with the original data. This will
138
     * be done only for entities that were explicitly saved (through persist() or a cascade).
139
     */
140
    const CHANGETRACKING_DEFERRED_EXPLICIT = 2;
141
142
    /**
143
     * NOTIFY means that Doctrine relies on the entities sending out notifications
144
     * when their properties change. Such entity classes must implement
145
     * the <tt>NotifyPropertyChanged</tt> interface.
146
     */
147
    const CHANGETRACKING_NOTIFY = 3;
148
149
    /**
150
     * SET means that fields will be written to the database using a $set operator
151
     */
152
    const STORAGE_STRATEGY_SET = 'set';
153
154
    /**
155
     * INCREMENT means that fields will be written to the database by calculating
156
     * the difference and using the $inc operator
157
     */
158
    const STORAGE_STRATEGY_INCREMENT = 'increment';
159
160
    const STORAGE_STRATEGY_PUSH_ALL = 'pushAll';
161
    const STORAGE_STRATEGY_ADD_TO_SET = 'addToSet';
162
    const STORAGE_STRATEGY_ATOMIC_SET = 'atomicSet';
163
    const STORAGE_STRATEGY_ATOMIC_SET_ARRAY = 'atomicSetArray';
164
    const STORAGE_STRATEGY_SET_ARRAY = 'setArray';
165
166
    /**
167
     * READ-ONLY: The name of the mongo database the document is mapped to.
168
     */
169
    public $db;
170
171
    /**
172
     * READ-ONLY: The name of the mongo collection the document is mapped to.
173
     */
174
    public $collection;
175
176
    /**
177
     * READ-ONLY: If the collection should be a fixed size.
178
     */
179
    public $collectionCapped;
180
181
    /**
182
     * READ-ONLY: If the collection is fixed size, its size in bytes.
183
     */
184
    public $collectionSize;
185
186
    /**
187
     * READ-ONLY: If the collection is fixed size, the maximum number of elements to store in the collection.
188
     */
189
    public $collectionMax;
190
191
    /**
192
     * READ-ONLY: Describes the level of acknowledgement requested from MongoDB for write operations.
193
     */
194
    public $writeConcern;
195
196
    /**
197
     * READ-ONLY: The field name of the document identifier.
198
     */
199
    public $identifier;
200
201
    /**
202
     * READ-ONLY: The field that stores a file reference and indicates the
203
     * document is a file and should be stored on the MongoGridFS.
204
     */
205
    public $file;
206
207
    /**
208
     * READ-ONLY: The field that stores the calculated distance when performing geo spatial
209
     * queries.
210
     */
211
    public $distance;
212
213
    /**
214
     * READ-ONLY: Whether or not reads for this class are okay to read from a slave.
215
     */
216
    public $slaveOkay;
217
218
    /**
219
     * READ-ONLY: The array of indexes for the document collection.
220
     */
221
    public $indexes = array();
222
223
    /**
224
     * READ-ONLY: Keys and options describing shard key. Only for sharded collections.
225
     */
226
    public $shardKey;
227
228
    /**
229
     * READ-ONLY: Whether or not queries on this document should require indexes.
230
     *
231
     * @deprecated property was deprecated in 1.2 and will be removed in 2.0
232
     */
233
    public $requireIndexes = false;
234
235
    /**
236
     * READ-ONLY: The name of the document class.
237
     */
238
    public $name;
239
240
    /**
241
     * READ-ONLY: The namespace the document class is contained in.
242
     *
243
     * @var string
244
     * @todo Not really needed. Usage could be localized.
245
     */
246
    public $namespace;
247
248
    /**
249
     * READ-ONLY: The name of the document class that is at the root of the mapped document inheritance
250
     * hierarchy. If the document is not part of a mapped inheritance hierarchy this is the same
251
     * as {@link $documentName}.
252
     *
253
     * @var string
254
     */
255
    public $rootDocumentName;
256
257
    /**
258
     * The name of the custom repository class used for the document class.
259
     * (Optional).
260
     *
261
     * @var string
262
     */
263
    public $customRepositoryClassName;
264
265
    /**
266
     * READ-ONLY: The names of the parent classes (ancestors).
267
     *
268
     * @var array
269
     */
270
    public $parentClasses = array();
271
272
    /**
273
     * READ-ONLY: The names of all subclasses (descendants).
274
     *
275
     * @var array
276
     */
277
    public $subClasses = array();
278
279
    /**
280
     * The ReflectionProperty instances of the mapped class.
281
     *
282
     * @var \ReflectionProperty[]
283
     */
284
    public $reflFields = array();
285
286
    /**
287
     * READ-ONLY: The inheritance mapping type used by the class.
288
     *
289
     * @var integer
290
     */
291
    public $inheritanceType = self::INHERITANCE_TYPE_NONE;
292
293
    /**
294
     * READ-ONLY: The Id generator type used by the class.
295
     *
296
     * @var string
297
     */
298
    public $generatorType = self::GENERATOR_TYPE_AUTO;
299
300
    /**
301
     * READ-ONLY: The Id generator options.
302
     *
303
     * @var array
304
     */
305
    public $generatorOptions = array();
306
307
    /**
308
     * READ-ONLY: The ID generator used for generating IDs for this class.
309
     *
310
     * @var \Doctrine\ODM\MongoDB\Id\AbstractIdGenerator
311
     */
312
    public $idGenerator;
313
314
    /**
315
     * READ-ONLY: The field mappings of the class.
316
     * Keys are field names and values are mapping definitions.
317
     *
318
     * The mapping definition array has the following values:
319
     *
320
     * - <b>fieldName</b> (string)
321
     * The name of the field in the Document.
322
     *
323
     * - <b>id</b> (boolean, optional)
324
     * Marks the field as the primary key of the document. Multiple fields of an
325
     * document can have the id attribute, forming a composite key.
326
     *
327
     * @var array
328
     */
329
    public $fieldMappings = array();
330
331
    /**
332
     * READ-ONLY: The association mappings of the class.
333
     * Keys are field names and values are mapping definitions.
334
     *
335
     * @var array
336
     */
337
    public $associationMappings = array();
338
339
    /**
340
     * READ-ONLY: Array of fields to also load with a given method.
341
     *
342
     * @var array
343
     */
344
    public $alsoLoadMethods = array();
345
346
    /**
347
     * READ-ONLY: The registered lifecycle callbacks for documents of this class.
348
     *
349
     * @var array
350
     */
351
    public $lifecycleCallbacks = array();
352
353
    /**
354
     * READ-ONLY: The discriminator value of this class.
355
     *
356
     * <b>This does only apply to the JOINED and SINGLE_COLLECTION inheritance mapping strategies
357
     * where a discriminator field is used.</b>
358
     *
359
     * @var mixed
360
     * @see discriminatorField
361
     */
362
    public $discriminatorValue;
363
364
    /**
365
     * READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
366
     *
367
     * <b>This does only apply to the SINGLE_COLLECTION inheritance mapping strategy
368
     * where a discriminator field is used.</b>
369
     *
370
     * @var mixed
371
     * @see discriminatorField
372
     */
373
    public $discriminatorMap = array();
374
375
    /**
376
     * READ-ONLY: The definition of the discriminator field used in SINGLE_COLLECTION
377
     * inheritance mapping.
378
     *
379
     * @var string
380
     */
381
    public $discriminatorField;
382
383
    /**
384
     * READ-ONLY: The default value for discriminatorField in case it's not set in the document
385
     *
386
     * @var string
387
     * @see discriminatorField
388
     */
389
    public $defaultDiscriminatorValue;
390
391
    /**
392
     * READ-ONLY: Whether this class describes the mapping of a mapped superclass.
393
     *
394
     * @var boolean
395
     */
396
    public $isMappedSuperclass = false;
397
398
    /**
399
     * READ-ONLY: Whether this class describes the mapping of a embedded document.
400
     *
401
     * @var boolean
402
     */
403
    public $isEmbeddedDocument = false;
404
405
    /**
406
     * READ-ONLY: Whether this class describes the mapping of an aggregation result document.
407
     *
408
     * @var boolean
409
     */
410
    public $isQueryResultDocument = false;
411
412
    /**
413
     * READ-ONLY: The policy used for change-tracking on entities of this class.
414
     *
415
     * @var integer
416
     */
417
    public $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT;
418
419
    /**
420
     * READ-ONLY: A flag for whether or not instances of this class are to be versioned
421
     * with optimistic locking.
422
     *
423
     * @var boolean $isVersioned
424
     */
425
    public $isVersioned;
426
427
    /**
428
     * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any).
429
     *
430
     * @var mixed $versionField
431
     */
432
    public $versionField;
433
434
    /**
435
     * READ-ONLY: A flag for whether or not instances of this class are to allow pessimistic
436
     * locking.
437
     *
438
     * @var boolean $isLockable
439
     */
440
    public $isLockable;
441
442
    /**
443
     * READ-ONLY: The name of the field which is used for locking a document.
444
     *
445
     * @var mixed $lockField
446
     */
447
    public $lockField;
448
449
    /**
450
     * The ReflectionClass instance of the mapped class.
451
     *
452
     * @var \ReflectionClass
453
     */
454
    public $reflClass;
455
456
    /**
457
     * Initializes a new ClassMetadata instance that will hold the object-document mapping
458
     * metadata of the class with the given name.
459
     *
460
     * @param string $documentName The name of the document class the new instance is used for.
461
     */
462 973
    public function __construct($documentName)
463
    {
464 973
        $this->name = $documentName;
465 973
        $this->rootDocumentName = $documentName;
466 973
    }
467
468
    /**
469
     * {@inheritDoc}
470
     */
471 902
    public function getReflectionClass()
472
    {
473 902
        if ( ! $this->reflClass) {
474 2
            $this->reflClass = new \ReflectionClass($this->name);
475
        }
476
477 902
        return $this->reflClass;
478
    }
479
480
    /**
481
     * {@inheritDoc}
482
     */
483 320
    public function isIdentifier($fieldName)
484
    {
485 320
        return $this->identifier === $fieldName;
486
    }
487
488
    /**
489
     * INTERNAL:
490
     * Sets the mapped identifier field of this class.
491
     *
492
     * @param string $identifier
493
     */
494 360
    public function setIdentifier($identifier)
495
    {
496 360
        $this->identifier = $identifier;
497 360
    }
498
499
    /**
500
     * {@inheritDoc}
501
     *
502
     * Since MongoDB only allows exactly one identifier field
503
     * this will always return an array with only one value
504
     */
505 41
    public function getIdentifier()
506
    {
507 41
        return array($this->identifier);
508
    }
509
510
    /**
511
     * {@inheritDoc}
512
     *
513
     * Since MongoDB only allows exactly one identifier field
514
     * this will always return an array with only one value
515
     */
516 96
    public function getIdentifierFieldNames()
517
    {
518 96
        return array($this->identifier);
519
    }
520
521
    /**
522
     * {@inheritDoc}
523
     */
524 552
    public function hasField($fieldName)
525
    {
526 552
        return isset($this->fieldMappings[$fieldName]);
527
    }
528
529
    /**
530
     * Sets the inheritance type used by the class and it's subclasses.
531
     *
532
     * @param integer $type
533
     */
534 376
    public function setInheritanceType($type)
535
    {
536 376
        $this->inheritanceType = $type;
537 376
    }
538
539
    /**
540
     * Checks whether a mapped field is inherited from an entity superclass.
541
     *
542
     * @param  string $fieldName
543
     *
544
     * @return boolean TRUE if the field is inherited, FALSE otherwise.
545
     */
546 902
    public function isInheritedField($fieldName)
547
    {
548 902
        return isset($this->fieldMappings[$fieldName]['inherited']);
549
    }
550
551
    /**
552
     * Registers a custom repository class for the document class.
553
     *
554
     * @param string $repositoryClassName The class name of the custom repository.
555
     */
556 313
    public function setCustomRepositoryClass($repositoryClassName)
557
    {
558 313
        if ($this->isEmbeddedDocument || $this->isQueryResultDocument) {
559
            return;
560
        }
561
562 313 View Code Duplication
        if ($repositoryClassName && strpos($repositoryClassName, '\\') === false && strlen($this->namespace)) {
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...
563 3
            $repositoryClassName = $this->namespace . '\\' . $repositoryClassName;
564
        }
565
566 313
        $this->customRepositoryClassName = $repositoryClassName;
567 313
    }
568
569
    /**
570
     * Dispatches the lifecycle event of the given document by invoking all
571
     * registered callbacks.
572
     *
573
     * @param string $event     Lifecycle event
574
     * @param object $document  Document on which the event occurred
575
     * @param array  $arguments Arguments to pass to all callbacks
576
     * @throws \InvalidArgumentException if document class is not this class or
577
     *                                   a Proxy of this class
578
     */
579 658
    public function invokeLifecycleCallbacks($event, $document, array $arguments = null)
580
    {
581 658
        if ( ! $document instanceof $this->name) {
582 1
            throw new \InvalidArgumentException(sprintf('Expected document class "%s"; found: "%s"', $this->name, get_class($document)));
583
        }
584
585 657
        if (empty($this->lifecycleCallbacks[$event])) {
586 642
            return;
587
        }
588
589 194
        foreach ($this->lifecycleCallbacks[$event] as $callback) {
590 194
            if ($arguments !== null) {
591 193
                call_user_func_array(array($document, $callback), $arguments);
592
            } else {
593 194
                $document->$callback();
594
            }
595
        }
596 194
    }
597
598
    /**
599
     * Checks whether the class has callbacks registered for a lifecycle event.
600
     *
601
     * @param string $event Lifecycle event
602
     *
603
     * @return boolean
604
     */
605
    public function hasLifecycleCallbacks($event)
606
    {
607
        return ! empty($this->lifecycleCallbacks[$event]);
608
    }
609
610
    /**
611
     * Gets the registered lifecycle callbacks for an event.
612
     *
613
     * @param string $event
614
     * @return array
615
     */
616
    public function getLifecycleCallbacks($event)
617
    {
618
        return isset($this->lifecycleCallbacks[$event]) ? $this->lifecycleCallbacks[$event] : array();
619
    }
620
621
    /**
622
     * Adds a lifecycle callback for documents of this class.
623
     *
624
     * If the callback is already registered, this is a NOOP.
625
     *
626
     * @param string $callback
627
     * @param string $event
628
     */
629 293
    public function addLifecycleCallback($callback, $event)
630
    {
631 293
        if (isset($this->lifecycleCallbacks[$event]) && in_array($callback, $this->lifecycleCallbacks[$event])) {
632 1
            return;
633
        }
634
635 293
        $this->lifecycleCallbacks[$event][] = $callback;
636 293
    }
637
638
    /**
639
     * Sets the lifecycle callbacks for documents of this class.
640
     *
641
     * Any previously registered callbacks are overwritten.
642
     *
643
     * @param array $callbacks
644
     */
645 359
    public function setLifecycleCallbacks(array $callbacks)
646
    {
647 359
        $this->lifecycleCallbacks = $callbacks;
648 359
    }
649
650
    /**
651
     * Registers a method for loading document data before field hydration.
652
     *
653
     * Note: A method may be registered multiple times for different fields.
654
     * it will be invoked only once for the first field found.
655
     *
656
     * @param string       $method Method name
657
     * @param array|string $fields Database field name(s)
658
     */
659 15
    public function registerAlsoLoadMethod($method, $fields)
660
    {
661 15
        $this->alsoLoadMethods[$method] = is_array($fields) ? $fields : array($fields);
662 15
    }
663
664
    /**
665
     * Sets the AlsoLoad methods for documents of this class.
666
     *
667
     * Any previously registered methods are overwritten.
668
     *
669
     * @param array $methods
670
     */
671 359
    public function setAlsoLoadMethods(array $methods)
672
    {
673 359
        $this->alsoLoadMethods = $methods;
674 359
    }
675
676
    /**
677
     * Sets the discriminator field.
678
     *
679
     * The field name is the the unmapped database field. Discriminator values
680
     * are only used to discern the hydration class and are not mapped to class
681
     * properties.
682
     *
683
     * @param string $discriminatorField
684
     *
685
     * @throws MappingException If the discriminator field conflicts with the
686
     *                          "name" attribute of a mapped field.
687
     */
688 386
    public function setDiscriminatorField($discriminatorField)
689
    {
690 386
        if ($discriminatorField === null) {
691 322
            $this->discriminatorField = null;
692
693 322
            return;
694
        }
695
696
        // Handle array argument with name/fieldName keys for BC
697 121
        if (is_array($discriminatorField)) {
698
            if (isset($discriminatorField['name'])) {
699
                $discriminatorField = $discriminatorField['name'];
700
            } elseif (isset($discriminatorField['fieldName'])) {
701
                $discriminatorField = $discriminatorField['fieldName'];
702
            }
703
        }
704
705 121
        foreach ($this->fieldMappings as $fieldMapping) {
706 4
            if ($discriminatorField == $fieldMapping['name']) {
707 4
                throw MappingException::discriminatorFieldConflict($this->name, $discriminatorField);
708
            }
709
        }
710
711 120
        $this->discriminatorField = $discriminatorField;
712 120
    }
713
714
    /**
715
     * Sets the discriminator values used by this class.
716
     * Used for JOINED and SINGLE_TABLE inheritance mapping strategies.
717
     *
718
     * @param array $map
719
     *
720
     * @throws MappingException
721
     */
722 382
    public function setDiscriminatorMap(array $map)
723
    {
724 382
        foreach ($map as $value => $className) {
725 119
            if (strpos($className, '\\') === false && strlen($this->namespace)) {
726 85
                $className = $this->namespace . '\\' . $className;
727
            }
728 119
            $this->discriminatorMap[$value] = $className;
729 119
            if ($this->name == $className) {
730 111
                $this->discriminatorValue = $value;
731
            } else {
732 114
                if ( ! class_exists($className)) {
733
                    throw MappingException::invalidClassInDiscriminatorMap($className, $this->name);
734
                }
735 114
                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...
736 119
                    $this->subClasses[] = $className;
737
                }
738
            }
739
        }
740 382
    }
741
742
    /**
743
     * Sets the default discriminator value to be used for this class
744
     * Used for JOINED and SINGLE_TABLE inheritance mapping strategies if the document has no discriminator value
745
     *
746
     * @param string $defaultDiscriminatorValue
747
     *
748
     * @throws MappingException
749
     */
750 366
    public function setDefaultDiscriminatorValue($defaultDiscriminatorValue)
751
    {
752 366
        if ($defaultDiscriminatorValue === null) {
753 359
            $this->defaultDiscriminatorValue = null;
754
755 359
            return;
756
        }
757
758 60
        if (!array_key_exists($defaultDiscriminatorValue, $this->discriminatorMap)) {
759
            throw MappingException::invalidDiscriminatorValue($defaultDiscriminatorValue, $this->name);
760
        }
761
762 60
        $this->defaultDiscriminatorValue = $defaultDiscriminatorValue;
763 60
    }
764
765
    /**
766
     * Sets the discriminator value for this class.
767
     * Used for JOINED/SINGLE_TABLE inheritance and multiple document types in a single
768
     * collection.
769
     *
770
     * @param string $value
771
     */
772
    public function setDiscriminatorValue($value)
773
    {
774
        $this->discriminatorMap[$value] = $this->name;
775
        $this->discriminatorValue = $value;
776
    }
777
778
    /**
779
     * Sets the slaveOkay option applied to collections for this class.
780
     *
781
     * @param boolean|null $slaveOkay
782
     */
783 3
    public function setSlaveOkay($slaveOkay)
784
    {
785 3
        $this->slaveOkay = $slaveOkay === null ? null : (boolean) $slaveOkay;
786 3
    }
787
788
    /**
789
     * Add a index for this Document.
790
     *
791
     * @param array $keys Array of keys for the index.
792
     * @param array $options Array of options for the index.
793
     */
794 229
    public function addIndex($keys, array $options = array())
795
    {
796 229
        $this->indexes[] = array(
797 View Code Duplication
            'keys' => array_map(function($value) {
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...
798 229
                if ($value == 1 || $value == -1) {
799 60
                    return (int) $value;
800
                }
801 222
                if (is_string($value)) {
802 222
                    $lower = strtolower($value);
803 222
                    if ($lower === 'asc') {
804 215
                        return 1;
805 11
                    } elseif ($lower === 'desc') {
806 4
                        return -1;
807
                    }
808
                }
809 7
                return $value;
810 229
            }, $keys),
811 229
            'options' => $options
812
        );
813 229
    }
814
815
    /**
816
     * Set whether or not queries on this document should require indexes.
817
     *
818
     * @param bool $requireIndexes
819
     *
820
     * @deprecated method was deprecated in 1.2 and will be removed in 2.0
821
     */
822 893
    public function setRequireIndexes($requireIndexes)
823
    {
824 893
        $this->requireIndexes = $requireIndexes;
0 ignored issues
show
Deprecated Code introduced by
The property Doctrine\ODM\MongoDB\Map...taInfo::$requireIndexes has been deprecated with message: property was deprecated in 1.2 and will be removed in 2.0

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
825 893
    }
826
827
    /**
828
     * Returns the array of indexes for this Document.
829
     *
830
     * @return array $indexes The array of indexes.
831
     */
832 54
    public function getIndexes()
833
    {
834 54
        return $this->indexes;
835
    }
836
837
    /**
838
     * Checks whether this document has indexes or not.
839
     *
840
     * @return boolean
841
     */
842
    public function hasIndexes()
843
    {
844
        return $this->indexes ? true : false;
845
    }
846
847
    /**
848
     * Set shard key for this Document.
849
     *
850
     * @param array $keys Array of document keys.
851
     * @param array $options Array of sharding options.
852
     *
853
     * @throws MappingException
854
     */
855 87
    public function setShardKey(array $keys, array $options = array())
856
    {
857 87
        if ($this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_COLLECTION && !is_null($this->shardKey)) {
858 2
            throw MappingException::shardKeyInSingleCollInheritanceSubclass($this->getName());
859
        }
860
861 87
        if ($this->isEmbeddedDocument) {
862 2
            throw MappingException::embeddedDocumentCantHaveShardKey($this->getName());
863
        }
864
865 85
        foreach (array_keys($keys) as $field) {
866 85
            if (! isset($this->fieldMappings[$field])) {
867 78
                continue;
868
            }
869
870 7
            if (in_array($this->fieldMappings[$field]['type'], ['many', 'collection'])) {
871 3
                throw MappingException::noMultiKeyShardKeys($this->getName(), $field);
872
            }
873
874 4
            if ($this->fieldMappings[$field]['strategy'] !== static::STORAGE_STRATEGY_SET) {
875 4
                throw MappingException::onlySetStrategyAllowedInShardKey($this->getName(), $field);
876
            }
877
        }
878
879 81
        $this->shardKey = array(
880 View Code Duplication
            'keys' => array_map(function($value) {
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...
881 81
                if ($value == 1 || $value == -1) {
882 6
                    return (int) $value;
883
                }
884 80
                if (is_string($value)) {
885 80
                    $lower = strtolower($value);
886 80
                    if ($lower === 'asc') {
887 79
                        return 1;
888 53
                    } elseif ($lower === 'desc') {
889
                        return -1;
890
                    }
891
                }
892 53
                return $value;
893 81
            }, $keys),
894 81
            'options' => $options
895
        );
896 81
    }
897
898
    /**
899
     * @return array
900
     */
901 28
    public function getShardKey()
902
    {
903 28
        return $this->shardKey;
904
    }
905
906
    /**
907
     * Checks whether this document has shard key or not.
908
     *
909
     * @return bool
910
     */
911 594
    public function isSharded()
912
    {
913 594
        return $this->shardKey ? true : false;
914
    }
915
916
    /**
917
     * Sets the write concern used by this class.
918
     *
919
     * @param string $writeConcern
920
     */
921 373
    public function setWriteConcern($writeConcern)
922
    {
923 373
        $this->writeConcern = $writeConcern;
924 373
    }
925
926
    /**
927
     * @return string
928
     */
929 12
    public function getWriteConcern()
930
    {
931 12
        return $this->writeConcern;
932
    }
933
934
    /**
935
     * Whether there is a write concern configured for this class.
936
     *
937
     * @return bool
938
     */
939 607
    public function hasWriteConcern()
940
    {
941 607
        return $this->writeConcern !== null;
942
    }
943
944
    /**
945
     * Sets the change tracking policy used by this class.
946
     *
947
     * @param integer $policy
948
     */
949 364
    public function setChangeTrackingPolicy($policy)
950
    {
951 364
        $this->changeTrackingPolicy = $policy;
952 364
    }
953
954
    /**
955
     * Whether the change tracking policy of this class is "deferred explicit".
956
     *
957
     * @return boolean
958
     */
959 70
    public function isChangeTrackingDeferredExplicit()
960
    {
961 70
        return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_EXPLICIT;
962
    }
963
964
    /**
965
     * Whether the change tracking policy of this class is "deferred implicit".
966
     *
967
     * @return boolean
968
     */
969 627
    public function isChangeTrackingDeferredImplicit()
970
    {
971 627
        return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_IMPLICIT;
972
    }
973
974
    /**
975
     * Whether the change tracking policy of this class is "notify".
976
     *
977
     * @return boolean
978
     */
979 347
    public function isChangeTrackingNotify()
980
    {
981 347
        return $this->changeTrackingPolicy == self::CHANGETRACKING_NOTIFY;
982
    }
983
984
    /**
985
     * Gets the ReflectionProperties of the mapped class.
986
     *
987
     * @return array An array of ReflectionProperty instances.
988
     */
989 96
    public function getReflectionProperties()
990
    {
991 96
        return $this->reflFields;
992
    }
993
994
    /**
995
     * Gets a ReflectionProperty for a specific field of the mapped class.
996
     *
997
     * @param string $name
998
     *
999
     * @return \ReflectionProperty
1000
     */
1001
    public function getReflectionProperty($name)
1002
    {
1003
        return $this->reflFields[$name];
1004
    }
1005
1006
    /**
1007
     * {@inheritDoc}
1008
     */
1009 908
    public function getName()
1010
    {
1011 908
        return $this->name;
1012
    }
1013
1014
    /**
1015
     * The namespace this Document class belongs to.
1016
     *
1017
     * @return string $namespace The namespace name.
1018
     */
1019
    public function getNamespace()
1020
    {
1021
        return $this->namespace;
1022
    }
1023
1024
    /**
1025
     * Returns the database this Document is mapped to.
1026
     *
1027
     * @return string $db The database name.
1028
     */
1029 829
    public function getDatabase()
1030
    {
1031 829
        return $this->db;
1032
    }
1033
1034
    /**
1035
     * Set the database this Document is mapped to.
1036
     *
1037
     * @param string $db The database name
1038
     */
1039 97
    public function setDatabase($db)
1040
    {
1041 97
        $this->db = $db;
1042 97
    }
1043
1044
    /**
1045
     * Get the collection this Document is mapped to.
1046
     *
1047
     * @return string $collection The collection name.
1048
     */
1049 835
    public function getCollection()
1050
    {
1051 835
        return $this->collection;
1052
    }
1053
1054
    /**
1055
     * Sets the collection this Document is mapped to.
1056
     *
1057
     * @param array|string $name
1058
     *
1059
     * @throws \InvalidArgumentException
1060
     */
1061 936
    public function setCollection($name)
1062
    {
1063 936
        if (is_array($name)) {
1064
            if ( ! isset($name['name'])) {
1065
                throw new \InvalidArgumentException('A name key is required when passing an array to setCollection()');
1066
            }
1067
            $this->collectionCapped = isset($name['capped']) ? $name['capped'] : false;
1068
            $this->collectionSize = isset($name['size']) ? $name['size'] : 0;
1069
            $this->collectionMax = isset($name['max']) ? $name['max'] : 0;
1070
            $this->collection = $name['name'];
1071
        } else {
1072 936
            $this->collection = $name;
1073
        }
1074 936
    }
1075
1076
    /**
1077
     * Get whether or not the documents collection is capped.
1078
     *
1079
     * @return boolean
1080
     */
1081 4
    public function getCollectionCapped()
1082
    {
1083 4
        return $this->collectionCapped;
1084
    }
1085
1086
    /**
1087
     * Set whether or not the documents collection is capped.
1088
     *
1089
     * @param boolean $bool
1090
     */
1091 1
    public function setCollectionCapped($bool)
1092
    {
1093 1
        $this->collectionCapped = $bool;
1094 1
    }
1095
1096
    /**
1097
     * Get the collection size
1098
     *
1099
     * @return integer
1100
     */
1101 4
    public function getCollectionSize()
1102
    {
1103 4
        return $this->collectionSize;
1104
    }
1105
1106
    /**
1107
     * Set the collection size.
1108
     *
1109
     * @param integer $size
1110
     */
1111 1
    public function setCollectionSize($size)
1112
    {
1113 1
        $this->collectionSize = $size;
1114 1
    }
1115
1116
    /**
1117
     * Get the collection max.
1118
     *
1119
     * @return integer
1120
     */
1121 4
    public function getCollectionMax()
1122
    {
1123 4
        return $this->collectionMax;
1124
    }
1125
1126
    /**
1127
     * Set the collection max.
1128
     *
1129
     * @param integer $max
1130
     */
1131 1
    public function setCollectionMax($max)
1132
    {
1133 1
        $this->collectionMax = $max;
1134 1
    }
1135
1136
    /**
1137
     * Returns TRUE if this Document is mapped to a collection FALSE otherwise.
1138
     *
1139
     * @return boolean
1140
     */
1141
    public function isMappedToCollection()
1142
    {
1143
        return $this->collection ? true : false;
1144
    }
1145
1146
    /**
1147
     * Returns TRUE if this Document is a file to be stored on the MongoGridFS FALSE otherwise.
1148
     *
1149
     * @return boolean
1150
     */
1151 775
    public function isFile()
1152
    {
1153 775
        return $this->file ? true : false;
1154
    }
1155
1156
    /**
1157
     * Returns the file field name.
1158
     *
1159
     * @return string $file The file field name.
1160
     */
1161 359
    public function getFile()
1162
    {
1163 359
        return $this->file;
1164
    }
1165
1166
    /**
1167
     * Set the field name that stores the grid file.
1168
     *
1169
     * @param string $file
1170
     */
1171 360
    public function setFile($file)
1172
    {
1173 360
        $this->file = $file;
1174 360
    }
1175
1176
    /**
1177
     * Returns the distance field name.
1178
     *
1179
     * @return string $distance The distance field name.
1180
     */
1181
    public function getDistance()
1182
    {
1183
        return $this->distance;
1184
    }
1185
1186
    /**
1187
     * Set the field name that stores the distance.
1188
     *
1189
     * @param string $distance
1190
     */
1191 1
    public function setDistance($distance)
1192
    {
1193 1
        $this->distance = $distance;
1194 1
    }
1195
1196
    /**
1197
     * Map a field.
1198
     *
1199
     * @param array $mapping The mapping information.
1200
     *
1201
     * @return array
1202
     *
1203
     * @throws MappingException
1204
     */
1205 951
    public function mapField(array $mapping)
1206
    {
1207 951
        if ( ! isset($mapping['fieldName']) && isset($mapping['name'])) {
1208 9
            $mapping['fieldName'] = $mapping['name'];
1209
        }
1210 951
        if ( ! isset($mapping['fieldName'])) {
1211
            throw MappingException::missingFieldName($this->name);
1212
        }
1213 951
        if ( ! isset($mapping['name'])) {
1214 942
            $mapping['name'] = $mapping['fieldName'];
1215
        }
1216 951
        if ($this->identifier === $mapping['name'] && empty($mapping['id'])) {
1217 1
            throw MappingException::mustNotChangeIdentifierFieldsType($this->name, $mapping['name']);
1218
        }
1219 950
        if (isset($this->fieldMappings[$mapping['fieldName']])) {
1220
            //throw MappingException::duplicateFieldMapping($this->name, $mapping['fieldName']);
1221
        }
1222 950
        if ($this->discriminatorField !== null && $this->discriminatorField == $mapping['name']) {
1223 1
            throw MappingException::discriminatorFieldConflict($this->name, $this->discriminatorField);
1224
        }
1225 949 View Code Duplication
        if (isset($mapping['targetDocument']) && strpos($mapping['targetDocument'], '\\') === false && strlen($this->namespace)) {
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...
1226 605
            $mapping['targetDocument'] = $this->namespace . '\\' . $mapping['targetDocument'];
1227
        }
1228 949
        if (isset($mapping['collectionClass'])) {
1229 65 View Code Duplication
            if (strpos($mapping['collectionClass'], '\\') === false && strlen($this->namespace)) {
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...
1230 63
                $mapping['collectionClass'] = $this->namespace . '\\' . $mapping['collectionClass'];
1231
            }
1232 65
            $mapping['collectionClass'] = ltrim($mapping['collectionClass'], '\\');
1233
        }
1234 949
        if ( ! empty($mapping['collectionClass'])) {
1235 65
            $rColl = new \ReflectionClass($mapping['collectionClass']);
1236 65
            if ( ! $rColl->implementsInterface('Doctrine\\Common\\Collections\\Collection')) {
1237 1
                throw MappingException::collectionClassDoesNotImplementCommonInterface($this->name, $mapping['fieldName'], $mapping['collectionClass']);
1238
            }
1239
        }
1240
1241 948
        if (isset($mapping['discriminatorMap'])) {
1242 123
            foreach ($mapping['discriminatorMap'] as $key => $class) {
1243 123 View Code Duplication
                if (strpos($class, '\\') === false && strlen($this->namespace)) {
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...
1244 123
                    $mapping['discriminatorMap'][$key] = $this->namespace . '\\' . $class;
1245
                }
1246
            }
1247
        }
1248
1249 948
        if (isset($mapping['cascade']) && isset($mapping['embedded'])) {
1250 1
            throw MappingException::cascadeOnEmbeddedNotAllowed($this->name, $mapping['fieldName']);
1251
        }
1252
1253 947
        $cascades = isset($mapping['cascade']) ? array_map('strtolower', (array) $mapping['cascade']) : array();
1254
1255 947
        if (in_array('all', $cascades) || isset($mapping['embedded'])) {
1256 631
            $cascades = array('remove', 'persist', 'refresh', 'merge', 'detach');
1257
        }
1258
1259 947
        if (isset($mapping['embedded'])) {
1260 594
            unset($mapping['cascade']);
1261 942
        } elseif (isset($mapping['cascade'])) {
1262 394
            $mapping['cascade'] = $cascades;
1263
        }
1264
1265 947
        $mapping['isCascadeRemove'] = in_array('remove', $cascades);
1266 947
        $mapping['isCascadePersist'] = in_array('persist', $cascades);
1267 947
        $mapping['isCascadeRefresh'] = in_array('refresh', $cascades);
1268 947
        $mapping['isCascadeMerge'] = in_array('merge', $cascades);
1269 947
        $mapping['isCascadeDetach'] = in_array('detach', $cascades);
1270
1271 947
        if (isset($mapping['type']) && $mapping['type'] === 'file') {
1272 63
            $mapping['file'] = true;
1273
        }
1274 947
        if (isset($mapping['type']) && $mapping['type'] === 'increment') {
1275 1
            $mapping['strategy'] = self::STORAGE_STRATEGY_INCREMENT;
1276
        }
1277 947 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...
1278 63
            $this->file = $mapping['fieldName'];
1279 63
            $mapping['name'] = 'file';
1280
        }
1281 947 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...
1282 7
            $this->distance = $mapping['fieldName'];
1283
        }
1284 947
        if (isset($mapping['id']) && $mapping['id'] === true) {
1285 918
            $mapping['name'] = '_id';
1286 918
            $this->identifier = $mapping['fieldName'];
1287 918 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...
1288 901
                $this->generatorType = constant(ClassMetadata::class . '::GENERATOR_TYPE_' . strtoupper($mapping['strategy']));
1289
            }
1290 918
            $this->generatorOptions = isset($mapping['options']) ? $mapping['options'] : array();
1291 918
            switch ($this->generatorType) {
1292 918
                case self::GENERATOR_TYPE_AUTO:
1293 846
                    $mapping['type'] = 'id';
1294 846
                    break;
1295
                default:
1296 151
                    if ( ! empty($this->generatorOptions['type'])) {
1297 52
                        $mapping['type'] = $this->generatorOptions['type'];
1298 99
                    } elseif (empty($mapping['type'])) {
1299 84
                        $mapping['type'] = $this->generatorType === self::GENERATOR_TYPE_INCREMENT ? 'int_id' : 'custom_id';
1300
                    }
1301
            }
1302 918
            unset($this->generatorOptions['type']);
1303
        }
1304
1305 947
        if ( ! isset($mapping['nullable'])) {
1306 52
            $mapping['nullable'] = false;
1307
        }
1308
1309
        // Synchronize the "simple" and "storeAs" mapping information for backwards compatibility
1310 947
        if (isset($mapping['simple']) && ($mapping['simple'] === true || $mapping['simple'] === 'true')) {
1311 287
            $mapping['storeAs'] = ClassMetadataInfo::REFERENCE_STORE_AS_ID;
1312
        }
1313
        // Provide the correct value for the "simple" field for backwards compatibility
1314 947
        if (isset($mapping['storeAs'])) {
1315 574
            $mapping['simple'] = $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID;
1316
        }
1317
1318 947 View Code Duplication
        if (isset($mapping['reference'])
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...
1319 947
            && isset($mapping['storeAs'])
1320 947
            && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID
1321 947
            && ! isset($mapping['targetDocument'])
1322
        ) {
1323 3
            throw MappingException::simpleReferenceRequiresTargetDocument($this->name, $mapping['fieldName']);
1324
        }
1325
1326 944 View Code Duplication
        if (isset($mapping['reference'])
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...
1327 944
            && isset($mapping['storeAs'])
1328 944
            && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID
1329 944
            && ! empty($mapping['redundantFields'])
1330
        ) {
1331 1
            throw MappingException::simpleReferenceCannotHaveRedundantFields($this->name, $mapping['fieldName']);
1332
        }
1333
1334 943
        if (isset($mapping['reference']) && empty($mapping['targetDocument']) && empty($mapping['discriminatorMap']) &&
1335 943
                (isset($mapping['mappedBy']) || isset($mapping['inversedBy']))) {
1336 4
            throw MappingException::owningAndInverseReferencesRequireTargetDocument($this->name, $mapping['fieldName']);
1337
        }
1338
1339 939
        if ($this->isEmbeddedDocument && $mapping['type'] === 'many' && CollectionHelper::isAtomic($mapping['strategy'])) {
1340 1
            throw MappingException::atomicCollectionStrategyNotAllowed($mapping['strategy'], $this->name, $mapping['fieldName']);
1341
        }
1342
1343 938 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...
1344 508
            $mapping['association'] = self::REFERENCE_ONE;
1345
        }
1346 938 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...
1347 447
            $mapping['association'] = self::REFERENCE_MANY;
1348
        }
1349 938 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...
1350 455
            $mapping['association'] = self::EMBED_ONE;
1351
        }
1352 938 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...
1353 500
            $mapping['association'] = self::EMBED_MANY;
1354
        }
1355
1356 938
        if (isset($mapping['association']) && ! isset($mapping['targetDocument']) && ! isset($mapping['discriminatorField'])) {
1357 131
            $mapping['discriminatorField'] = self::DEFAULT_DISCRIMINATOR_FIELD;
1358
        }
1359
1360
        /*
1361
        if (isset($mapping['type']) && ($mapping['type'] === 'one' || $mapping['type'] === 'many')) {
1362
            $mapping['type'] = $mapping['type'] === 'one' ? self::ONE : self::MANY;
1363
        }
1364
        */
1365 938
        if (isset($mapping['version'])) {
1366 100
            $mapping['notSaved'] = true;
1367 100
            $this->setVersionMapping($mapping);
1368
        }
1369 938
        if (isset($mapping['lock'])) {
1370 27
            $mapping['notSaved'] = true;
1371 27
            $this->setLockMapping($mapping);
1372
        }
1373 938
        $mapping['isOwningSide'] = true;
1374 938
        $mapping['isInverseSide'] = false;
1375 938
        if (isset($mapping['reference'])) {
1376 578 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...
1377 83
                $mapping['isOwningSide'] = true;
1378 83
                $mapping['isInverseSide'] = false;
1379
            }
1380 578 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...
1381 288
                $mapping['isInverseSide'] = true;
1382 288
                $mapping['isOwningSide'] = false;
1383
            }
1384 578 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...
1385 63
                $mapping['isInverseSide'] = true;
1386 63
                $mapping['isOwningSide'] = false;
1387
            }
1388 578
            if (!isset($mapping['orphanRemoval'])) {
1389 555
                $mapping['orphanRemoval'] = false;
1390
            }
1391
        }
1392
1393 938
        $this->applyStorageStrategy($mapping);
1394
1395 937
        $this->fieldMappings[$mapping['fieldName']] = $mapping;
1396 937
        if (isset($mapping['association'])) {
1397 728
            $this->associationMappings[$mapping['fieldName']] = $mapping;
1398
        }
1399
1400 937
        return $mapping;
1401
    }
1402
1403
    /**
1404
     * Validates the storage strategy of a mapping for consistency
1405
     * @param array $mapping
1406
     * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException
1407
     */
1408 938
    private function applyStorageStrategy(array &$mapping)
1409
    {
1410 938
        if (! isset($mapping['type']) || isset($mapping['id'])) {
1411 920
            return;
1412
        }
1413
1414
        switch (true) {
1415 900
            case $mapping['type'] == 'int':
1416 899
            case $mapping['type'] == 'float':
1417 899
            case $mapping['type'] == 'increment':
1418 330
                $defaultStrategy = self::STORAGE_STRATEGY_SET;
1419 330
                $allowedStrategies = [self::STORAGE_STRATEGY_SET, self::STORAGE_STRATEGY_INCREMENT];
1420 330
                break;
1421
1422 898
            case $mapping['type'] == 'many':
1423 604
                $defaultStrategy = CollectionHelper::DEFAULT_STRATEGY;
1424
                $allowedStrategies = [
1425 604
                    self::STORAGE_STRATEGY_PUSH_ALL,
1426 604
                    self::STORAGE_STRATEGY_ADD_TO_SET,
1427 604
                    self::STORAGE_STRATEGY_SET,
1428 604
                    self::STORAGE_STRATEGY_SET_ARRAY,
1429 604
                    self::STORAGE_STRATEGY_ATOMIC_SET,
1430 604
                    self::STORAGE_STRATEGY_ATOMIC_SET_ARRAY,
1431
                ];
1432 604
                break;
1433
1434
            default:
1435 888
                $defaultStrategy = self::STORAGE_STRATEGY_SET;
1436 888
                $allowedStrategies = [self::STORAGE_STRATEGY_SET];
1437
        }
1438
1439 900
        if (! isset($mapping['strategy'])) {
1440 891
            $mapping['strategy'] = $defaultStrategy;
1441
        }
1442
1443 900
        if (! in_array($mapping['strategy'], $allowedStrategies)) {
1444
            throw MappingException::invalidStorageStrategy($this->name, $mapping['fieldName'], $mapping['type'], $mapping['strategy']);
1445
        }
1446
1447 900
        if (isset($mapping['reference']) && $mapping['type'] === 'many' && $mapping['isOwningSide']
1448 900
            && ! empty($mapping['sort']) && ! CollectionHelper::usesSet($mapping['strategy'])) {
1449 1
            throw MappingException::referenceManySortMustNotBeUsedWithNonSetCollectionStrategy($this->name, $mapping['fieldName'], $mapping['strategy']);
1450
        }
1451 899
    }
1452
1453
    /**
1454
     * Map a MongoGridFSFile.
1455
     *
1456
     * @param array $mapping The mapping information.
1457
     */
1458
    public function mapFile(array $mapping)
1459
    {
1460
        $mapping['file'] = true;
1461
        $mapping['type'] = 'file';
1462
        $this->mapField($mapping);
1463
    }
1464
1465
    /**
1466
     * Map a single embedded document.
1467
     *
1468
     * @param array $mapping The mapping information.
1469
     */
1470 6
    public function mapOneEmbedded(array $mapping)
1471
    {
1472 6
        $mapping['embedded'] = true;
1473 6
        $mapping['type'] = 'one';
1474 6
        $this->mapField($mapping);
1475 5
    }
1476
1477
    /**
1478
     * Map a collection of embedded documents.
1479
     *
1480
     * @param array $mapping The mapping information.
1481
     */
1482 5
    public function mapManyEmbedded(array $mapping)
1483
    {
1484 5
        $mapping['embedded'] = true;
1485 5
        $mapping['type'] = 'many';
1486 5
        $this->mapField($mapping);
1487 5
    }
1488
1489
    /**
1490
     * Map a single document reference.
1491
     *
1492
     * @param array $mapping The mapping information.
1493
     */
1494 9
    public function mapOneReference(array $mapping)
1495
    {
1496 9
        $mapping['reference'] = true;
1497 9
        $mapping['type'] = 'one';
1498 9
        $this->mapField($mapping);
1499 8
    }
1500
1501
    /**
1502
     * Map a collection of document references.
1503
     *
1504
     * @param array $mapping The mapping information.
1505
     */
1506 8
    public function mapManyReference(array $mapping)
1507
    {
1508 8
        $mapping['reference'] = true;
1509 8
        $mapping['type'] = 'many';
1510 8
        $this->mapField($mapping);
1511 8
    }
1512
1513
    /**
1514
     * INTERNAL:
1515
     * Adds a field mapping without completing/validating it.
1516
     * This is mainly used to add inherited field mappings to derived classes.
1517
     *
1518
     * @param array $fieldMapping
1519
     */
1520 123
    public function addInheritedFieldMapping(array $fieldMapping)
1521
    {
1522 123
        $this->fieldMappings[$fieldMapping['fieldName']] = $fieldMapping;
1523
1524 123
        if (isset($fieldMapping['association'])) {
1525 77
            $this->associationMappings[$fieldMapping['fieldName']] = $fieldMapping;
1526
        }
1527 123
    }
1528
1529
    /**
1530
     * INTERNAL:
1531
     * Adds an association mapping without completing/validating it.
1532
     * This is mainly used to add inherited association mappings to derived classes.
1533
     *
1534
     * @param array $mapping
1535
     *
1536
     * @return void
1537
     *
1538
     * @throws MappingException
1539
     */
1540 78
    public function addInheritedAssociationMapping(array $mapping/*, $owningClassName = null*/)
1541
    {
1542 78
        $this->associationMappings[$mapping['fieldName']] = $mapping;
1543 78
    }
1544
1545
    /**
1546
     * Checks whether the class has a mapped association with the given field name.
1547
     *
1548
     * @param string $fieldName
1549
     * @return boolean
1550
     */
1551 18
    public function hasReference($fieldName)
1552
    {
1553 18
        return isset($this->fieldMappings[$fieldName]['reference']);
1554
    }
1555
1556
    /**
1557
     * Checks whether the class has a mapped embed with the given field name.
1558
     *
1559
     * @param string $fieldName
1560
     * @return boolean
1561
     */
1562 9
    public function hasEmbed($fieldName)
1563
    {
1564 9
        return isset($this->fieldMappings[$fieldName]['embedded']);
1565
    }
1566
1567
    /**
1568
     * {@inheritDoc}
1569
     *
1570
     * Checks whether the class has a mapped association (embed or reference) with the given field name.
1571
     */
1572 11
    public function hasAssociation($fieldName)
1573
    {
1574 11
        return $this->hasReference($fieldName) || $this->hasEmbed($fieldName);
1575
    }
1576
1577
    /**
1578
     * {@inheritDoc}
1579
     *
1580
     * Checks whether the class has a mapped reference or embed for the specified field and
1581
     * is a single valued association.
1582
     */
1583
    public function isSingleValuedAssociation($fieldName)
1584
    {
1585
        return $this->isSingleValuedReference($fieldName) || $this->isSingleValuedEmbed($fieldName);
1586
    }
1587
1588
    /**
1589
     * {@inheritDoc}
1590
     *
1591
     * Checks whether the class has a mapped reference or embed for the specified field and
1592
     * is a collection valued association.
1593
     */
1594
    public function isCollectionValuedAssociation($fieldName)
1595
    {
1596
        return $this->isCollectionValuedReference($fieldName) || $this->isCollectionValuedEmbed($fieldName);
1597
    }
1598
1599
    /**
1600
     * Checks whether the class has a mapped association for the specified field
1601
     * and if yes, checks whether it is a single-valued association (to-one).
1602
     *
1603
     * @param string $fieldName
1604
     * @return boolean TRUE if the association exists and is single-valued, FALSE otherwise.
1605
     */
1606
    public function isSingleValuedReference($fieldName)
1607
    {
1608
        return isset($this->fieldMappings[$fieldName]['association']) &&
1609
            $this->fieldMappings[$fieldName]['association'] === self::REFERENCE_ONE;
1610
    }
1611
1612
    /**
1613
     * Checks whether the class has a mapped association for the specified field
1614
     * and if yes, checks whether it is a collection-valued association (to-many).
1615
     *
1616
     * @param string $fieldName
1617
     * @return boolean TRUE if the association exists and is collection-valued, FALSE otherwise.
1618
     */
1619
    public function isCollectionValuedReference($fieldName)
1620
    {
1621
        return isset($this->fieldMappings[$fieldName]['association']) &&
1622
            $this->fieldMappings[$fieldName]['association'] === self::REFERENCE_MANY;
1623
    }
1624
1625
    /**
1626
     * Checks whether the class has a mapped embedded document for the specified field
1627
     * and if yes, checks whether it is a single-valued association (to-one).
1628
     *
1629
     * @param string $fieldName
1630
     * @return boolean TRUE if the association exists and is single-valued, FALSE otherwise.
1631
     */
1632
    public function isSingleValuedEmbed($fieldName)
1633
    {
1634
        return isset($this->fieldMappings[$fieldName]['association']) &&
1635
            $this->fieldMappings[$fieldName]['association'] === self::EMBED_ONE;
1636
    }
1637
1638
    /**
1639
     * Checks whether the class has a mapped embedded document for the specified field
1640
     * and if yes, checks whether it is a collection-valued association (to-many).
1641
     *
1642
     * @param string $fieldName
1643
     * @return boolean TRUE if the association exists and is collection-valued, FALSE otherwise.
1644
     */
1645
    public function isCollectionValuedEmbed($fieldName)
1646
    {
1647
        return isset($this->fieldMappings[$fieldName]['association']) &&
1648
            $this->fieldMappings[$fieldName]['association'] === self::EMBED_MANY;
1649
    }
1650
1651
    /**
1652
     * Sets the ID generator used to generate IDs for instances of this class.
1653
     *
1654
     * @param \Doctrine\ODM\MongoDB\Id\AbstractIdGenerator $generator
1655
     */
1656 841
    public function setIdGenerator($generator)
1657
    {
1658 841
        $this->idGenerator = $generator;
1659 841
    }
1660
1661
    /**
1662
     * Casts the identifier to its portable PHP type.
1663
     *
1664
     * @param mixed $id
1665
     * @return mixed $id
1666
     */
1667 644
    public function getPHPIdentifierValue($id)
1668
    {
1669 644
        $idType = $this->fieldMappings[$this->identifier]['type'];
1670 644
        return Type::getType($idType)->convertToPHPValue($id);
1671
    }
1672
1673
    /**
1674
     * Casts the identifier to its database type.
1675
     *
1676
     * @param mixed $id
1677
     * @return mixed $id
1678
     */
1679 712
    public function getDatabaseIdentifierValue($id)
1680
    {
1681 712
        $idType = $this->fieldMappings[$this->identifier]['type'];
1682 712
        return Type::getType($idType)->convertToDatabaseValue($id);
1683
    }
1684
1685
    /**
1686
     * Sets the document identifier of a document.
1687
     *
1688
     * The value will be converted to a PHP type before being set.
1689
     *
1690
     * @param object $document
1691
     * @param mixed $id
1692
     */
1693 575
    public function setIdentifierValue($document, $id)
1694
    {
1695 575
        $id = $this->getPHPIdentifierValue($id);
1696 575
        $this->reflFields[$this->identifier]->setValue($document, $id);
1697 575
    }
1698
1699
    /**
1700
     * Gets the document identifier as a PHP type.
1701
     *
1702
     * @param object $document
1703
     * @return mixed $id
1704
     */
1705 663
    public function getIdentifierValue($document)
1706
    {
1707 663
        return $this->reflFields[$this->identifier]->getValue($document);
1708
    }
1709
1710
    /**
1711
     * {@inheritDoc}
1712
     *
1713
     * Since MongoDB only allows exactly one identifier field this is a proxy
1714
     * to {@see getIdentifierValue()} and returns an array with the identifier
1715
     * field as a key.
1716
     */
1717
    public function getIdentifierValues($object)
1718
    {
1719
        return array($this->identifier => $this->getIdentifierValue($object));
1720
    }
1721
1722
    /**
1723
     * Get the document identifier object as a database type.
1724
     *
1725
     * @param object $document
1726
     *
1727
     * @return \MongoId $id The MongoID object.
1728
     */
1729 34
    public function getIdentifierObject($document)
1730
    {
1731 34
        return $this->getDatabaseIdentifierValue($this->getIdentifierValue($document));
1732
    }
1733
1734
    /**
1735
     * Sets the specified field to the specified value on the given document.
1736
     *
1737
     * @param object $document
1738
     * @param string $field
1739
     * @param mixed $value
1740
     */
1741 8
    public function setFieldValue($document, $field, $value)
1742
    {
1743 8
        if ($document instanceof Proxy && ! $document->__isInitialized()) {
1744
            //property changes to an uninitialized proxy will not be tracked or persisted,
1745
            //so the proxy needs to be loaded first.
1746 1
            $document->__load();
1747
        }
1748
1749 8
        $this->reflFields[$field]->setValue($document, $value);
1750 8
    }
1751
1752
    /**
1753
     * Gets the specified field's value off the given document.
1754
     *
1755
     * @param object $document
1756
     * @param string $field
1757
     *
1758
     * @return mixed
1759
     */
1760 31
    public function getFieldValue($document, $field)
1761
    {
1762 31
        if ($document instanceof Proxy && $field !== $this->identifier && ! $document->__isInitialized()) {
1763 2
            $document->__load();
1764
        }
1765
1766 31
        return $this->reflFields[$field]->getValue($document);
1767
    }
1768
1769
    /**
1770
     * Gets the mapping of a field.
1771
     *
1772
     * @param string $fieldName  The field name.
1773
     *
1774
     * @return array  The field mapping.
1775
     *
1776
     * @throws MappingException if the $fieldName is not found in the fieldMappings array
1777
     */
1778 105
    public function getFieldMapping($fieldName)
1779
    {
1780 105
        if ( ! isset($this->fieldMappings[$fieldName])) {
1781 6
            throw MappingException::mappingNotFound($this->name, $fieldName);
1782
        }
1783 103
        return $this->fieldMappings[$fieldName];
1784
    }
1785
1786
    /**
1787
     * Gets mappings of fields holding embedded document(s).
1788
     *
1789
     * @return array of field mappings
1790
     */
1791 619
    public function getEmbeddedFieldsMappings()
1792
    {
1793 619
        return array_filter(
1794 619
            $this->associationMappings,
1795
            function($assoc) { return ! empty($assoc['embedded']); }
1796
        );
1797
    }
1798
1799
    /**
1800
     * Gets the field mapping by its DB name.
1801
     * E.g. it returns identifier's mapping when called with _id.
1802
     *
1803
     * @param string $dbFieldName
1804
     *
1805
     * @return array
1806
     * @throws MappingException
1807
     */
1808 9
    public function getFieldMappingByDbFieldName($dbFieldName)
1809
    {
1810 9
        foreach ($this->fieldMappings as $mapping) {
1811 9
            if ($mapping['name'] == $dbFieldName) {
1812 9
                return $mapping;
1813
            }
1814
        }
1815
1816
        throw MappingException::mappingNotFoundByDbName($this->name, $dbFieldName);
1817
    }
1818
1819
    /**
1820
     * Check if the field is not null.
1821
     *
1822
     * @param string $fieldName  The field name
1823
     *
1824
     * @return boolean  TRUE if the field is not null, FALSE otherwise.
1825
     */
1826 1
    public function isNullable($fieldName)
1827
    {
1828 1
        $mapping = $this->getFieldMapping($fieldName);
1829 1
        if ($mapping !== false) {
1830 1
            return isset($mapping['nullable']) && $mapping['nullable'] == true;
1831
        }
1832
        return false;
1833
    }
1834
1835
    /**
1836
     * Checks whether the document has a discriminator field and value configured.
1837
     *
1838
     * @return boolean
1839
     */
1840 521
    public function hasDiscriminator()
1841
    {
1842 521
        return isset($this->discriminatorField, $this->discriminatorValue);
1843
    }
1844
1845
    /**
1846
     * Sets the type of Id generator to use for the mapped class.
1847
     *
1848
     * @param string $generatorType Generator type.
1849
     */
1850 365
    public function setIdGeneratorType($generatorType)
1851
    {
1852 365
        $this->generatorType = $generatorType;
1853 365
    }
1854
1855
    /**
1856
     * Sets the Id generator options.
1857
     *
1858
     * @param array $generatorOptions Generator options.
1859
     */
1860
    public function setIdGeneratorOptions($generatorOptions)
1861
    {
1862
        $this->generatorOptions = $generatorOptions;
1863
    }
1864
1865
    /**
1866
     * @return boolean
1867
     */
1868 625
    public function isInheritanceTypeNone()
1869
    {
1870 625
        return $this->inheritanceType == self::INHERITANCE_TYPE_NONE;
1871
    }
1872
1873
    /**
1874
     * Checks whether the mapped class uses the SINGLE_COLLECTION inheritance mapping strategy.
1875
     *
1876
     * @return boolean
1877
     */
1878 358
    public function isInheritanceTypeSingleCollection()
1879
    {
1880 358
        return $this->inheritanceType == self::INHERITANCE_TYPE_SINGLE_COLLECTION;
1881
    }
1882
1883
    /**
1884
     * Checks whether the mapped class uses the COLLECTION_PER_CLASS inheritance mapping strategy.
1885
     *
1886
     * @return boolean
1887
     */
1888
    public function isInheritanceTypeCollectionPerClass()
1889
    {
1890
        return $this->inheritanceType == self::INHERITANCE_TYPE_COLLECTION_PER_CLASS;
1891
    }
1892
1893
    /**
1894
     * Sets the mapped subclasses of this class.
1895
     *
1896
     * @param string[] $subclasses The names of all mapped subclasses.
1897
     */
1898 2
    public function setSubclasses(array $subclasses)
1899
    {
1900 2
        foreach ($subclasses as $subclass) {
1901 2
            if (strpos($subclass, '\\') === false && strlen($this->namespace)) {
1902 1
                $this->subClasses[] = $this->namespace . '\\' . $subclass;
1903
            } else {
1904 2
                $this->subClasses[] = $subclass;
1905
            }
1906
        }
1907 2
    }
1908
1909
    /**
1910
     * Sets the parent class names.
1911
     * Assumes that the class names in the passed array are in the order:
1912
     * directParent -> directParentParent -> directParentParentParent ... -> root.
1913
     *
1914
     * @param string[] $classNames
1915
     */
1916 899
    public function setParentClasses(array $classNames)
1917
    {
1918 899
        $this->parentClasses = $classNames;
1919
1920 899
        if (count($classNames) > 0) {
1921 107
            $this->rootDocumentName = array_pop($classNames);
1922
        }
1923 899
    }
1924
1925
    /**
1926
     * Checks whether the class will generate a new \MongoId instance for us.
1927
     *
1928
     * @return boolean TRUE if the class uses the AUTO generator, FALSE otherwise.
1929
     */
1930
    public function isIdGeneratorAuto()
1931
    {
1932
        return $this->generatorType == self::GENERATOR_TYPE_AUTO;
1933
    }
1934
1935
    /**
1936
     * Checks whether the class will use a collection to generate incremented identifiers.
1937
     *
1938
     * @return boolean TRUE if the class uses the INCREMENT generator, FALSE otherwise.
1939
     */
1940
    public function isIdGeneratorIncrement()
1941
    {
1942
        return $this->generatorType == self::GENERATOR_TYPE_INCREMENT;
1943
    }
1944
1945
    /**
1946
     * Checks whether the class will generate a uuid id.
1947
     *
1948
     * @return boolean TRUE if the class uses the UUID generator, FALSE otherwise.
1949
     */
1950
    public function isIdGeneratorUuid()
1951
    {
1952
        return $this->generatorType == self::GENERATOR_TYPE_UUID;
1953
    }
1954
1955
    /**
1956
     * Checks whether the class uses no id generator.
1957
     *
1958
     * @return boolean TRUE if the class does not use any id generator, FALSE otherwise.
1959
     */
1960
    public function isIdGeneratorNone()
1961
    {
1962
        return $this->generatorType == self::GENERATOR_TYPE_NONE;
1963
    }
1964
1965
    /**
1966
     * Sets the version field mapping used for versioning. Sets the default
1967
     * value to use depending on the column type.
1968
     *
1969
     * @param array $mapping   The version field mapping array
1970
     *
1971
     * @throws LockException
1972
     */
1973 100
    public function setVersionMapping(array &$mapping)
1974
    {
1975 100
        if ($mapping['type'] !== 'int' && $mapping['type'] !== 'date') {
1976 1
            throw LockException::invalidVersionFieldType($mapping['type']);
1977
        }
1978
1979 99
        $this->isVersioned  = true;
1980 99
        $this->versionField = $mapping['fieldName'];
1981 99
    }
1982
1983
    /**
1984
     * Sets whether this class is to be versioned for optimistic locking.
1985
     *
1986
     * @param boolean $bool
1987
     */
1988 359
    public function setVersioned($bool)
1989
    {
1990 359
        $this->isVersioned = $bool;
1991 359
    }
1992
1993
    /**
1994
     * Sets the name of the field that is to be used for versioning if this class is
1995
     * versioned for optimistic locking.
1996
     *
1997
     * @param string $versionField
1998
     */
1999 359
    public function setVersionField($versionField)
2000
    {
2001 359
        $this->versionField = $versionField;
2002 359
    }
2003
2004
    /**
2005
     * Sets the version field mapping used for versioning. Sets the default
2006
     * value to use depending on the column type.
2007
     *
2008
     * @param array $mapping   The version field mapping array
2009
     *
2010
     * @throws \Doctrine\ODM\MongoDB\LockException
2011
     */
2012 27
    public function setLockMapping(array &$mapping)
2013
    {
2014 27
        if ($mapping['type'] !== 'int') {
2015 1
            throw LockException::invalidLockFieldType($mapping['type']);
2016
        }
2017
2018 26
        $this->isLockable = true;
2019 26
        $this->lockField = $mapping['fieldName'];
2020 26
    }
2021
2022
    /**
2023
     * Sets whether this class is to allow pessimistic locking.
2024
     *
2025
     * @param boolean $bool
2026
     */
2027
    public function setLockable($bool)
2028
    {
2029
        $this->isLockable = $bool;
2030
    }
2031
2032
    /**
2033
     * Sets the name of the field that is to be used for storing whether a document
2034
     * is currently locked or not.
2035
     *
2036
     * @param string $lockField
2037
     */
2038
    public function setLockField($lockField)
2039
    {
2040
        $this->lockField = $lockField;
2041
    }
2042
2043
    /**
2044
     * {@inheritDoc}
2045
     */
2046
    public function getFieldNames()
2047
    {
2048
        return array_keys($this->fieldMappings);
2049
    }
2050
2051
    /**
2052
     * {@inheritDoc}
2053
     */
2054
    public function getAssociationNames()
2055
    {
2056
        return array_keys($this->associationMappings);
2057
    }
2058
2059
    /**
2060
     * {@inheritDoc}
2061
     */
2062 23
    public function getTypeOfField($fieldName)
2063
    {
2064 23
        return isset($this->fieldMappings[$fieldName]) ?
2065 23
            $this->fieldMappings[$fieldName]['type'] : null;
2066
    }
2067
2068
    /**
2069
     * {@inheritDoc}
2070
     */
2071 6
    public function getAssociationTargetClass($assocName)
2072
    {
2073 6
        if ( ! isset($this->associationMappings[$assocName])) {
2074 3
            throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association.");
2075
        }
2076
2077 3
        return $this->associationMappings[$assocName]['targetDocument'];
2078
    }
2079
2080
    /**
2081
     * Retrieve the collectionClass associated with an association
2082
     *
2083
     * @param string $assocName
2084
     */
2085 2
    public function getAssociationCollectionClass($assocName)
2086
    {
2087 2
        if ( ! isset($this->associationMappings[$assocName])) {
2088
            throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association.");
2089
        }
2090
2091 2
        if ( ! array_key_exists('collectionClass', $this->associationMappings[$assocName])) {
2092
            throw new InvalidArgumentException("collectionClass can only be applied to 'embedMany' and 'referenceMany' associations.");
2093
        }
2094
2095 2
        return $this->associationMappings[$assocName]['collectionClass'];
2096
    }
2097
2098
    /**
2099
     * {@inheritDoc}
2100
     */
2101
    public function isAssociationInverseSide($fieldName)
2102
    {
2103
        throw new \BadMethodCallException(__METHOD__ . '() is not implemented yet.');
2104
    }
2105
2106
    /**
2107
     * {@inheritDoc}
2108
     */
2109
    public function getAssociationMappedByTargetField($fieldName)
2110
    {
2111
        throw new \BadMethodCallException(__METHOD__ . '() is not implemented yet.');
2112
    }
2113
}
2114