Completed
Push — master ( 73492b...2db3cf )
by Jeremy
11:56
created

ClassMetadataInfo::setShardKey()   C

Complexity

Conditions 13
Paths 7

Size

Total Lines 42
Code Lines 25

Duplication

Lines 14
Ratio 33.33 %

Code Coverage

Tests 24
CRAP Score 13.0108

Importance

Changes 0
Metric Value
dl 14
loc 42
ccs 24
cts 25
cp 0.96
rs 5.1234
c 0
b 0
f 0
cc 13
eloc 25
nc 7
nop 2
crap 13.0108

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 983
    public function __construct($documentName)
463
    {
464 983
        $this->name = $documentName;
465 983
        $this->rootDocumentName = $documentName;
466 983
    }
467
468
    /**
469
     * {@inheritDoc}
470
     */
471 911
    public function getReflectionClass()
472
    {
473 911
        if ( ! $this->reflClass) {
474 2
            $this->reflClass = new \ReflectionClass($this->name);
475
        }
476
477 911
        return $this->reflClass;
478
    }
479
480
    /**
481
     * {@inheritDoc}
482
     */
483 330
    public function isIdentifier($fieldName)
484
    {
485 330
        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 368
    public function setIdentifier($identifier)
495
    {
496 368
        $this->identifier = $identifier;
497 368
    }
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 40
    public function getIdentifier()
506
    {
507 40
        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 98
    public function getIdentifierFieldNames()
517
    {
518 98
        return array($this->identifier);
519
    }
520
521
    /**
522
     * {@inheritDoc}
523
     */
524 561
    public function hasField($fieldName)
525
    {
526 561
        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 384
    public function setInheritanceType($type)
535
    {
536 384
        $this->inheritanceType = $type;
537 384
    }
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 911
    public function isInheritedField($fieldName)
547
    {
548 911
        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 316
    public function setCustomRepositoryClass($repositoryClassName)
557
    {
558 316
        if ($this->isEmbeddedDocument || $this->isQueryResultDocument) {
559
            return;
560
        }
561
562 316 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 4
            $repositoryClassName = $this->namespace . '\\' . $repositoryClassName;
564
        }
565
566 316
        $this->customRepositoryClassName = $repositoryClassName;
567 316
    }
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 667
    public function invokeLifecycleCallbacks($event, $document, array $arguments = null)
580
    {
581 667
        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 666
        if (empty($this->lifecycleCallbacks[$event])) {
586 652
            return;
587
        }
588
589 196
        foreach ($this->lifecycleCallbacks[$event] as $callback) {
590 196
            if ($arguments !== null) {
591 195
                call_user_func_array(array($document, $callback), $arguments);
592
            } else {
593 2
                $document->$callback();
594
            }
595
        }
596 196
    }
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 295
    public function addLifecycleCallback($callback, $event)
630
    {
631 295
        if (isset($this->lifecycleCallbacks[$event]) && in_array($callback, $this->lifecycleCallbacks[$event])) {
632 1
            return;
633
        }
634
635 295
        $this->lifecycleCallbacks[$event][] = $callback;
636 295
    }
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 367
    public function setLifecycleCallbacks(array $callbacks)
646
    {
647 367
        $this->lifecycleCallbacks = $callbacks;
648 367
    }
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 367
    public function setAlsoLoadMethods(array $methods)
672
    {
673 367
        $this->alsoLoadMethods = $methods;
674 367
    }
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 397
    public function setDiscriminatorField($discriminatorField)
689
    {
690 397
        if ($discriminatorField === null) {
691 324
            $this->discriminatorField = null;
692
693 324
            return;
694
        }
695
696
        // Handle array argument with name/fieldName keys for BC
697 130
        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 130
        foreach ($this->fieldMappings as $fieldMapping) {
706 4
            if ($discriminatorField == $fieldMapping['name']) {
707 1
                throw MappingException::discriminatorFieldConflict($this->name, $discriminatorField);
708
            }
709
        }
710
711 129
        $this->discriminatorField = $discriminatorField;
712 129
    }
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 390
    public function setDiscriminatorMap(array $map)
723
    {
724 390
        foreach ($map as $value => $className) {
725 125
            if (strpos($className, '\\') === false && strlen($this->namespace)) {
726 91
                $className = $this->namespace . '\\' . $className;
727
            }
728 125
            $this->discriminatorMap[$value] = $className;
729 125
            if ($this->name == $className) {
730 117
                $this->discriminatorValue = $value;
731
            } else {
732 120
                if ( ! class_exists($className)) {
733
                    throw MappingException::invalidClassInDiscriminatorMap($className, $this->name);
734
                }
735 120
                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 106
                    $this->subClasses[] = $className;
737
                }
738
            }
739
        }
740 390
    }
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 374
    public function setDefaultDiscriminatorValue($defaultDiscriminatorValue)
751
    {
752 374
        if ($defaultDiscriminatorValue === null) {
753 367
            $this->defaultDiscriminatorValue = null;
754
755 367
            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 3
    public function setDiscriminatorValue($value)
773
    {
774 3
        $this->discriminatorMap[$value] = $this->name;
775 3
        $this->discriminatorValue = $value;
776 3
    }
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 232
    public function addIndex($keys, array $options = array())
795
    {
796 232
        $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 232
                if ($value == 1 || $value == -1) {
799 63
                    return (int) $value;
800
                }
801 224
                if (is_string($value)) {
802 224
                    $lower = strtolower($value);
803 224
                    if ($lower === 'asc') {
804 217
                        return 1;
805 11
                    } elseif ($lower === 'desc') {
806 4
                        return -1;
807
                    }
808
                }
809 7
                return $value;
810 232
            }, $keys),
811 232
            'options' => $options
812
        );
813 232
    }
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 902
    public function setRequireIndexes($requireIndexes)
823
    {
824 902
        $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 902
    }
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 1
                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 606
    public function isSharded()
912
    {
913 606
        return $this->shardKey ? true : false;
914
    }
915
916
    /**
917
     * Sets the write concern used by this class.
918
     *
919
     * @param string $writeConcern
920
     */
921 381
    public function setWriteConcern($writeConcern)
922
    {
923 381
        $this->writeConcern = $writeConcern;
924 381
    }
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 611
    public function hasWriteConcern()
940
    {
941 611
        return $this->writeConcern !== null;
942
    }
943
944
    /**
945
     * Sets the change tracking policy used by this class.
946
     *
947
     * @param integer $policy
948
     */
949 372
    public function setChangeTrackingPolicy($policy)
950
    {
951 372
        $this->changeTrackingPolicy = $policy;
952 372
    }
953
954
    /**
955
     * Whether the change tracking policy of this class is "deferred explicit".
956
     *
957
     * @return boolean
958
     */
959 73
    public function isChangeTrackingDeferredExplicit()
960
    {
961 73
        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 631
    public function isChangeTrackingDeferredImplicit()
970
    {
971 631
        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 350
    public function isChangeTrackingNotify()
980
    {
981 350
        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 98
    public function getReflectionProperties()
990
    {
991 98
        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 917
    public function getName()
1010
    {
1011 917
        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 839
    public function getDatabase()
1030
    {
1031 839
        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 104
    public function setDatabase($db)
1040
    {
1041 104
        $this->db = $db;
1042 104
    }
1043
1044
    /**
1045
     * Get the collection this Document is mapped to.
1046
     *
1047
     * @return string $collection The collection name.
1048
     */
1049 844
    public function getCollection()
1050
    {
1051 844
        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 947
    public function setCollection($name)
1062
    {
1063 947
        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 947
            $this->collection = $name;
1073
        }
1074 947
    }
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 785
    public function isFile()
1152
    {
1153 785
        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 367
    public function getFile()
1162
    {
1163 367
        return $this->file;
1164
    }
1165
1166
    /**
1167
     * Set the field name that stores the grid file.
1168
     *
1169
     * @param string $file
1170
     */
1171 368
    public function setFile($file)
1172
    {
1173 368
        $this->file = $file;
1174 368
    }
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 961
    public function mapField(array $mapping)
1206
    {
1207 961
        if ( ! isset($mapping['fieldName']) && isset($mapping['name'])) {
1208 10
            $mapping['fieldName'] = $mapping['name'];
1209
        }
1210 961
        if ( ! isset($mapping['fieldName'])) {
1211
            throw MappingException::missingFieldName($this->name);
1212
        }
1213 961
        if ( ! isset($mapping['name'])) {
1214 951
            $mapping['name'] = $mapping['fieldName'];
1215
        }
1216 961
        if ($this->identifier === $mapping['name'] && empty($mapping['id'])) {
1217 1
            throw MappingException::mustNotChangeIdentifierFieldsType($this->name, $mapping['name']);
1218
        }
1219 960
        if (isset($this->fieldMappings[$mapping['fieldName']])) {
1220
            //throw MappingException::duplicateFieldMapping($this->name, $mapping['fieldName']);
1221
        }
1222 960
        if ($this->discriminatorField !== null && $this->discriminatorField == $mapping['name']) {
1223 1
            throw MappingException::discriminatorFieldConflict($this->name, $this->discriminatorField);
1224
        }
1225 959 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 614
            $mapping['targetDocument'] = $this->namespace . '\\' . $mapping['targetDocument'];
1227
        }
1228 959
        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 959
        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 958
        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 75
                    $mapping['discriminatorMap'][$key] = $this->namespace . '\\' . $class;
1245
                }
1246
            }
1247
        }
1248
1249 958
        if (isset($mapping['cascade']) && isset($mapping['embedded'])) {
1250 1
            throw MappingException::cascadeOnEmbeddedNotAllowed($this->name, $mapping['fieldName']);
1251
        }
1252
1253 957
        $cascades = isset($mapping['cascade']) ? array_map('strtolower', (array) $mapping['cascade']) : array();
1254
1255 957
        if (in_array('all', $cascades) || isset($mapping['embedded'])) {
1256 642
            $cascades = array('remove', 'persist', 'refresh', 'merge', 'detach');
1257
        }
1258
1259 957
        if (isset($mapping['embedded'])) {
1260 599
            unset($mapping['cascade']);
1261 952
        } elseif (isset($mapping['cascade'])) {
1262 406
            $mapping['cascade'] = $cascades;
1263
        }
1264
1265 957
        $mapping['isCascadeRemove'] = in_array('remove', $cascades);
1266 957
        $mapping['isCascadePersist'] = in_array('persist', $cascades);
1267 957
        $mapping['isCascadeRefresh'] = in_array('refresh', $cascades);
1268 957
        $mapping['isCascadeMerge'] = in_array('merge', $cascades);
1269 957
        $mapping['isCascadeDetach'] = in_array('detach', $cascades);
1270
1271 957
        if (isset($mapping['type']) && $mapping['type'] === 'file') {
1272 63
            $mapping['file'] = true;
1273
        }
1274 957
        if (isset($mapping['type']) && $mapping['type'] === 'increment') {
1275 1
            $mapping['strategy'] = self::STORAGE_STRATEGY_INCREMENT;
1276
        }
1277 957 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 957 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 957
        if (isset($mapping['id']) && $mapping['id'] === true) {
1285 929
            $mapping['name'] = '_id';
1286 929
            $this->identifier = $mapping['fieldName'];
1287 929 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 910
                $this->generatorType = constant(ClassMetadata::class . '::GENERATOR_TYPE_' . strtoupper($mapping['strategy']));
1289
            }
1290 929
            $this->generatorOptions = isset($mapping['options']) ? $mapping['options'] : array();
1291 929
            switch ($this->generatorType) {
1292 929
                case self::GENERATOR_TYPE_AUTO:
1293 855
                    $mapping['type'] = 'id';
1294 855
                    break;
1295
                default:
1296 153
                    if ( ! empty($this->generatorOptions['type'])) {
1297 52
                        $mapping['type'] = $this->generatorOptions['type'];
1298 101
                    } elseif (empty($mapping['type'])) {
1299 86
                        $mapping['type'] = $this->generatorType === self::GENERATOR_TYPE_INCREMENT ? 'int_id' : 'custom_id';
1300
                    }
1301
            }
1302 929
            unset($this->generatorOptions['type']);
1303
        }
1304
1305 957
        if ( ! isset($mapping['nullable'])) {
1306 53
            $mapping['nullable'] = false;
1307
        }
1308
1309
        // Synchronize the "simple" and "storeAs" mapping information for backwards compatibility
1310 957
        if (isset($mapping['simple']) && ($mapping['simple'] === true || $mapping['simple'] === 'true')) {
1311 291
            $mapping['storeAs'] = ClassMetadataInfo::REFERENCE_STORE_AS_ID;
1312
        }
1313
        // Provide the correct value for the "simple" field for backwards compatibility
1314 957
        if (isset($mapping['storeAs'])) {
1315 581
            $mapping['simple'] = $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID;
1316
        }
1317
1318 957
        if (isset($mapping['reference'])
1319 594
            && isset($mapping['storeAs'])
1320 581
            && $mapping['storeAs'] === ClassMetadataInfo::REFERENCE_STORE_AS_ID
1321 346
            && ! isset($mapping['targetDocument'])
1322
        ) {
1323 3
            throw MappingException::simpleReferenceRequiresTargetDocument($this->name, $mapping['fieldName']);
1324
        }
1325
1326 954
        if (isset($mapping['reference']) && empty($mapping['targetDocument']) && empty($mapping['discriminatorMap']) &&
1327 112
                (isset($mapping['mappedBy']) || isset($mapping['inversedBy']))) {
1328 4
            throw MappingException::owningAndInverseReferencesRequireTargetDocument($this->name, $mapping['fieldName']);
1329
        }
1330
1331 950
        if ($this->isEmbeddedDocument && $mapping['type'] === 'many' && CollectionHelper::isAtomic($mapping['strategy'])) {
1332 1
            throw MappingException::atomicCollectionStrategyNotAllowed($mapping['strategy'], $this->name, $mapping['fieldName']);
1333
        }
1334
1335 949 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...
1336 514
            $mapping['association'] = self::REFERENCE_ONE;
1337
        }
1338 949 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...
1339 458
            $mapping['association'] = self::REFERENCE_MANY;
1340
        }
1341 949 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...
1342 460
            $mapping['association'] = self::EMBED_ONE;
1343
        }
1344 949 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...
1345 503
            $mapping['association'] = self::EMBED_MANY;
1346
        }
1347
1348 949
        if (isset($mapping['association']) && ! isset($mapping['targetDocument']) && ! isset($mapping['discriminatorField'])) {
1349 133
            $mapping['discriminatorField'] = self::DEFAULT_DISCRIMINATOR_FIELD;
1350
        }
1351
1352
        /*
1353
        if (isset($mapping['type']) && ($mapping['type'] === 'one' || $mapping['type'] === 'many')) {
1354
            $mapping['type'] = $mapping['type'] === 'one' ? self::ONE : self::MANY;
1355
        }
1356
        */
1357 949
        if (isset($mapping['version'])) {
1358 100
            $mapping['notSaved'] = true;
1359 100
            $this->setVersionMapping($mapping);
1360
        }
1361 949
        if (isset($mapping['lock'])) {
1362 27
            $mapping['notSaved'] = true;
1363 27
            $this->setLockMapping($mapping);
1364
        }
1365 949
        $mapping['isOwningSide'] = true;
1366 949
        $mapping['isInverseSide'] = false;
1367 949
        if (isset($mapping['reference'])) {
1368 586 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...
1369 92
                $mapping['isOwningSide'] = true;
1370 92
                $mapping['isInverseSide'] = false;
1371
            }
1372 586 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...
1373 293
                $mapping['isInverseSide'] = true;
1374 293
                $mapping['isOwningSide'] = false;
1375
            }
1376 586 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...
1377 67
                $mapping['isInverseSide'] = true;
1378 67
                $mapping['isOwningSide'] = false;
1379
            }
1380 586
            if (!isset($mapping['orphanRemoval'])) {
1381 561
                $mapping['orphanRemoval'] = false;
1382
            }
1383
        }
1384
1385 949
        if (!empty($mapping['prime']) && ($mapping['association'] !== self::REFERENCE_MANY || !$mapping['isInverseSide'])) {
1386
            throw MappingException::referencePrimersOnlySupportedForInverseReferenceMany($this->name, $mapping['fieldName']);
1387
        }
1388
1389 949
        $this->applyStorageStrategy($mapping);
1390
1391 948
        $this->fieldMappings[$mapping['fieldName']] = $mapping;
1392 948
        if (isset($mapping['association'])) {
1393 739
            $this->associationMappings[$mapping['fieldName']] = $mapping;
1394
        }
1395
1396 948
        return $mapping;
1397
    }
1398
1399
    /**
1400
     * Validates the storage strategy of a mapping for consistency
1401
     * @param array $mapping
1402
     * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException
1403
     */
1404 949
    private function applyStorageStrategy(array &$mapping)
1405
    {
1406 949
        if (! isset($mapping['type']) || isset($mapping['id'])) {
1407 931
            return;
1408
        }
1409
1410
        switch (true) {
1411 911
            case $mapping['type'] == 'int':
1412 910
            case $mapping['type'] == 'float':
1413 910
            case $mapping['type'] == 'increment':
1414 332
                $defaultStrategy = self::STORAGE_STRATEGY_SET;
1415 332
                $allowedStrategies = [self::STORAGE_STRATEGY_SET, self::STORAGE_STRATEGY_INCREMENT];
1416 332
                break;
1417
1418 909
            case $mapping['type'] == 'many':
1419 616
                $defaultStrategy = CollectionHelper::DEFAULT_STRATEGY;
1420
                $allowedStrategies = [
1421 616
                    self::STORAGE_STRATEGY_PUSH_ALL,
1422 616
                    self::STORAGE_STRATEGY_ADD_TO_SET,
1423 616
                    self::STORAGE_STRATEGY_SET,
1424 616
                    self::STORAGE_STRATEGY_SET_ARRAY,
1425 616
                    self::STORAGE_STRATEGY_ATOMIC_SET,
1426 616
                    self::STORAGE_STRATEGY_ATOMIC_SET_ARRAY,
1427
                ];
1428 616
                break;
1429
1430
            default:
1431 897
                $defaultStrategy = self::STORAGE_STRATEGY_SET;
1432 897
                $allowedStrategies = [self::STORAGE_STRATEGY_SET];
1433
        }
1434
1435 911
        if (! isset($mapping['strategy'])) {
1436 900
            $mapping['strategy'] = $defaultStrategy;
1437
        }
1438
1439 911
        if (! in_array($mapping['strategy'], $allowedStrategies)) {
1440
            throw MappingException::invalidStorageStrategy($this->name, $mapping['fieldName'], $mapping['type'], $mapping['strategy']);
1441
        }
1442
1443 911
        if (isset($mapping['reference']) && $mapping['type'] === 'many' && $mapping['isOwningSide']
1444 451
            && ! empty($mapping['sort']) && ! CollectionHelper::usesSet($mapping['strategy'])) {
1445 1
            throw MappingException::referenceManySortMustNotBeUsedWithNonSetCollectionStrategy($this->name, $mapping['fieldName'], $mapping['strategy']);
1446
        }
1447 910
    }
1448
1449
    /**
1450
     * Map a MongoGridFSFile.
1451
     *
1452
     * @param array $mapping The mapping information.
1453
     */
1454
    public function mapFile(array $mapping)
1455
    {
1456
        $mapping['file'] = true;
1457
        $mapping['type'] = 'file';
1458
        $this->mapField($mapping);
1459
    }
1460
1461
    /**
1462
     * Map a single embedded document.
1463
     *
1464
     * @param array $mapping The mapping information.
1465
     */
1466 6
    public function mapOneEmbedded(array $mapping)
1467
    {
1468 6
        $mapping['embedded'] = true;
1469 6
        $mapping['type'] = 'one';
1470 6
        $this->mapField($mapping);
1471 5
    }
1472
1473
    /**
1474
     * Map a collection of embedded documents.
1475
     *
1476
     * @param array $mapping The mapping information.
1477
     */
1478 5
    public function mapManyEmbedded(array $mapping)
1479
    {
1480 5
        $mapping['embedded'] = true;
1481 5
        $mapping['type'] = 'many';
1482 5
        $this->mapField($mapping);
1483 5
    }
1484
1485
    /**
1486
     * Map a single document reference.
1487
     *
1488
     * @param array $mapping The mapping information.
1489
     */
1490 8
    public function mapOneReference(array $mapping)
1491
    {
1492 8
        $mapping['reference'] = true;
1493 8
        $mapping['type'] = 'one';
1494 8
        $this->mapField($mapping);
1495 8
    }
1496
1497
    /**
1498
     * Map a collection of document references.
1499
     *
1500
     * @param array $mapping The mapping information.
1501
     */
1502 8
    public function mapManyReference(array $mapping)
1503
    {
1504 8
        $mapping['reference'] = true;
1505 8
        $mapping['type'] = 'many';
1506 8
        $this->mapField($mapping);
1507 8
    }
1508
1509
    /**
1510
     * INTERNAL:
1511
     * Adds a field mapping without completing/validating it.
1512
     * This is mainly used to add inherited field mappings to derived classes.
1513
     *
1514
     * @param array $fieldMapping
1515
     */
1516 129
    public function addInheritedFieldMapping(array $fieldMapping)
1517
    {
1518 129
        $this->fieldMappings[$fieldMapping['fieldName']] = $fieldMapping;
1519
1520 129
        if (isset($fieldMapping['association'])) {
1521 77
            $this->associationMappings[$fieldMapping['fieldName']] = $fieldMapping;
1522
        }
1523 129
    }
1524
1525
    /**
1526
     * INTERNAL:
1527
     * Adds an association mapping without completing/validating it.
1528
     * This is mainly used to add inherited association mappings to derived classes.
1529
     *
1530
     * @param array $mapping
1531
     *
1532
     * @return void
1533
     *
1534
     * @throws MappingException
1535
     */
1536 78
    public function addInheritedAssociationMapping(array $mapping/*, $owningClassName = null*/)
1537
    {
1538 78
        $this->associationMappings[$mapping['fieldName']] = $mapping;
1539 78
    }
1540
1541
    /**
1542
     * Checks whether the class has a mapped association with the given field name.
1543
     *
1544
     * @param string $fieldName
1545
     * @return boolean
1546
     */
1547 14
    public function hasReference($fieldName)
1548
    {
1549 14
        return isset($this->fieldMappings[$fieldName]['reference']);
1550
    }
1551
1552
    /**
1553
     * Checks whether the class has a mapped embed with the given field name.
1554
     *
1555
     * @param string $fieldName
1556
     * @return boolean
1557
     */
1558 5
    public function hasEmbed($fieldName)
1559
    {
1560 5
        return isset($this->fieldMappings[$fieldName]['embedded']);
1561
    }
1562
1563
    /**
1564
     * {@inheritDoc}
1565
     *
1566
     * Checks whether the class has a mapped association (embed or reference) with the given field name.
1567
     */
1568 7
    public function hasAssociation($fieldName)
1569
    {
1570 7
        return $this->hasReference($fieldName) || $this->hasEmbed($fieldName);
1571
    }
1572
1573
    /**
1574
     * {@inheritDoc}
1575
     *
1576
     * Checks whether the class has a mapped reference or embed for the specified field and
1577
     * is a single valued association.
1578
     */
1579
    public function isSingleValuedAssociation($fieldName)
1580
    {
1581
        return $this->isSingleValuedReference($fieldName) || $this->isSingleValuedEmbed($fieldName);
1582
    }
1583
1584
    /**
1585
     * {@inheritDoc}
1586
     *
1587
     * Checks whether the class has a mapped reference or embed for the specified field and
1588
     * is a collection valued association.
1589
     */
1590
    public function isCollectionValuedAssociation($fieldName)
1591
    {
1592
        return $this->isCollectionValuedReference($fieldName) || $this->isCollectionValuedEmbed($fieldName);
1593
    }
1594
1595
    /**
1596
     * Checks whether the class has a mapped association for the specified field
1597
     * and if yes, checks whether it is a single-valued association (to-one).
1598
     *
1599
     * @param string $fieldName
1600
     * @return boolean TRUE if the association exists and is single-valued, FALSE otherwise.
1601
     */
1602
    public function isSingleValuedReference($fieldName)
1603
    {
1604
        return isset($this->fieldMappings[$fieldName]['association']) &&
1605
            $this->fieldMappings[$fieldName]['association'] === self::REFERENCE_ONE;
1606
    }
1607
1608
    /**
1609
     * Checks whether the class has a mapped association for the specified field
1610
     * and if yes, checks whether it is a collection-valued association (to-many).
1611
     *
1612
     * @param string $fieldName
1613
     * @return boolean TRUE if the association exists and is collection-valued, FALSE otherwise.
1614
     */
1615
    public function isCollectionValuedReference($fieldName)
1616
    {
1617
        return isset($this->fieldMappings[$fieldName]['association']) &&
1618
            $this->fieldMappings[$fieldName]['association'] === self::REFERENCE_MANY;
1619
    }
1620
1621
    /**
1622
     * Checks whether the class has a mapped embedded document for the specified field
1623
     * and if yes, checks whether it is a single-valued association (to-one).
1624
     *
1625
     * @param string $fieldName
1626
     * @return boolean TRUE if the association exists and is single-valued, FALSE otherwise.
1627
     */
1628
    public function isSingleValuedEmbed($fieldName)
1629
    {
1630
        return isset($this->fieldMappings[$fieldName]['association']) &&
1631
            $this->fieldMappings[$fieldName]['association'] === self::EMBED_ONE;
1632
    }
1633
1634
    /**
1635
     * Checks whether the class has a mapped embedded document for the specified field
1636
     * and if yes, checks whether it is a collection-valued association (to-many).
1637
     *
1638
     * @param string $fieldName
1639
     * @return boolean TRUE if the association exists and is collection-valued, FALSE otherwise.
1640
     */
1641
    public function isCollectionValuedEmbed($fieldName)
1642
    {
1643
        return isset($this->fieldMappings[$fieldName]['association']) &&
1644
            $this->fieldMappings[$fieldName]['association'] === self::EMBED_MANY;
1645
    }
1646
1647
    /**
1648
     * Sets the ID generator used to generate IDs for instances of this class.
1649
     *
1650
     * @param \Doctrine\ODM\MongoDB\Id\AbstractIdGenerator $generator
1651
     */
1652 850
    public function setIdGenerator($generator)
1653
    {
1654 850
        $this->idGenerator = $generator;
1655 850
    }
1656
1657
    /**
1658
     * Casts the identifier to its portable PHP type.
1659
     *
1660
     * @param mixed $id
1661
     * @return mixed $id
1662
     */
1663 653
    public function getPHPIdentifierValue($id)
1664
    {
1665 653
        $idType = $this->fieldMappings[$this->identifier]['type'];
1666 653
        return Type::getType($idType)->convertToPHPValue($id);
1667
    }
1668
1669
    /**
1670
     * Casts the identifier to its database type.
1671
     *
1672
     * @param mixed $id
1673
     * @return mixed $id
1674
     */
1675 721
    public function getDatabaseIdentifierValue($id)
1676
    {
1677 721
        $idType = $this->fieldMappings[$this->identifier]['type'];
1678 721
        return Type::getType($idType)->convertToDatabaseValue($id);
1679
    }
1680
1681
    /**
1682
     * Sets the document identifier of a document.
1683
     *
1684
     * The value will be converted to a PHP type before being set.
1685
     *
1686
     * @param object $document
1687
     * @param mixed $id
1688
     */
1689 582
    public function setIdentifierValue($document, $id)
1690
    {
1691 582
        $id = $this->getPHPIdentifierValue($id);
1692 582
        $this->reflFields[$this->identifier]->setValue($document, $id);
1693 582
    }
1694
1695
    /**
1696
     * Gets the document identifier as a PHP type.
1697
     *
1698
     * @param object $document
1699
     * @return mixed $id
1700
     */
1701 672
    public function getIdentifierValue($document)
1702
    {
1703 672
        return $this->reflFields[$this->identifier]->getValue($document);
1704
    }
1705
1706
    /**
1707
     * {@inheritDoc}
1708
     *
1709
     * Since MongoDB only allows exactly one identifier field this is a proxy
1710
     * to {@see getIdentifierValue()} and returns an array with the identifier
1711
     * field as a key.
1712
     */
1713
    public function getIdentifierValues($object)
1714
    {
1715
        return array($this->identifier => $this->getIdentifierValue($object));
1716
    }
1717
1718
    /**
1719
     * Get the document identifier object as a database type.
1720
     *
1721
     * @param object $document
1722
     *
1723
     * @return \MongoId $id The MongoID object.
1724
     */
1725 36
    public function getIdentifierObject($document)
1726
    {
1727 36
        return $this->getDatabaseIdentifierValue($this->getIdentifierValue($document));
1728
    }
1729
1730
    /**
1731
     * Sets the specified field to the specified value on the given document.
1732
     *
1733
     * @param object $document
1734
     * @param string $field
1735
     * @param mixed $value
1736
     */
1737 11
    public function setFieldValue($document, $field, $value)
1738
    {
1739 11
        if ($document instanceof Proxy && ! $document->__isInitialized()) {
1740
            //property changes to an uninitialized proxy will not be tracked or persisted,
1741
            //so the proxy needs to be loaded first.
1742 1
            $document->__load();
1743
        }
1744
1745 11
        $this->reflFields[$field]->setValue($document, $value);
1746 11
    }
1747
1748
    /**
1749
     * Gets the specified field's value off the given document.
1750
     *
1751
     * @param object $document
1752
     * @param string $field
1753
     *
1754
     * @return mixed
1755
     */
1756 31
    public function getFieldValue($document, $field)
1757
    {
1758 31
        if ($document instanceof Proxy && $field !== $this->identifier && ! $document->__isInitialized()) {
1759 1
            $document->__load();
1760
        }
1761
1762 31
        return $this->reflFields[$field]->getValue($document);
1763
    }
1764
1765
    /**
1766
     * Gets the mapping of a field.
1767
     *
1768
     * @param string $fieldName  The field name.
1769
     *
1770
     * @return array  The field mapping.
1771
     *
1772
     * @throws MappingException if the $fieldName is not found in the fieldMappings array
1773
     */
1774 102
    public function getFieldMapping($fieldName)
1775
    {
1776 102
        if ( ! isset($this->fieldMappings[$fieldName])) {
1777 6
            throw MappingException::mappingNotFound($this->name, $fieldName);
1778
        }
1779 100
        return $this->fieldMappings[$fieldName];
1780
    }
1781
1782
    /**
1783
     * Gets mappings of fields holding embedded document(s).
1784
     *
1785
     * @return array of field mappings
1786
     */
1787 623
    public function getEmbeddedFieldsMappings()
1788
    {
1789 623
        return array_filter(
1790 623
            $this->associationMappings,
1791
            function($assoc) { return ! empty($assoc['embedded']); }
1792
        );
1793
    }
1794
1795
    /**
1796
     * Gets the field mapping by its DB name.
1797
     * E.g. it returns identifier's mapping when called with _id.
1798
     *
1799
     * @param string $dbFieldName
1800
     *
1801
     * @return array
1802
     * @throws MappingException
1803
     */
1804 9
    public function getFieldMappingByDbFieldName($dbFieldName)
1805
    {
1806 9
        foreach ($this->fieldMappings as $mapping) {
1807 9
            if ($mapping['name'] == $dbFieldName) {
1808 9
                return $mapping;
1809
            }
1810
        }
1811
1812
        throw MappingException::mappingNotFoundByDbName($this->name, $dbFieldName);
1813
    }
1814
1815
    /**
1816
     * Check if the field is not null.
1817
     *
1818
     * @param string $fieldName  The field name
1819
     *
1820
     * @return boolean  TRUE if the field is not null, FALSE otherwise.
1821
     */
1822 1
    public function isNullable($fieldName)
1823
    {
1824 1
        $mapping = $this->getFieldMapping($fieldName);
1825 1
        if ($mapping !== false) {
1826 1
            return isset($mapping['nullable']) && $mapping['nullable'] == true;
1827
        }
1828
        return false;
1829
    }
1830
1831
    /**
1832
     * Checks whether the document has a discriminator field and value configured.
1833
     *
1834
     * @return boolean
1835
     */
1836 531
    public function hasDiscriminator()
1837
    {
1838 531
        return isset($this->discriminatorField, $this->discriminatorValue);
1839
    }
1840
1841
    /**
1842
     * Sets the type of Id generator to use for the mapped class.
1843
     *
1844
     * @param string $generatorType Generator type.
1845
     */
1846 373
    public function setIdGeneratorType($generatorType)
1847
    {
1848 373
        $this->generatorType = $generatorType;
1849 373
    }
1850
1851
    /**
1852
     * Sets the Id generator options.
1853
     *
1854
     * @param array $generatorOptions Generator options.
1855
     */
1856
    public function setIdGeneratorOptions($generatorOptions)
1857
    {
1858
        $this->generatorOptions = $generatorOptions;
1859
    }
1860
1861
    /**
1862
     * @return boolean
1863
     */
1864 629
    public function isInheritanceTypeNone()
1865
    {
1866 629
        return $this->inheritanceType == self::INHERITANCE_TYPE_NONE;
1867
    }
1868
1869
    /**
1870
     * Checks whether the mapped class uses the SINGLE_COLLECTION inheritance mapping strategy.
1871
     *
1872
     * @return boolean
1873
     */
1874 366
    public function isInheritanceTypeSingleCollection()
1875
    {
1876 366
        return $this->inheritanceType == self::INHERITANCE_TYPE_SINGLE_COLLECTION;
1877
    }
1878
1879
    /**
1880
     * Checks whether the mapped class uses the COLLECTION_PER_CLASS inheritance mapping strategy.
1881
     *
1882
     * @return boolean
1883
     */
1884
    public function isInheritanceTypeCollectionPerClass()
1885
    {
1886
        return $this->inheritanceType == self::INHERITANCE_TYPE_COLLECTION_PER_CLASS;
1887
    }
1888
1889
    /**
1890
     * Sets the mapped subclasses of this class.
1891
     *
1892
     * @param string[] $subclasses The names of all mapped subclasses.
1893
     */
1894 2
    public function setSubclasses(array $subclasses)
1895
    {
1896 2
        foreach ($subclasses as $subclass) {
1897 2
            if (strpos($subclass, '\\') === false && strlen($this->namespace)) {
1898 1
                $this->subClasses[] = $this->namespace . '\\' . $subclass;
1899
            } else {
1900 1
                $this->subClasses[] = $subclass;
1901
            }
1902
        }
1903 2
    }
1904
1905
    /**
1906
     * Sets the parent class names.
1907
     * Assumes that the class names in the passed array are in the order:
1908
     * directParent -> directParentParent -> directParentParentParent ... -> root.
1909
     *
1910
     * @param string[] $classNames
1911
     */
1912 908
    public function setParentClasses(array $classNames)
1913
    {
1914 908
        $this->parentClasses = $classNames;
1915
1916 908
        if (count($classNames) > 0) {
1917 113
            $this->rootDocumentName = array_pop($classNames);
1918
        }
1919 908
    }
1920
1921
    /**
1922
     * Checks whether the class will generate a new \MongoId instance for us.
1923
     *
1924
     * @return boolean TRUE if the class uses the AUTO generator, FALSE otherwise.
1925
     */
1926
    public function isIdGeneratorAuto()
1927
    {
1928
        return $this->generatorType == self::GENERATOR_TYPE_AUTO;
1929
    }
1930
1931
    /**
1932
     * Checks whether the class will use a collection to generate incremented identifiers.
1933
     *
1934
     * @return boolean TRUE if the class uses the INCREMENT generator, FALSE otherwise.
1935
     */
1936
    public function isIdGeneratorIncrement()
1937
    {
1938
        return $this->generatorType == self::GENERATOR_TYPE_INCREMENT;
1939
    }
1940
1941
    /**
1942
     * Checks whether the class will generate a uuid id.
1943
     *
1944
     * @return boolean TRUE if the class uses the UUID generator, FALSE otherwise.
1945
     */
1946
    public function isIdGeneratorUuid()
1947
    {
1948
        return $this->generatorType == self::GENERATOR_TYPE_UUID;
1949
    }
1950
1951
    /**
1952
     * Checks whether the class uses no id generator.
1953
     *
1954
     * @return boolean TRUE if the class does not use any id generator, FALSE otherwise.
1955
     */
1956
    public function isIdGeneratorNone()
1957
    {
1958
        return $this->generatorType == self::GENERATOR_TYPE_NONE;
1959
    }
1960
1961
    /**
1962
     * Sets the version field mapping used for versioning. Sets the default
1963
     * value to use depending on the column type.
1964
     *
1965
     * @param array $mapping   The version field mapping array
1966
     *
1967
     * @throws LockException
1968
     */
1969 100
    public function setVersionMapping(array &$mapping)
1970
    {
1971 100
        if ($mapping['type'] !== 'int' && $mapping['type'] !== 'date') {
1972 1
            throw LockException::invalidVersionFieldType($mapping['type']);
1973
        }
1974
1975 99
        $this->isVersioned  = true;
1976 99
        $this->versionField = $mapping['fieldName'];
1977 99
    }
1978
1979
    /**
1980
     * Sets whether this class is to be versioned for optimistic locking.
1981
     *
1982
     * @param boolean $bool
1983
     */
1984 367
    public function setVersioned($bool)
1985
    {
1986 367
        $this->isVersioned = $bool;
1987 367
    }
1988
1989
    /**
1990
     * Sets the name of the field that is to be used for versioning if this class is
1991
     * versioned for optimistic locking.
1992
     *
1993
     * @param string $versionField
1994
     */
1995 367
    public function setVersionField($versionField)
1996
    {
1997 367
        $this->versionField = $versionField;
1998 367
    }
1999
2000
    /**
2001
     * Sets the version field mapping used for versioning. Sets the default
2002
     * value to use depending on the column type.
2003
     *
2004
     * @param array $mapping   The version field mapping array
2005
     *
2006
     * @throws \Doctrine\ODM\MongoDB\LockException
2007
     */
2008 27
    public function setLockMapping(array &$mapping)
2009
    {
2010 27
        if ($mapping['type'] !== 'int') {
2011 1
            throw LockException::invalidLockFieldType($mapping['type']);
2012
        }
2013
2014 26
        $this->isLockable = true;
2015 26
        $this->lockField = $mapping['fieldName'];
2016 26
    }
2017
2018
    /**
2019
     * Sets whether this class is to allow pessimistic locking.
2020
     *
2021
     * @param boolean $bool
2022
     */
2023
    public function setLockable($bool)
2024
    {
2025
        $this->isLockable = $bool;
2026
    }
2027
2028
    /**
2029
     * Sets the name of the field that is to be used for storing whether a document
2030
     * is currently locked or not.
2031
     *
2032
     * @param string $lockField
2033
     */
2034
    public function setLockField($lockField)
2035
    {
2036
        $this->lockField = $lockField;
2037
    }
2038
2039
    /**
2040
     * {@inheritDoc}
2041
     */
2042
    public function getFieldNames()
2043
    {
2044
        return array_keys($this->fieldMappings);
2045
    }
2046
2047
    /**
2048
     * {@inheritDoc}
2049
     */
2050
    public function getAssociationNames()
2051
    {
2052
        return array_keys($this->associationMappings);
2053
    }
2054
2055
    /**
2056
     * {@inheritDoc}
2057
     */
2058 22
    public function getTypeOfField($fieldName)
2059
    {
2060 22
        return isset($this->fieldMappings[$fieldName]) ?
2061 22
            $this->fieldMappings[$fieldName]['type'] : null;
2062
    }
2063
2064
    /**
2065
     * {@inheritDoc}
2066
     */
2067 6
    public function getAssociationTargetClass($assocName)
2068
    {
2069 6
        if ( ! isset($this->associationMappings[$assocName])) {
2070 3
            throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association.");
2071
        }
2072
2073 3
        return $this->associationMappings[$assocName]['targetDocument'];
2074
    }
2075
2076
    /**
2077
     * Retrieve the collectionClass associated with an association
2078
     *
2079
     * @param string $assocName
2080
     */
2081 2
    public function getAssociationCollectionClass($assocName)
2082
    {
2083 2
        if ( ! isset($this->associationMappings[$assocName])) {
2084
            throw new InvalidArgumentException("Association name expected, '" . $assocName . "' is not an association.");
2085
        }
2086
2087 2
        if ( ! array_key_exists('collectionClass', $this->associationMappings[$assocName])) {
2088
            throw new InvalidArgumentException("collectionClass can only be applied to 'embedMany' and 'referenceMany' associations.");
2089
        }
2090
2091 2
        return $this->associationMappings[$assocName]['collectionClass'];
2092
    }
2093
2094
    /**
2095
     * {@inheritDoc}
2096
     */
2097
    public function isAssociationInverseSide($fieldName)
2098
    {
2099
        throw new \BadMethodCallException(__METHOD__ . '() is not implemented yet.');
2100
    }
2101
2102
    /**
2103
     * {@inheritDoc}
2104
     */
2105
    public function getAssociationMappedByTargetField($fieldName)
2106
    {
2107
        throw new \BadMethodCallException(__METHOD__ . '() is not implemented yet.');
2108
    }
2109
}
2110