Completed
Pull Request — master (#5828)
by Matteo
13:04
created

ClassMetadataInfo::markReadOnly()   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
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
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\ORM\Mapping;
21
22
use BadMethodCallException;
23
use Doctrine\Instantiator\Instantiator;
24
use InvalidArgumentException;
25
use RuntimeException;
26
use Doctrine\DBAL\Types\Type;
27
use Doctrine\DBAL\Platforms\AbstractPlatform;
28
use ReflectionClass;
29
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Doctrine\ORM\Mapping\ClassMetadata.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
30
use Doctrine\Common\ClassLoader;
31
use Doctrine\ORM\Cache\CacheException;
32
33
/**
34
 * A <tt>ClassMetadata</tt> instance holds all the object-relational mapping metadata
35
 * of an entity and its associations.
36
 *
37
 * Once populated, ClassMetadata instances are usually cached in a serialized form.
38
 *
39
 * <b>IMPORTANT NOTE:</b>
40
 *
41
 * The fields of this class are only public for 2 reasons:
42
 * 1) To allow fast READ access.
43
 * 2) To drastically reduce the size of a serialized instance (private/protected members
44
 *    get the whole class name, namespace inclusive, prepended to every property in
45
 *    the serialized representation).
46
 *
47
 * @author Roman Borschel <[email protected]>
48
 * @author Jonathan H. Wage <[email protected]>
49
 * @since 2.0
50
 */
51
class ClassMetadataInfo implements ClassMetadata
52
{
53
    /* The inheritance mapping types */
54
    /**
55
     * NONE means the class does not participate in an inheritance hierarchy
56
     * and therefore does not need an inheritance mapping type.
57
     */
58
    const INHERITANCE_TYPE_NONE = 1;
59
60
    /**
61
     * JOINED means the class will be persisted according to the rules of
62
     * <tt>Class Table Inheritance</tt>.
63
     */
64
    const INHERITANCE_TYPE_JOINED = 2;
65
66
    /**
67
     * SINGLE_TABLE means the class will be persisted according to the rules of
68
     * <tt>Single Table Inheritance</tt>.
69
     */
70
    const INHERITANCE_TYPE_SINGLE_TABLE = 3;
71
72
    /**
73
     * TABLE_PER_CLASS means the class will be persisted according to the rules
74
     * of <tt>Concrete Table Inheritance</tt>.
75
     */
76
    const INHERITANCE_TYPE_TABLE_PER_CLASS = 4;
77
78
    /* The Id generator types. */
79
    /**
80
     * AUTO means the generator type will depend on what the used platform prefers.
81
     * Offers full portability.
82
     */
83
    const GENERATOR_TYPE_AUTO = 1;
84
85
    /**
86
     * SEQUENCE means a separate sequence object will be used. Platforms that do
87
     * not have native sequence support may emulate it. Full portability is currently
88
     * not guaranteed.
89
     */
90
    const GENERATOR_TYPE_SEQUENCE = 2;
91
92
    /**
93
     * TABLE means a separate table is used for id generation.
94
     * Offers full portability.
95
     */
96
    const GENERATOR_TYPE_TABLE = 3;
97
98
    /**
99
     * IDENTITY means an identity column is used for id generation. The database
100
     * will fill in the id column on insertion. Platforms that do not support
101
     * native identity columns may emulate them. Full portability is currently
102
     * not guaranteed.
103
     */
104
    const GENERATOR_TYPE_IDENTITY = 4;
105
106
    /**
107
     * NONE means the class does not have a generated id. That means the class
108
     * must have a natural, manually assigned id.
109
     */
110
    const GENERATOR_TYPE_NONE = 5;
111
112
    /**
113
     * UUID means that a UUID/GUID expression is used for id generation. Full
114
     * portability is currently not guaranteed.
115
     */
116
    const GENERATOR_TYPE_UUID = 6;
117
118
    /**
119
     * CUSTOM means that customer will use own ID generator that supposedly work
120
     */
121
    const GENERATOR_TYPE_CUSTOM = 7;
122
123
    /**
124
     * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time
125
     * by doing a property-by-property comparison with the original data. This will
126
     * be done for all entities that are in MANAGED state at commit-time.
127
     *
128
     * This is the default change tracking policy.
129
     */
130
    const CHANGETRACKING_DEFERRED_IMPLICIT = 1;
131
132
    /**
133
     * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time
134
     * by doing a property-by-property comparison with the original data. This will
135
     * be done only for entities that were explicitly saved (through persist() or a cascade).
136
     */
137
    const CHANGETRACKING_DEFERRED_EXPLICIT = 2;
138
139
    /**
140
     * NOTIFY means that Doctrine relies on the entities sending out notifications
141
     * when their properties change. Such entity classes must implement
142
     * the <tt>NotifyPropertyChanged</tt> interface.
143
     */
144
    const CHANGETRACKING_NOTIFY = 3;
145
146
    /**
147
     * Specifies that an association is to be fetched when it is first accessed.
148
     */
149
    const FETCH_LAZY = 2;
150
151
    /**
152
     * Specifies that an association is to be fetched when the owner of the
153
     * association is fetched.
154
     */
155
    const FETCH_EAGER = 3;
156
157
    /**
158
     * Specifies that an association is to be fetched lazy (on first access) and that
159
     * commands such as Collection#count, Collection#slice are issued directly against
160
     * the database if the collection is not yet initialized.
161
     */
162
    const FETCH_EXTRA_LAZY = 4;
163
164
    /**
165
     * Identifies a one-to-one association.
166
     */
167
    const ONE_TO_ONE = 1;
168
169
    /**
170
     * Identifies a many-to-one association.
171
     */
172
    const MANY_TO_ONE = 2;
173
174
    /**
175
     * Identifies a one-to-many association.
176
     */
177
    const ONE_TO_MANY = 4;
178
179
    /**
180
     * Identifies a many-to-many association.
181
     */
182
    const MANY_TO_MANY = 8;
183
184
    /**
185
     * Combined bitmask for to-one (single-valued) associations.
186
     */
187
    const TO_ONE = 3;
188
189
    /**
190
     * Combined bitmask for to-many (collection-valued) associations.
191
     */
192
    const TO_MANY = 12;
193
194
    /**
195
     * ReadOnly cache can do reads, inserts and deletes, cannot perform updates or employ any locks,
196
     */
197
    const CACHE_USAGE_READ_ONLY = 1;
198
199
    /**
200
     * Nonstrict Read Write Cache doesn’t employ any locks but can do inserts, update and deletes.
201
     */
202
    const CACHE_USAGE_NONSTRICT_READ_WRITE = 2;
203
204
    /**
205
     * Read Write Attempts to lock the entity before update/delete.
206
     */
207
    const CACHE_USAGE_READ_WRITE = 3;
208
209
    /**
210
     * READ-ONLY: The name of the entity class.
211
     *
212
     * @var string
213
     */
214
    public $name;
215
216
    /**
217
     * READ-ONLY: The namespace the entity class is contained in.
218
     *
219
     * @var string
220
     *
221
     * @todo Not really needed. Usage could be localized.
222
     */
223
    public $namespace;
224
225
    /**
226
     * READ-ONLY: The name of the entity class that is at the root of the mapped entity inheritance
227
     * hierarchy. If the entity is not part of a mapped inheritance hierarchy this is the same
228
     * as {@link $name}.
229
     *
230
     * @var string
231
     */
232
    public $rootEntityName;
233
234
    /**
235
     * READ-ONLY: The definition of custom generator. Only used for CUSTOM
236
     * generator type
237
     *
238
     * The definition has the following structure:
239
     * <code>
240
     * array(
241
     *     'class' => 'ClassName',
242
     * )
243
     * </code>
244
     *
245
     * @var array
246
     *
247
     * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
248
     */
249
    public $customGeneratorDefinition;
250
251
    /**
252
     * The name of the custom repository class used for the entity class.
253
     * (Optional).
254
     *
255
     * @var string
256
     */
257
    public $customRepositoryClassName;
258
259
    /**
260
     * READ-ONLY: Whether this class describes the mapping of a mapped superclass.
261
     *
262
     * @var boolean
263
     */
264
    public $isMappedSuperclass = false;
265
266
    /**
267
     * READ-ONLY: Whether this class describes the mapping of an embeddable class.
268
     *
269
     * @var boolean
270
     */
271
    public $isEmbeddedClass = false;
272
273
    /**
274
     * READ-ONLY: The names of the parent classes (ancestors).
275
     *
276
     * @var array
277
     */
278
    public $parentClasses = array();
279
280
    /**
281
     * READ-ONLY: The names of all subclasses (descendants).
282
     *
283
     * @var array
284
     */
285
    public $subClasses = array();
286
287
    /**
288
     * READ-ONLY: The names of all embedded classes based on properties.
289
     *
290
     * @var array
291
     */
292
    public $embeddedClasses = array();
293
294
    /**
295
     * READ-ONLY: The named queries allowed to be called directly from Repository.
296
     *
297
     * @var array
298
     */
299
    public $namedQueries = array();
300
301
    /**
302
     * READ-ONLY: The named native queries allowed to be called directly from Repository.
303
     *
304
     * A native SQL named query definition has the following structure:
305
     * <pre>
306
     * array(
307
     *     'name'               => <query name>,
308
     *     'query'              => <sql query>,
309
     *     'resultClass'        => <class of the result>,
310
     *     'resultSetMapping'   => <name of a SqlResultSetMapping>
311
     * )
312
     * </pre>
313
     *
314
     * @var array
315
     */
316
    public $namedNativeQueries = array();
317
318
    /**
319
     * READ-ONLY: The mappings of the results of native SQL queries.
320
     *
321
     * A native result mapping definition has the following structure:
322
     * <pre>
323
     * array(
324
     *     'name'               => <result name>,
325
     *     'entities'           => array(<entity result mapping>),
326
     *     'columns'            => array(<column result mapping>)
327
     * )
328
     * </pre>
329
     *
330
     * @var array
331
     */
332
    public $sqlResultSetMappings = array();
333
334
    /**
335
     * READ-ONLY: The field names of all fields that are part of the identifier/primary key
336
     * of the mapped entity class.
337
     *
338
     * @var array
339
     */
340
    public $identifier = array();
341
342
    /**
343
     * READ-ONLY: The inheritance mapping type used by the class.
344
     *
345
     * @var integer
346
     */
347
    public $inheritanceType = self::INHERITANCE_TYPE_NONE;
348
349
    /**
350
     * READ-ONLY: The Id generator type used by the class.
351
     *
352
     * @var int
353
     */
354
    public $generatorType = self::GENERATOR_TYPE_NONE;
355
356
    /**
357
     * READ-ONLY: The field mappings of the class.
358
     * Keys are field names and values are mapping definitions.
359
     *
360
     * The mapping definition array has the following values:
361
     *
362
     * - <b>fieldName</b> (string)
363
     * The name of the field in the Entity.
364
     *
365
     * - <b>type</b> (string)
366
     * The type name of the mapped field. Can be one of Doctrine's mapping types
367
     * or a custom mapping type.
368
     *
369
     * - <b>columnName</b> (string, optional)
370
     * The column name. Optional. Defaults to the field name.
371
     *
372
     * - <b>length</b> (integer, optional)
373
     * The database length of the column. Optional. Default value taken from
374
     * the type.
375
     *
376
     * - <b>id</b> (boolean, optional)
377
     * Marks the field as the primary key of the entity. Multiple fields of an
378
     * entity can have the id attribute, forming a composite key.
379
     *
380
     * - <b>nullable</b> (boolean, optional)
381
     * Whether the column is nullable. Defaults to FALSE.
382
     *
383
     * - <b>columnDefinition</b> (string, optional, schema-only)
384
     * The SQL fragment that is used when generating the DDL for the column.
385
     *
386
     * - <b>precision</b> (integer, optional, schema-only)
387
     * The precision of a decimal column. Only valid if the column type is decimal.
388
     *
389
     * - <b>scale</b> (integer, optional, schema-only)
390
     * The scale of a decimal column. Only valid if the column type is decimal.
391
     *
392
     * - <b>'unique'</b> (string, optional, schema-only)
393
     * Whether a unique constraint should be generated for the column.
394
     *
395
     * @var array
396
     */
397
    public $fieldMappings = array();
398
399
    /**
400
     * READ-ONLY: An array of field names. Used to look up field names from column names.
401
     * Keys are column names and values are field names.
402
     *
403
     * @var array
404
     */
405
    public $fieldNames = array();
406
407
    /**
408
     * READ-ONLY: A map of field names to column names. Keys are field names and values column names.
409
     * Used to look up column names from field names.
410
     * This is the reverse lookup map of $_fieldNames.
411
     *
412
     * @var array
413
     *
414
     * @deprecated 3.0 Remove this.
415
     */
416
    public $columnNames = array();
417
418
    /**
419
     * READ-ONLY: The discriminator value of this class.
420
     *
421
     * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
422
     * where a discriminator column is used.</b>
423
     *
424
     * @var mixed
425
     *
426
     * @see discriminatorColumn
427
     */
428
    public $discriminatorValue;
429
430
    /**
431
     * READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
432
     *
433
     * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
434
     * where a discriminator column is used.</b>
435
     *
436
     * @var mixed
437
     *
438
     * @see discriminatorColumn
439
     */
440
    public $discriminatorMap = array();
441
442
    /**
443
     * READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE
444
     * inheritance mappings.
445
     *
446
     * @var array
447
     */
448
    public $discriminatorColumn;
449
450
    /**
451
     * READ-ONLY: The primary table definition. The definition is an array with the
452
     * following entries:
453
     *
454
     * name => <tableName>
455
     * schema => <schemaName>
456
     * indexes => array
457
     * uniqueConstraints => array
458
     *
459
     * @var array
460
     */
461
    public $table;
462
463
    /**
464
     * READ-ONLY: The registered lifecycle callbacks for entities of this class.
465
     *
466
     * @var array
467
     */
468
    public $lifecycleCallbacks = array();
469
470
    /**
471
     * READ-ONLY: The registered entity listeners.
472
     *
473
     * @var array
474
     */
475
    public $entityListeners = array();
476
477
    /**
478
     * READ-ONLY: The association mappings of this class.
479
     *
480
     * The mapping definition array supports the following keys:
481
     *
482
     * - <b>fieldName</b> (string)
483
     * The name of the field in the entity the association is mapped to.
484
     *
485
     * - <b>targetEntity</b> (string)
486
     * The class name of the target entity. If it is fully-qualified it is used as is.
487
     * If it is a simple, unqualified class name the namespace is assumed to be the same
488
     * as the namespace of the source entity.
489
     *
490
     * - <b>mappedBy</b> (string, required for bidirectional associations)
491
     * The name of the field that completes the bidirectional association on the owning side.
492
     * This key must be specified on the inverse side of a bidirectional association.
493
     *
494
     * - <b>inversedBy</b> (string, required for bidirectional associations)
495
     * The name of the field that completes the bidirectional association on the inverse side.
496
     * This key must be specified on the owning side of a bidirectional association.
497
     *
498
     * - <b>cascade</b> (array, optional)
499
     * The names of persistence operations to cascade on the association. The set of possible
500
     * values are: "persist", "remove", "detach", "merge", "refresh", "all" (implies all others).
501
     *
502
     * - <b>orderBy</b> (array, one-to-many/many-to-many only)
503
     * A map of field names (of the target entity) to sorting directions (ASC/DESC).
504
     * Example: array('priority' => 'desc')
505
     *
506
     * - <b>fetch</b> (integer, optional)
507
     * The fetching strategy to use for the association, usually defaults to FETCH_LAZY.
508
     * Possible values are: ClassMetadata::FETCH_EAGER, ClassMetadata::FETCH_LAZY.
509
     *
510
     * - <b>joinTable</b> (array, optional, many-to-many only)
511
     * Specification of the join table and its join columns (foreign keys).
512
     * Only valid for many-to-many mappings. Note that one-to-many associations can be mapped
513
     * through a join table by simply mapping the association as many-to-many with a unique
514
     * constraint on the join table.
515
     *
516
     * - <b>indexBy</b> (string, optional, to-many only)
517
     * Specification of a field on target-entity that is used to index the collection by.
518
     * This field HAS to be either the primary key or a unique column. Otherwise the collection
519
     * does not contain all the entities that are actually related.
520
     *
521
     * A join table definition has the following structure:
522
     * <pre>
523
     * array(
524
     *     'name' => <join table name>,
525
     *      'joinColumns' => array(<join column mapping from join table to source table>),
526
     *      'inverseJoinColumns' => array(<join column mapping from join table to target table>)
527
     * )
528
     * </pre>
529
     *
530
     * @var array
531
     */
532
    public $associationMappings = array();
533
534
    /**
535
     * READ-ONLY: Flag indicating whether the identifier/primary key of the class is composite.
536
     *
537
     * @var boolean
538
     */
539
    public $isIdentifierComposite = false;
540
541
    /**
542
     * READ-ONLY: Flag indicating whether the identifier/primary key contains at least one foreign key association.
543
     *
544
     * This flag is necessary because some code blocks require special treatment of this cases.
545
     *
546
     * @var boolean
547
     */
548
    public $containsForeignIdentifier = false;
549
550
    /**
551
     * READ-ONLY: The ID generator used for generating IDs for this class.
552
     *
553
     * @var \Doctrine\ORM\Id\AbstractIdGenerator
554
     *
555
     * @todo Remove!
556
     */
557
    public $idGenerator;
558
559
    /**
560
     * READ-ONLY: The definition of the sequence generator of this class. Only used for the
561
     * SEQUENCE generation strategy.
562
     *
563
     * The definition has the following structure:
564
     * <code>
565
     * array(
566
     *     'sequenceName' => 'name',
567
     *     'allocationSize' => 20,
568
     *     'initialValue' => 1
569
     * )
570
     * </code>
571
     *
572
     * @var array
573
     *
574
     * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
575
     */
576
    public $sequenceGeneratorDefinition;
577
578
    /**
579
     * READ-ONLY: The definition of the table generator of this class. Only used for the
580
     * TABLE generation strategy.
581
     *
582
     * @var array
583
     *
584
     * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
585
     */
586
    public $tableGeneratorDefinition;
587
588
    /**
589
     * READ-ONLY: The policy used for change-tracking on entities of this class.
590
     *
591
     * @var integer
592
     */
593
    public $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT;
594
595
    /**
596
     * READ-ONLY: A flag for whether or not instances of this class are to be versioned
597
     * with optimistic locking.
598
     *
599
     * @var boolean
600
     */
601
    public $isVersioned;
602
603
    /**
604
     * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any).
605
     *
606
     * @var mixed
607
     */
608
    public $versionField;
609
610
    /**
611
     * @var array
612
     */
613
    public $cache = null;
614
615
    /**
616
     * The ReflectionClass instance of the mapped class.
617
     *
618
     * @var ReflectionClass
619
     */
620
    public $reflClass;
621
622
    /**
623
     * Is this entity marked as "read-only"?
624
     *
625
     * That means it is never considered for change-tracking in the UnitOfWork. It is a very helpful performance
626
     * optimization for entities that are immutable, either in your domain or through the relation database
627
     * (coming from a view, or a history table for example).
628
     *
629
     * @var bool
630
     */
631
    public $isReadOnly = false;
632
633
    /**
634
     * NamingStrategy determining the default column and table names.
635
     *
636
     * @var \Doctrine\ORM\Mapping\NamingStrategy
637
     */
638
    protected $namingStrategy;
639
640
    /**
641
     * The ReflectionProperty instances of the mapped class.
642
     *
643
     * @var \ReflectionProperty[]
644
     */
645
    public $reflFields = array();
646
647
    /**
648
     * @var \Doctrine\Instantiator\InstantiatorInterface|null
649
     */
650
    private $instantiator;
651
652
    /**
653
     * Initializes a new ClassMetadata instance that will hold the object-relational mapping
654
     * metadata of the class with the given name.
655
     *
656
     * @param string              $entityName     The name of the entity class the new instance is used for.
657
     * @param NamingStrategy|null $namingStrategy
658
     */
659 645
    public function __construct($entityName, NamingStrategy $namingStrategy = null)
660
    {
661 645
        $this->name = $entityName;
662 645
        $this->rootEntityName = $entityName;
663 645
        $this->namingStrategy = $namingStrategy ?: new DefaultNamingStrategy();
664 645
        $this->instantiator   = new Instantiator();
665 645
    }
666
667
    /**
668
     * Gets the ReflectionProperties of the mapped class.
669
     *
670
     * @return array An array of ReflectionProperty instances.
671
     */
672 223
    public function getReflectionProperties()
673
    {
674 223
        return $this->reflFields;
675
    }
676
677
    /**
678
     * Gets a ReflectionProperty for a specific field of the mapped class.
679
     *
680
     * @param string $name
681
     *
682
     * @return \ReflectionProperty
683
     */
684 1
    public function getReflectionProperty($name)
685
    {
686 1
        return $this->reflFields[$name];
687
    }
688
689
    /**
690
     * Gets the ReflectionProperty for the single identifier field.
691
     *
692
     * @return \ReflectionProperty
693
     *
694
     * @throws BadMethodCallException If the class has a composite identifier.
695
     */
696
    public function getSingleIdReflectionProperty()
697
    {
698
        if ($this->isIdentifierComposite) {
699
            throw new BadMethodCallException("Class " . $this->name . " has a composite identifier.");
700
        }
701
702
        return $this->reflFields[$this->identifier[0]];
703
    }
704
705
    /**
706
     * Extracts the identifier values of an entity of this class.
707
     *
708
     * For composite identifiers, the identifier values are returned as an array
709
     * with the same order as the field order in {@link identifier}.
710
     *
711
     * @param object $entity
712
     *
713
     * @return array
714
     */
715 463
    public function getIdentifierValues($entity)
716
    {
717 463
        if ($this->isIdentifierComposite) {
718 90
            $id = array();
719
720 90
            foreach ($this->identifier as $idField) {
721 90
                $value = $this->reflFields[$idField]->getValue($entity);
722
723 90
                if ($value !== null) {
724 90
                    $id[$idField] = $value;
725
                }
726
            }
727
728 90
            return $id;
729
        }
730
731 444
        $id = $this->identifier[0];
732 444
        $value = $this->reflFields[$id]->getValue($entity);
733
734 444
        if (null === $value) {
735 28
            return array();
736
        }
737
738 421
        return array($id => $value);
739
    }
740
741
    /**
742
     * Populates the entity identifier of an entity.
743
     *
744
     * @param object $entity
745
     * @param array  $id
746
     *
747
     * @return void
748
     *
749
     * @todo Rename to assignIdentifier()
750
     */
751 6
    public function setIdentifierValues($entity, array $id)
752
    {
753 6
        foreach ($id as $idField => $idValue) {
754 6
            $this->reflFields[$idField]->setValue($entity, $idValue);
755
        }
756 6
    }
757
758
    /**
759
     * Sets the specified field to the specified value on the given entity.
760
     *
761
     * @param object $entity
762
     * @param string $field
763
     * @param mixed  $value
764
     *
765
     * @return void
766
     */
767 231
    public function setFieldValue($entity, $field, $value)
768
    {
769 231
        $this->reflFields[$field]->setValue($entity, $value);
770 231
    }
771
772
    /**
773
     * Gets the specified field's value off the given entity.
774
     *
775
     * @param object $entity
776
     * @param string $field
777
     *
778
     * @return mixed
779
     */
780 302
    public function getFieldValue($entity, $field)
781
    {
782 302
        if (!$entity instanceof $this->reflFields[$field]->class) {
783 1
            return null;
784
        }
785
786 302
        return $this->reflFields[$field]->getValue($entity);
787
    }
788
789
    /**
790
     * Creates a string representation of this instance.
791
     *
792
     * @return string The string representation of this instance.
793
     *
794
     * @todo Construct meaningful string representation.
795
     */
796
    public function __toString()
797
    {
798
        return __CLASS__ . '@' . spl_object_hash($this);
799
    }
800
801
    /**
802
     * Determines which fields get serialized.
803
     *
804
     * It is only serialized what is necessary for best unserialization performance.
805
     * That means any metadata properties that are not set or empty or simply have
806
     * their default value are NOT serialized.
807
     *
808
     * Parts that are also NOT serialized because they can not be properly unserialized:
809
     *      - reflClass (ReflectionClass)
810
     *      - reflFields (ReflectionProperty array)
811
     *
812
     * @return array The names of all the fields that should be serialized.
813
     */
814 6
    public function __sleep()
815
    {
816
        // This metadata is always serialized/cached.
817
        $serialized = array(
818 6
            'associationMappings',
819
            'columnNames', //TODO: 3.0 Remove this. Can use fieldMappings[$fieldName]['columnName']
820
            'fieldMappings',
821
            'fieldNames',
822
            'embeddedClasses',
823
            'identifier',
824
            'isIdentifierComposite', // TODO: REMOVE
825
            'name',
826
            'namespace', // TODO: REMOVE
827
            'table',
828
            'rootEntityName',
829
            'idGenerator', //TODO: Does not really need to be serialized. Could be moved to runtime.
830
        );
831
832
        // The rest of the metadata is only serialized if necessary.
833 6
        if ($this->changeTrackingPolicy != self::CHANGETRACKING_DEFERRED_IMPLICIT) {
834
            $serialized[] = 'changeTrackingPolicy';
835
        }
836
837 6
        if ($this->customRepositoryClassName) {
838 1
            $serialized[] = 'customRepositoryClassName';
839
        }
840
841 6
        if ($this->inheritanceType != self::INHERITANCE_TYPE_NONE) {
842 1
            $serialized[] = 'inheritanceType';
843 1
            $serialized[] = 'discriminatorColumn';
844 1
            $serialized[] = 'discriminatorValue';
845 1
            $serialized[] = 'discriminatorMap';
846 1
            $serialized[] = 'parentClasses';
847 1
            $serialized[] = 'subClasses';
848
        }
849
850 6
        if ($this->generatorType != self::GENERATOR_TYPE_NONE) {
851 1
            $serialized[] = 'generatorType';
852 1
            if ($this->generatorType == self::GENERATOR_TYPE_SEQUENCE) {
853
                $serialized[] = 'sequenceGeneratorDefinition';
854
            }
855
        }
856
857 6
        if ($this->isMappedSuperclass) {
858
            $serialized[] = 'isMappedSuperclass';
859
        }
860
861 6
        if ($this->isEmbeddedClass) {
862 1
            $serialized[] = 'isEmbeddedClass';
863
        }
864
865 6
        if ($this->containsForeignIdentifier) {
866
            $serialized[] = 'containsForeignIdentifier';
867
        }
868
869 6
        if ($this->isVersioned) {
870
            $serialized[] = 'isVersioned';
871
            $serialized[] = 'versionField';
872
        }
873
874 6
        if ($this->lifecycleCallbacks) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->lifecycleCallbacks of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
875
            $serialized[] = 'lifecycleCallbacks';
876
        }
877
878 6
        if ($this->entityListeners) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->entityListeners of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
879 1
            $serialized[] = 'entityListeners';
880
        }
881
882 6
        if ($this->namedQueries) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->namedQueries of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
883 1
            $serialized[] = 'namedQueries';
884
        }
885
886 6
        if ($this->namedNativeQueries) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->namedNativeQueries of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
887
            $serialized[] = 'namedNativeQueries';
888
        }
889
890 6
        if ($this->sqlResultSetMappings) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->sqlResultSetMappings of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
891
            $serialized[] = 'sqlResultSetMappings';
892
        }
893
894 6
        if ($this->isReadOnly) {
895 1
            $serialized[] = 'isReadOnly';
896
        }
897
898 6
        if ($this->customGeneratorDefinition) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->customGeneratorDefinition of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
899
            $serialized[] = "customGeneratorDefinition";
900
        }
901
902 6
        if ($this->cache) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->cache of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
903
            $serialized[] = 'cache';
904
        }
905
906 6
        return $serialized;
907
    }
908
909
    /**
910
     * Creates a new instance of the mapped class, without invoking the constructor.
911
     *
912
     * @return object
913
     */
914 670
    public function newInstance()
915
    {
916 670
        return $this->instantiator->instantiate($this->name);
917
    }
918
919
    /**
920
     * Restores some state that can not be serialized/unserialized.
921
     *
922
     * @param \Doctrine\Common\Persistence\Mapping\ReflectionService $reflService
923
     *
924
     * @return void
925
     */
926 2003
    public function wakeupReflection($reflService)
927
    {
928
        // Restore ReflectionClass and properties
929 2003
        $this->reflClass    = $reflService->getClass($this->name);
930 2003
        $this->instantiator = $this->instantiator ?: new Instantiator();
931
932 2003
        $parentReflFields = array();
933
934 2003
        foreach ($this->embeddedClasses as $property => $embeddedClass) {
935 20
            if (isset($embeddedClass['declaredField'])) {
936 15
                $parentReflFields[$property] = new ReflectionEmbeddedProperty(
937 15
                    $parentReflFields[$embeddedClass['declaredField']],
938 15
                    $reflService->getAccessibleProperty(
0 ignored issues
show
Bug introduced by
It seems like $reflService->getAccessi...Class['originalField']) can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
939 15
                        $this->embeddedClasses[$embeddedClass['declaredField']]['class'],
940 15
                        $embeddedClass['originalField']
941
                    ),
942 15
                    $this->embeddedClasses[$embeddedClass['declaredField']]['class']
943
                );
944
945 15
                continue;
946
            }
947
948 20
            $parentReflFields[$property] = $reflService->getAccessibleProperty($this->name, $property);
949 20
            $this->reflFields[$property] = $reflService->getAccessibleProperty($this->name, $property);
950
        }
951
952 2003
        foreach ($this->fieldMappings as $field => $mapping) {
953 1998
            if (isset($mapping['declaredField']) && isset($parentReflFields[$mapping['declaredField']])) {
954 19
                $this->reflFields[$field] = new ReflectionEmbeddedProperty(
955 19
                    $parentReflFields[$mapping['declaredField']],
956 19
                    $reflService->getAccessibleProperty($mapping['originalClass'], $mapping['originalField']),
0 ignored issues
show
Bug introduced by
It seems like $reflService->getAccessi...pping['originalField']) can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
957 19
                    $mapping['originalClass']
958
                );
959 19
                continue;
960
            }
961
962 1998
            $this->reflFields[$field] = isset($mapping['declared'])
963 493
                ? $reflService->getAccessibleProperty($mapping['declared'], $field)
964 1998
                : $reflService->getAccessibleProperty($this->name, $field);
965
        }
966
967 2003
        foreach ($this->associationMappings as $field => $mapping) {
968 1691
            $this->reflFields[$field] = isset($mapping['declared'])
969 401
                ? $reflService->getAccessibleProperty($mapping['declared'], $field)
970 1691
                : $reflService->getAccessibleProperty($this->name, $field);
971
        }
972 2003
    }
973
974
    /**
975
     * Initializes a new ClassMetadata instance that will hold the object-relational mapping
976
     * metadata of the class with the given name.
977
     *
978
     * @param \Doctrine\Common\Persistence\Mapping\ReflectionService $reflService The reflection service.
979
     *
980
     * @return void
981
     */
982 609
    public function initializeReflection($reflService)
983
    {
984 609
        $this->reflClass = $reflService->getClass($this->name);
985 609
        $this->namespace = $reflService->getClassNamespace($this->name);
986
987 609
        if ($this->reflClass) {
988 602
            $this->name = $this->rootEntityName = $this->reflClass->getName();
989
        }
990
991 609
        $this->table['name'] = $this->namingStrategy->classToTableName($this->name);
992 609
    }
993
994
    /**
995
     * Validates Identifier.
996
     *
997
     * @return void
998
     *
999
     * @throws MappingException
1000
     */
1001 398
    public function validateIdentifier()
1002
    {
1003 398
        if ($this->isMappedSuperclass || $this->isEmbeddedClass) {
1004 59
            return;
1005
        }
1006
1007
        // Verify & complete identifier mapping
1008 396
        if ( ! $this->identifier) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->identifier of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1009 6
            throw MappingException::identifierRequired($this->name);
1010
        }
1011
1012 390
        if ($this->usesIdGenerator() && $this->isIdentifierComposite) {
1013
            throw MappingException::compositeKeyAssignedIdGeneratorRequired($this->name);
1014
        }
1015 390
    }
1016
1017
    /**
1018
     * Validates association targets actually exist.
1019
     *
1020
     * @return void
1021
     *
1022
     * @throws MappingException
1023
     */
1024 399
    public function validateAssociations()
1025
    {
1026 399
        foreach ($this->associationMappings as $mapping) {
1027 266
            if ( ! ClassLoader::classExists($mapping['targetEntity']) ) {
1028 266
                throw MappingException::invalidTargetEntityClass($mapping['targetEntity'], $this->name, $mapping['fieldName']);
1029
            }
1030
        }
1031 398
    }
1032
1033
    /**
1034
     * Validates lifecycle callbacks.
1035
     *
1036
     * @param \Doctrine\Common\Persistence\Mapping\ReflectionService $reflService
1037
     *
1038
     * @return void
1039
     *
1040
     * @throws MappingException
1041
     */
1042 399
    public function validateLifecycleCallbacks($reflService)
1043
    {
1044 399
        foreach ($this->lifecycleCallbacks as $callbacks) {
1045 13
            foreach ($callbacks as $callbackFuncName) {
1046 13
                if ( ! $reflService->hasPublicMethod($this->name, $callbackFuncName)) {
1047 13
                    throw MappingException::lifecycleCallbackMethodNotFound($this->name, $callbackFuncName);
1048
                }
1049
            }
1050
        }
1051 398
    }
1052
1053
    /**
1054
     * {@inheritDoc}
1055
     */
1056 526
    public function getReflectionClass()
1057
    {
1058 526
        return $this->reflClass;
1059
    }
1060
1061
    /**
1062
     * @param array $cache
1063
     *
1064
     * @return void
1065
     */
1066 20
    public function enableCache(array $cache)
1067
    {
1068 20
        if ( ! isset($cache['usage'])) {
1069
            $cache['usage'] = self::CACHE_USAGE_READ_ONLY;
1070
        }
1071
1072 20
        if ( ! isset($cache['region'])) {
1073 20
            $cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName));
1074
        }
1075
1076 20
        $this->cache = $cache;
1077 20
    }
1078
1079
    /**
1080
     * @param string $fieldName
1081
     * @param array  $cache
1082
     *
1083
     * @return void
1084
     */
1085 2
    public function enableAssociationCache($fieldName, array $cache)
1086
    {
1087 2
        $this->associationMappings[$fieldName]['cache'] = $this->getAssociationCacheDefaults ($fieldName, $cache);
1088 2
    }
1089
1090
    /**
1091
     * @param string $fieldName
1092
     * @param array  $cache
1093
     *
1094
     * @return array
1095
     */
1096 16
    public function getAssociationCacheDefaults($fieldName, array $cache)
1097
    {
1098 16
        if ( ! isset($cache['usage'])) {
1099 1
            $cache['usage'] = isset($this->cache['usage'])
1100 1
                ? $this->cache['usage']
1101
                : self::CACHE_USAGE_READ_ONLY;
1102
        }
1103
1104 16
        if ( ! isset($cache['region'])) {
1105 16
            $cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName)) . '__' . $fieldName;
1106
        }
1107
1108 16
        return $cache;
1109
    }
1110
1111
    /**
1112
     * Sets the change tracking policy used by this class.
1113
     *
1114
     * @param integer $policy
1115
     *
1116
     * @return void
1117
     */
1118 138
    public function setChangeTrackingPolicy($policy)
1119
    {
1120 138
        $this->changeTrackingPolicy = $policy;
1121 138
    }
1122
1123
    /**
1124
     * Whether the change tracking policy of this class is "deferred explicit".
1125
     *
1126
     * @return boolean
1127
     */
1128 267
    public function isChangeTrackingDeferredExplicit()
1129
    {
1130 267
        return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_EXPLICIT;
1131
    }
1132
1133
    /**
1134
     * Whether the change tracking policy of this class is "deferred implicit".
1135
     *
1136
     * @return boolean
1137
     */
1138 457
    public function isChangeTrackingDeferredImplicit()
1139
    {
1140 457
        return $this->changeTrackingPolicy == self::CHANGETRACKING_DEFERRED_IMPLICIT;
1141
    }
1142
1143
    /**
1144
     * Whether the change tracking policy of this class is "notify".
1145
     *
1146
     * @return boolean
1147
     */
1148 289
    public function isChangeTrackingNotify()
1149
    {
1150 289
        return $this->changeTrackingPolicy == self::CHANGETRACKING_NOTIFY;
1151
    }
1152
1153
    /**
1154
     * Checks whether a field is part of the identifier/primary key field(s).
1155
     *
1156
     * @param string $fieldName The field name.
1157
     *
1158
     * @return boolean TRUE if the field is part of the table identifier/primary key field(s),
1159
     *                 FALSE otherwise.
1160
     */
1161 1068
    public function isIdentifier($fieldName)
1162
    {
1163 1068
        if ( ! $this->identifier) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->identifier of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1164 1
            return false;
1165
        }
1166
1167 1067
        if ( ! $this->isIdentifierComposite) {
1168 1062
            return $fieldName === $this->identifier[0];
1169
        }
1170
1171 93
        return in_array($fieldName, $this->identifier);
1172
    }
1173
1174
    /**
1175
     * Checks if the field is unique.
1176
     *
1177
     * @param string $fieldName The field name.
1178
     *
1179
     * @return boolean TRUE if the field is unique, FALSE otherwise.
1180
     */
1181
    public function isUniqueField($fieldName)
1182
    {
1183
        $mapping = $this->getFieldMapping($fieldName);
1184
1185
        if ($mapping !== false) {
1186
            return isset($mapping['unique']) && $mapping['unique'] == true;
1187
        }
1188
1189
        return false;
1190
    }
1191
1192
    /**
1193
     * Checks if the field is not null.
1194
     *
1195
     * @param string $fieldName The field name.
1196
     *
1197
     * @return boolean TRUE if the field is not null, FALSE otherwise.
1198
     */
1199 1
    public function isNullable($fieldName)
1200
    {
1201 1
        $mapping = $this->getFieldMapping($fieldName);
1202
1203 1
        if ($mapping !== false) {
1204 1
            return isset($mapping['nullable']) && $mapping['nullable'] == true;
1205
        }
1206
1207
        return false;
1208
    }
1209
1210
    /**
1211
     * Gets a column name for a field name.
1212
     * If the column name for the field cannot be found, the given field name
1213
     * is returned.
1214
     *
1215
     * @param string $fieldName The field name.
1216
     *
1217
     * @return string The column name.
1218
     */
1219 16
    public function getColumnName($fieldName)
1220
    {
1221 16
        return isset($this->columnNames[$fieldName])
0 ignored issues
show
Deprecated Code introduced by
The property Doctrine\ORM\Mapping\Cla...adataInfo::$columnNames has been deprecated with message: 3.0 Remove this.

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...
1222 16
            ? $this->columnNames[$fieldName]
0 ignored issues
show
Deprecated Code introduced by
The property Doctrine\ORM\Mapping\Cla...adataInfo::$columnNames has been deprecated with message: 3.0 Remove this.

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...
1223 16
            : $fieldName;
1224
    }
1225
1226
    /**
1227
     * Gets the mapping of a (regular) field that holds some data but not a
1228
     * reference to another object.
1229
     *
1230
     * @param string $fieldName The field name.
1231
     *
1232
     * @return array The field mapping.
1233
     *
1234
     * @throws MappingException
1235
     */
1236 199
    public function getFieldMapping($fieldName)
1237
    {
1238 199
        if ( ! isset($this->fieldMappings[$fieldName])) {
1239 1
            throw MappingException::mappingNotFound($this->name, $fieldName);
1240
        }
1241
1242 198
        return $this->fieldMappings[$fieldName];
1243
    }
1244
1245
    /**
1246
     * Gets the mapping of an association.
1247
     *
1248
     * @see ClassMetadataInfo::$associationMappings
1249
     *
1250
     * @param string $fieldName The field name that represents the association in
1251
     *                          the object model.
1252
     *
1253
     * @return array The mapping.
1254
     *
1255
     * @throws MappingException
1256
     */
1257 484
    public function getAssociationMapping($fieldName)
1258
    {
1259 484
        if ( ! isset($this->associationMappings[$fieldName])) {
1260
            throw MappingException::mappingNotFound($this->name, $fieldName);
1261
        }
1262
1263 484
        return $this->associationMappings[$fieldName];
1264
    }
1265
1266
    /**
1267
     * Gets all association mappings of the class.
1268
     *
1269
     * @return array
1270
     */
1271
    public function getAssociationMappings()
1272
    {
1273
        return $this->associationMappings;
1274
    }
1275
1276
    /**
1277
     * Gets the field name for a column name.
1278
     * If no field name can be found the column name is returned.
1279
     *
1280
     * @param string $columnName The column name.
1281
     *
1282
     * @return string The column alias.
1283
     */
1284 236
    public function getFieldName($columnName)
1285
    {
1286 236
        return isset($this->fieldNames[$columnName])
1287 236
            ? $this->fieldNames[$columnName]
1288 236
            : $columnName;
1289
    }
1290
1291
    /**
1292
     * Gets the named query.
1293
     *
1294
     * @see ClassMetadataInfo::$namedQueries
1295
     *
1296
     * @param string $queryName The query name.
1297
     *
1298
     * @return string
1299
     *
1300
     * @throws MappingException
1301
     */
1302 4
    public function getNamedQuery($queryName)
1303
    {
1304 4
        if ( ! isset($this->namedQueries[$queryName])) {
1305 1
            throw MappingException::queryNotFound($this->name, $queryName);
1306
        }
1307
1308 3
        return $this->namedQueries[$queryName]['dql'];
1309
    }
1310
1311
    /**
1312
     * Gets all named queries of the class.
1313
     *
1314
     * @return array
1315
     */
1316 7
    public function getNamedQueries()
1317
    {
1318 7
        return $this->namedQueries;
1319
    }
1320
1321
    /**
1322
     * Gets the named native query.
1323
     *
1324
     * @see ClassMetadataInfo::$namedNativeQueries
1325
     *
1326
     * @param string $queryName The query name.
1327
     *
1328
     * @return array
1329
     *
1330
     * @throws MappingException
1331
     */
1332 17
    public function getNamedNativeQuery($queryName)
1333
    {
1334 17
        if ( ! isset($this->namedNativeQueries[$queryName])) {
1335
            throw MappingException::queryNotFound($this->name, $queryName);
1336
        }
1337
1338 17
        return $this->namedNativeQueries[$queryName];
1339
    }
1340
1341
    /**
1342
     * Gets all named native queries of the class.
1343
     *
1344
     * @return array
1345
     */
1346 2
    public function getNamedNativeQueries()
1347
    {
1348 2
        return $this->namedNativeQueries;
1349
    }
1350
1351
    /**
1352
     * Gets the result set mapping.
1353
     *
1354
     * @see ClassMetadataInfo::$sqlResultSetMappings
1355
     *
1356
     * @param string $name The result set mapping name.
1357
     *
1358
     * @return array
1359
     *
1360
     * @throws MappingException
1361
     */
1362 21
    public function getSqlResultSetMapping($name)
1363
    {
1364 21
        if ( ! isset($this->sqlResultSetMappings[$name])) {
1365
            throw MappingException::resultMappingNotFound($this->name, $name);
1366
        }
1367
1368 21
        return $this->sqlResultSetMappings[$name];
1369
    }
1370
1371
    /**
1372
     * Gets all sql result set mappings of the class.
1373
     *
1374
     * @return array
1375
     */
1376 8
    public function getSqlResultSetMappings()
1377
    {
1378 8
        return $this->sqlResultSetMappings;
1379
    }
1380
1381
    /**
1382
     * Validates & completes the given field mapping.
1383
     *
1384
     * @param array $mapping The field mapping to validate & complete.
1385
     *
1386
     * @return array The validated and completed field mapping.
1387
     *
1388
     * @throws MappingException
1389
     */
1390 526
    protected function _validateAndCompleteFieldMapping(array &$mapping)
1391
    {
1392
        // Check mandatory fields
1393 526
        if ( ! isset($mapping['fieldName']) || strlen($mapping['fieldName']) == 0) {
1394 1
            throw MappingException::missingFieldName($this->name);
1395
        }
1396
1397 525
        if ( ! isset($mapping['type'])) {
1398
            // Default to string
1399 64
            $mapping['type'] = 'string';
1400
        }
1401
1402
        // Complete fieldName and columnName mapping
1403 525
        if ( ! isset($mapping['columnName'])) {
1404 433
            $mapping['columnName'] = $this->namingStrategy->propertyToColumnName($mapping['fieldName'], $this->name);
1405
        }
1406
1407 525
        if ($mapping['columnName'][0] === '`') {
1408 11
            $mapping['columnName']  = trim($mapping['columnName'], '`');
1409 11
            $mapping['quoted']      = true;
1410
        }
1411
1412 525
        $this->columnNames[$mapping['fieldName']] = $mapping['columnName'];
0 ignored issues
show
Deprecated Code introduced by
The property Doctrine\ORM\Mapping\Cla...adataInfo::$columnNames has been deprecated with message: 3.0 Remove this.

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...
1413
1414 525
        if (isset($this->fieldNames[$mapping['columnName']]) || ($this->discriminatorColumn != null && $this->discriminatorColumn['name'] == $mapping['columnName'])) {
1415 2
            throw MappingException::duplicateColumnName($this->name, $mapping['columnName']);
1416
        }
1417
1418 524
        $this->fieldNames[$mapping['columnName']] = $mapping['fieldName'];
1419
1420
        // Complete id mapping
1421 524
        if (isset($mapping['id']) && $mapping['id'] === true) {
1422 486
            if ($this->versionField == $mapping['fieldName']) {
1423
                throw MappingException::cannotVersionIdField($this->name, $mapping['fieldName']);
1424
            }
1425
1426 486
            if ( ! in_array($mapping['fieldName'], $this->identifier)) {
1427 486
                $this->identifier[] = $mapping['fieldName'];
1428
            }
1429
1430
            // Check for composite key
1431 486
            if ( ! $this->isIdentifierComposite && count($this->identifier) > 1) {
1432 17
                $this->isIdentifierComposite = true;
1433
            }
1434
        }
1435
1436 524
        if (Type::hasType($mapping['type']) && Type::getType($mapping['type'])->canRequireSQLConversion()) {
1437 5
            if (isset($mapping['id']) && $mapping['id'] === true) {
1438
                 throw MappingException::sqlConversionNotAllowedForIdentifiers($this->name, $mapping['fieldName'], $mapping['type']);
1439
            }
1440
1441 5
            $mapping['requireSQLConversion'] = true;
1442
        }
1443 524
    }
1444
1445
    /**
1446
     * Validates & completes the basic mapping information that is common to all
1447
     * association mappings (one-to-one, many-ot-one, one-to-many, many-to-many).
1448
     *
1449
     * @param array $mapping The mapping.
1450
     *
1451
     * @return array The updated mapping.
1452
     *
1453
     * @throws MappingException If something is wrong with the mapping.
1454
     */
1455 349
    protected function _validateAndCompleteAssociationMapping(array $mapping)
1456
    {
1457 349
        if ( ! isset($mapping['mappedBy'])) {
1458 335
            $mapping['mappedBy'] = null;
1459
        }
1460
1461 349
        if ( ! isset($mapping['inversedBy'])) {
1462 322
            $mapping['inversedBy'] = null;
1463
        }
1464
1465 349
        $mapping['isOwningSide'] = true; // assume owning side until we hit mappedBy
1466
1467
        // unset optional indexBy attribute if its empty
1468 349
        if ( ! isset($mapping['indexBy']) || !$mapping['indexBy']) {
1469 346
            unset($mapping['indexBy']);
1470
        }
1471
1472
        // If targetEntity is unqualified, assume it is in the same namespace as
1473
        // the sourceEntity.
1474 349
        $mapping['sourceEntity'] = $this->name;
1475
1476 349
        if (isset($mapping['targetEntity'])) {
1477 349
            $mapping['targetEntity'] = $this->fullyQualifiedClassName($mapping['targetEntity']);
1478 349
            $mapping['targetEntity'] = ltrim($mapping['targetEntity'], '\\');
1479
        }
1480
1481 349
        if (($mapping['type'] & self::MANY_TO_ONE) > 0 && isset($mapping['orphanRemoval']) && $mapping['orphanRemoval'] == true) {
1482 1
            throw MappingException::illegalOrphanRemoval($this->name, $mapping['fieldName']);
1483
        }
1484
1485
        // Complete id mapping
1486 348
        if (isset($mapping['id']) && $mapping['id'] === true) {
1487 53
            if (isset($mapping['orphanRemoval']) && $mapping['orphanRemoval'] == true) {
1488 1
                throw MappingException::illegalOrphanRemovalOnIdentifierAssociation($this->name, $mapping['fieldName']);
1489
            }
1490
1491 52
            if ( ! in_array($mapping['fieldName'], $this->identifier)) {
1492 52
                if (isset($mapping['joinColumns']) && count($mapping['joinColumns']) >= 2) {
1493
                    throw MappingException::cannotMapCompositePrimaryKeyEntitiesAsForeignId(
1494
                        $mapping['targetEntity'], $this->name, $mapping['fieldName']
1495
                    );
1496
                }
1497
1498 52
                $this->identifier[] = $mapping['fieldName'];
1499 52
                $this->containsForeignIdentifier = true;
1500
            }
1501
1502
            // Check for composite key
1503 52
            if ( ! $this->isIdentifierComposite && count($this->identifier) > 1) {
1504 24
                $this->isIdentifierComposite = true;
1505
            }
1506
1507 52
            if ($this->cache && !isset($mapping['cache'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->cache of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1508 3
                throw CacheException::nonCacheableEntityAssociation($this->name, $mapping['fieldName']);
1509
            }
1510
        }
1511
1512
        // Mandatory attributes for both sides
1513
        // Mandatory: fieldName, targetEntity
1514 344
        if ( ! isset($mapping['fieldName']) || strlen($mapping['fieldName']) == 0) {
1515
            throw MappingException::missingFieldName($this->name);
1516
        }
1517
1518 344
        if ( ! isset($mapping['targetEntity'])) {
1519
            throw MappingException::missingTargetEntity($mapping['fieldName']);
1520
        }
1521
1522
        // Mandatory and optional attributes for either side
1523 344
        if ( ! $mapping['mappedBy']) {
1524 330
            if (isset($mapping['joinTable']) && $mapping['joinTable']) {
1525 119
                if (isset($mapping['joinTable']['name']) && $mapping['joinTable']['name'][0] === '`') {
1526 4
                    $mapping['joinTable']['name']   = trim($mapping['joinTable']['name'], '`');
1527 330
                    $mapping['joinTable']['quoted'] = true;
1528
                }
1529
            }
1530
        } else {
1531 182
            $mapping['isOwningSide'] = false;
1532
        }
1533
1534 344
        if (isset($mapping['id']) && $mapping['id'] === true && $mapping['type'] & self::TO_MANY) {
1535 3
            throw MappingException::illegalToManyIdentifierAssociation($this->name, $mapping['fieldName']);
1536
        }
1537
1538
        // Fetch mode. Default fetch mode to LAZY, if not set.
1539 341
        if ( ! isset($mapping['fetch'])) {
1540 95
            $mapping['fetch'] = self::FETCH_LAZY;
1541
        }
1542
1543
        // Cascades
1544 341
        $cascades = isset($mapping['cascade']) ? array_map('strtolower', $mapping['cascade']) : array();
1545
1546 341
        if (in_array('all', $cascades)) {
1547 36
            $cascades = array('remove', 'persist', 'refresh', 'merge', 'detach');
1548
        }
1549
1550 341
        if (count($cascades) !== count(array_intersect($cascades, array('remove', 'persist', 'refresh', 'merge', 'detach')))) {
1551 1
            throw MappingException::invalidCascadeOption(
1552 1
                array_diff($cascades, array_intersect($cascades, array('remove', 'persist', 'refresh', 'merge', 'detach'))),
1553 1
                $this->name,
1554 1
                $mapping['fieldName']
1555
            );
1556
        }
1557
1558 340
        $mapping['cascade'] = $cascades;
1559 340
        $mapping['isCascadeRemove'] = in_array('remove', $cascades);
1560 340
        $mapping['isCascadePersist'] = in_array('persist', $cascades);
1561 340
        $mapping['isCascadeRefresh'] = in_array('refresh', $cascades);
1562 340
        $mapping['isCascadeMerge'] = in_array('merge', $cascades);
1563 340
        $mapping['isCascadeDetach'] = in_array('detach', $cascades);
1564
1565 340
        return $mapping;
1566
    }
1567
1568
    /**
1569
     * Validates & completes a one-to-one association mapping.
1570
     *
1571
     * @param array $mapping The mapping to validate & complete.
1572
     *
1573
     * @return array The validated & completed mapping.
1574
     *
1575
     * @throws RuntimeException
1576
     * @throws MappingException
1577
     */
1578 296
    protected function _validateAndCompleteOneToOneMapping(array $mapping)
1579
    {
1580 296
        $mapping = $this->_validateAndCompleteAssociationMapping($mapping);
1581
1582 290
        if (isset($mapping['joinColumns']) && $mapping['joinColumns']) {
1583 209
            $mapping['isOwningSide'] = true;
1584
        }
1585
1586 290
        if ($mapping['isOwningSide']) {
1587 277
            if ( ! isset($mapping['joinColumns']) || ! $mapping['joinColumns']) {
1588
                // Apply default join column
1589 89
                $mapping['joinColumns'] = array(
1590
                    array(
1591 89
                        'name' => $this->namingStrategy->joinColumnName($mapping['fieldName'], $this->name),
0 ignored issues
show
Unused Code introduced by
The call to NamingStrategy::joinColumnName() has too many arguments starting with $this->name.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1592 89
                        'referencedColumnName' => $this->namingStrategy->referenceColumnName()
1593
                    )
1594
                );
1595
            }
1596
1597 277
            $uniqueConstraintColumns = array();
1598
1599 277
            foreach ($mapping['joinColumns'] as &$joinColumn) {
1600 277
                if ($mapping['type'] === self::ONE_TO_ONE && ! $this->isInheritanceTypeSingleTable()) {
1601 150
                    if (count($mapping['joinColumns']) == 1) {
1602 148
                        if ( ! isset($mapping['id']) || ! $mapping['id']) {
1603 148
                            $joinColumn['unique'] = true;
1604
                        }
1605
                    } else {
1606 2
                        $uniqueConstraintColumns[] = $joinColumn['name'];
1607
                    }
1608
                }
1609
1610 277
                if (empty($joinColumn['name'])) {
1611 29
                    $joinColumn['name'] = $this->namingStrategy->joinColumnName($mapping['fieldName'], $this->name);
0 ignored issues
show
Unused Code introduced by
The call to NamingStrategy::joinColumnName() has too many arguments starting with $this->name.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1612
                }
1613
1614 277
                if (empty($joinColumn['referencedColumnName'])) {
1615 5
                    $joinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName();
1616
                }
1617
1618 277
                if ($joinColumn['name'][0] === '`') {
1619 7
                    $joinColumn['name']   = trim($joinColumn['name'], '`');
1620 7
                    $joinColumn['quoted'] = true;
1621
                }
1622
1623 277
                if ($joinColumn['referencedColumnName'][0] === '`') {
1624 4
                    $joinColumn['referencedColumnName'] = trim($joinColumn['referencedColumnName'], '`');
1625 4
                    $joinColumn['quoted']               = true;
1626
                }
1627
1628 277
                $mapping['sourceToTargetKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName'];
1629 277
                $mapping['joinColumnFieldNames'][$joinColumn['name']] = isset($joinColumn['fieldName'])
1630
                    ? $joinColumn['fieldName']
1631 277
                    : $joinColumn['name'];
1632
            }
1633
1634 277
            if ($uniqueConstraintColumns) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uniqueConstraintColumns of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1635 2
                if ( ! $this->table) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->table of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1636
                    throw new RuntimeException("ClassMetadataInfo::setTable() has to be called before defining a one to one relationship.");
1637
                }
1638
1639 2
                $this->table['uniqueConstraints'][$mapping['fieldName'] . "_uniq"] = array(
1640 2
                    'columns' => $uniqueConstraintColumns
1641
                );
1642
            }
1643
1644 277
            $mapping['targetToSourceKeyColumns'] = array_flip($mapping['sourceToTargetKeyColumns']);
1645
        }
1646
1647 290
        $mapping['orphanRemoval']   = isset($mapping['orphanRemoval']) ? (bool) $mapping['orphanRemoval'] : false;
1648 290
        $mapping['isCascadeRemove'] = $mapping['orphanRemoval'] ? true : $mapping['isCascadeRemove'];
1649
1650 290
        if ($mapping['orphanRemoval']) {
1651 21
            unset($mapping['unique']);
1652
        }
1653
1654 290
        if (isset($mapping['id']) && $mapping['id'] === true && !$mapping['isOwningSide']) {
1655 2
            throw MappingException::illegalInverseIdentifierAssociation($this->name, $mapping['fieldName']);
1656
        }
1657
1658 288
        return $mapping;
1659
    }
1660
1661
    /**
1662
     * Validates & completes a one-to-many association mapping.
1663
     *
1664
     * @param array $mapping The mapping to validate and complete.
1665
     *
1666
     * @return array The validated and completed mapping.
1667
     *
1668
     * @throws MappingException
1669
     * @throws InvalidArgumentException
1670
     */
1671 128
    protected function _validateAndCompleteOneToManyMapping(array $mapping)
1672
    {
1673 128
        $mapping = $this->_validateAndCompleteAssociationMapping($mapping);
1674
1675
        // OneToMany-side MUST be inverse (must have mappedBy)
1676 127
        if ( ! isset($mapping['mappedBy'])) {
1677
            throw MappingException::oneToManyRequiresMappedBy($mapping['fieldName']);
1678
        }
1679
1680 127
        $mapping['orphanRemoval']   = isset($mapping['orphanRemoval']) ? (bool) $mapping['orphanRemoval'] : false;
1681 127
        $mapping['isCascadeRemove'] = $mapping['orphanRemoval'] ? true : $mapping['isCascadeRemove'];
1682
1683 127
        if (isset($mapping['orderBy'])) {
1684 37
            if ( ! is_array($mapping['orderBy'])) {
1685
                throw new InvalidArgumentException("'orderBy' is expected to be an array, not ".gettype($mapping['orderBy']));
1686
            }
1687
        }
1688
1689 127
        return $mapping;
1690
    }
1691
1692
    /**
1693
     * Validates & completes a many-to-many association mapping.
1694
     *
1695
     * @param array $mapping The mapping to validate & complete.
1696
     *
1697
     * @return array The validated & completed mapping.
1698
     *
1699
     * @throws \InvalidArgumentException
1700
     */
1701 149
    protected function _validateAndCompleteManyToManyMapping(array $mapping)
1702
    {
1703 149
        $mapping = $this->_validateAndCompleteAssociationMapping($mapping);
1704
1705 147
        if ($mapping['isOwningSide']) {
1706
            // owning side MUST have a join table
1707 129
            if ( ! isset($mapping['joinTable']['name'])) {
1708 22
                $mapping['joinTable']['name'] = $this->namingStrategy->joinTableName($mapping['sourceEntity'], $mapping['targetEntity'], $mapping['fieldName']);
1709
            }
1710
1711 129
            $selfReferencingEntityWithoutJoinColumns = $mapping['sourceEntity'] == $mapping['targetEntity']
1712 129
                && (! (isset($mapping['joinTable']['joinColumns']) || isset($mapping['joinTable']['inverseJoinColumns'])));
1713
1714 129
            if ( ! isset($mapping['joinTable']['joinColumns'])) {
1715 21
                $mapping['joinTable']['joinColumns'] = array(
1716
                    array(
1717 21
                        'name' => $this->namingStrategy->joinKeyColumnName($mapping['sourceEntity'], $selfReferencingEntityWithoutJoinColumns ? 'source' : null),
1718 21
                        'referencedColumnName' => $this->namingStrategy->referenceColumnName(),
1719 21
                        'onDelete' => 'CASCADE'
1720
                    )
1721
                );
1722
            }
1723
1724 129
            if ( ! isset($mapping['joinTable']['inverseJoinColumns'])) {
1725 22
                $mapping['joinTable']['inverseJoinColumns'] = array(
1726
                    array(
1727 22
                        'name' => $this->namingStrategy->joinKeyColumnName($mapping['targetEntity'], $selfReferencingEntityWithoutJoinColumns ? 'target' : null),
1728 22
                        'referencedColumnName' => $this->namingStrategy->referenceColumnName(),
1729 22
                        'onDelete' => 'CASCADE'
1730
                    )
1731
                );
1732
            }
1733
1734 129
            $mapping['joinTableColumns'] = array();
1735
1736 129
            foreach ($mapping['joinTable']['joinColumns'] as &$joinColumn) {
1737 129
                if (empty($joinColumn['name'])) {
1738 2
                    $joinColumn['name'] = $this->namingStrategy->joinKeyColumnName($mapping['sourceEntity'], $joinColumn['referencedColumnName']);
0 ignored issues
show
Documentation introduced by
$mapping['sourceEntity'] is of type array|boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1739
                }
1740
1741 129
                if (empty($joinColumn['referencedColumnName'])) {
1742 6
                    $joinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName();
1743
                }
1744
1745 129
                if ($joinColumn['name'][0] === '`') {
1746 3
                    $joinColumn['name']   = trim($joinColumn['name'], '`');
1747 3
                    $joinColumn['quoted'] = true;
1748
                }
1749
1750 129
                if ($joinColumn['referencedColumnName'][0] === '`') {
1751 3
                    $joinColumn['referencedColumnName'] = trim($joinColumn['referencedColumnName'], '`');
1752 3
                    $joinColumn['quoted']               = true;
1753
                }
1754
1755 129
                if (isset($joinColumn['onDelete']) && strtolower($joinColumn['onDelete']) == 'cascade') {
1756 30
                    $mapping['isOnDeleteCascade'] = true;
1757
                }
1758
1759 129
                $mapping['relationToSourceKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName'];
1760 129
                $mapping['joinTableColumns'][] = $joinColumn['name'];
1761
            }
1762
1763 129
            foreach ($mapping['joinTable']['inverseJoinColumns'] as &$inverseJoinColumn) {
1764 129
                if (empty($inverseJoinColumn['name'])) {
1765 2
                    $inverseJoinColumn['name'] = $this->namingStrategy->joinKeyColumnName($mapping['targetEntity'], $inverseJoinColumn['referencedColumnName']);
0 ignored issues
show
Documentation introduced by
$mapping['targetEntity'] is of type array|boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1766
                }
1767
1768 129
                if (empty($inverseJoinColumn['referencedColumnName'])) {
1769 6
                    $inverseJoinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName();
1770
                }
1771
1772 129
                if ($inverseJoinColumn['name'][0] === '`') {
1773 3
                    $inverseJoinColumn['name']   = trim($inverseJoinColumn['name'], '`');
1774 3
                    $inverseJoinColumn['quoted'] = true;
1775
                }
1776
1777 129
                if ($inverseJoinColumn['referencedColumnName'][0] === '`') {
1778 3
                    $inverseJoinColumn['referencedColumnName']  = trim($inverseJoinColumn['referencedColumnName'], '`');
1779 3
                    $inverseJoinColumn['quoted']                = true;
1780
                }
1781
1782 129
                if (isset($inverseJoinColumn['onDelete']) && strtolower($inverseJoinColumn['onDelete']) == 'cascade') {
1783 26
                    $mapping['isOnDeleteCascade'] = true;
1784
                }
1785
1786 129
                $mapping['relationToTargetKeyColumns'][$inverseJoinColumn['name']] = $inverseJoinColumn['referencedColumnName'];
1787 129
                $mapping['joinTableColumns'][] = $inverseJoinColumn['name'];
1788
            }
1789
        }
1790
1791 147
        $mapping['orphanRemoval'] = isset($mapping['orphanRemoval']) ? (bool) $mapping['orphanRemoval'] : false;
1792
1793 147
        if (isset($mapping['orderBy'])) {
1794 3
            if ( ! is_array($mapping['orderBy'])) {
1795
                throw new InvalidArgumentException("'orderBy' is expected to be an array, not ".gettype($mapping['orderBy']));
1796
            }
1797
        }
1798
1799 147
        return $mapping;
1800
    }
1801
1802
    /**
1803
     * {@inheritDoc}
1804
     */
1805 593
    public function getIdentifierFieldNames()
1806
    {
1807 593
        return $this->identifier;
1808
    }
1809
1810
    /**
1811
     * Gets the name of the single id field. Note that this only works on
1812
     * entity classes that have a single-field pk.
1813
     *
1814
     * @return string
1815
     *
1816
     * @throws MappingException If the class has a composite primary key.
1817
     */
1818 396
    public function getSingleIdentifierFieldName()
1819
    {
1820 396
        if ($this->isIdentifierComposite) {
1821 1
            throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->name);
1822
        }
1823
1824 395
        return $this->identifier[0];
1825
    }
1826
1827
    /**
1828
     * Gets the column name of the single id column. Note that this only works on
1829
     * entity classes that have a single-field pk.
1830
     *
1831
     * @return string
1832
     *
1833
     * @throws MappingException If the class has a composite primary key.
1834
     */
1835 3
    public function getSingleIdentifierColumnName()
1836
    {
1837 3
        return $this->getColumnName($this->getSingleIdentifierFieldName());
1838
    }
1839
1840
    /**
1841
     * INTERNAL:
1842
     * Sets the mapped identifier/primary key fields of this class.
1843
     * Mainly used by the ClassMetadataFactory to assign inherited identifiers.
1844
     *
1845
     * @param array $identifier
1846
     *
1847
     * @return void
1848
     */
1849 123
    public function setIdentifier(array $identifier)
1850
    {
1851 123
        $this->identifier = $identifier;
1852 123
        $this->isIdentifierComposite = (count($this->identifier) > 1);
1853 123
    }
1854
1855
    /**
1856
     * {@inheritDoc}
1857
     */
1858 61
    public function getIdentifier()
1859
    {
1860 61
        return $this->identifier;
1861
    }
1862
1863
    /**
1864
     * {@inheritDoc}
1865
     */
1866 292
    public function hasField($fieldName)
1867
    {
1868 292
        return isset($this->fieldMappings[$fieldName]);
1869
    }
1870
1871
    /**
1872
     * Gets an array containing all the column names.
1873
     *
1874
     * @param array|null $fieldNames
1875
     *
1876
     * @return array
1877
     */
1878 42
    public function getColumnNames(array $fieldNames = null)
1879
    {
1880 42
        if (null === $fieldNames) {
1881 41
            return array_keys($this->fieldNames);
1882
        }
1883
1884 1
        return array_values(array_map([$this, 'getColumnName'], $fieldNames));
1885
    }
1886
1887
    /**
1888
     * Returns an array with all the identifier column names.
1889
     *
1890
     * @return array
1891
     */
1892 322
    public function getIdentifierColumnNames()
1893
    {
1894 322
        $columnNames = array();
1895
1896 322
        foreach ($this->identifier as $idProperty) {
1897 322
            if (isset($this->fieldMappings[$idProperty])) {
1898 318
                $columnNames[] = $this->fieldMappings[$idProperty]['columnName'];
1899
1900 318
                continue;
1901
            }
1902
1903
            // Association defined as Id field
1904 22
            $joinColumns      = $this->associationMappings[$idProperty]['joinColumns'];
1905
            $assocColumnNames = array_map(function ($joinColumn) { return $joinColumn['name']; }, $joinColumns);
1906
1907 22
            $columnNames = array_merge($columnNames, $assocColumnNames);
1908
        }
1909
1910 322
        return $columnNames;
1911
    }
1912
1913
    /**
1914
     * Sets the type of Id generator to use for the mapped class.
1915
     *
1916
     * @param int $generatorType
1917
     *
1918
     * @return void
1919
     */
1920 455
    public function setIdGeneratorType($generatorType)
1921
    {
1922 455
        $this->generatorType = $generatorType;
1923 455
    }
1924
1925
    /**
1926
     * Checks whether the mapped class uses an Id generator.
1927
     *
1928
     * @return boolean TRUE if the mapped class uses an Id generator, FALSE otherwise.
1929
     */
1930 390
    public function usesIdGenerator()
1931
    {
1932 390
        return $this->generatorType != self::GENERATOR_TYPE_NONE;
1933
    }
1934
1935
    /**
1936
     * @return boolean
1937
     */
1938 1321
    public function isInheritanceTypeNone()
1939
    {
1940 1321
        return $this->inheritanceType == self::INHERITANCE_TYPE_NONE;
1941
    }
1942
1943
    /**
1944
     * Checks whether the mapped class uses the JOINED inheritance mapping strategy.
1945
     *
1946
     * @return boolean TRUE if the class participates in a JOINED inheritance mapping,
1947
     *                 FALSE otherwise.
1948
     */
1949 1049
    public function isInheritanceTypeJoined()
1950
    {
1951 1049
        return $this->inheritanceType == self::INHERITANCE_TYPE_JOINED;
1952
    }
1953
1954
    /**
1955
     * Checks whether the mapped class uses the SINGLE_TABLE inheritance mapping strategy.
1956
     *
1957
     * @return boolean TRUE if the class participates in a SINGLE_TABLE inheritance mapping,
1958
     *                 FALSE otherwise.
1959
     */
1960 1221
    public function isInheritanceTypeSingleTable()
1961
    {
1962 1221
        return $this->inheritanceType == self::INHERITANCE_TYPE_SINGLE_TABLE;
1963
    }
1964
1965
    /**
1966
     * Checks whether the mapped class uses the TABLE_PER_CLASS inheritance mapping strategy.
1967
     *
1968
     * @return boolean TRUE if the class participates in a TABLE_PER_CLASS inheritance mapping,
1969
     *                 FALSE otherwise.
1970
     */
1971 259
    public function isInheritanceTypeTablePerClass()
1972
    {
1973 259
        return $this->inheritanceType == self::INHERITANCE_TYPE_TABLE_PER_CLASS;
1974
    }
1975
1976
    /**
1977
     * Checks whether the class uses an identity column for the Id generation.
1978
     *
1979
     * @return boolean TRUE if the class uses the IDENTITY generator, FALSE otherwise.
1980
     */
1981 1061
    public function isIdGeneratorIdentity()
1982
    {
1983 1061
        return $this->generatorType == self::GENERATOR_TYPE_IDENTITY;
1984
    }
1985
1986
    /**
1987
     * Checks whether the class uses a sequence for id generation.
1988
     *
1989
     * @return boolean TRUE if the class uses the SEQUENCE generator, FALSE otherwise.
1990
     */
1991 312
    public function isIdGeneratorSequence()
1992
    {
1993 312
        return $this->generatorType == self::GENERATOR_TYPE_SEQUENCE;
1994
    }
1995
1996
    /**
1997
     * Checks whether the class uses a table for id generation.
1998
     *
1999
     * @return boolean TRUE if the class uses the TABLE generator, FALSE otherwise.
2000
     */
2001 80
    public function isIdGeneratorTable()
2002
    {
2003 80
        return $this->generatorType == self::GENERATOR_TYPE_TABLE;
2004
    }
2005
2006
    /**
2007
     * Checks whether the class has a natural identifier/pk (which means it does
2008
     * not use any Id generator.
2009
     *
2010
     * @return boolean
2011
     */
2012 73
    public function isIdentifierNatural()
2013
    {
2014 73
        return $this->generatorType == self::GENERATOR_TYPE_NONE;
2015
    }
2016
2017
    /**
2018
     * Checks whether the class use a UUID for id generation.
2019
     *
2020
     * @return boolean
2021
     */
2022
    public function isIdentifierUuid()
2023
    {
2024
        return $this->generatorType == self::GENERATOR_TYPE_UUID;
2025
    }
2026
2027
    /**
2028
     * Gets the type of a field.
2029
     *
2030
     * @param string $fieldName
2031
     *
2032
     * @return \Doctrine\DBAL\Types\Type|string|null
2033
     *
2034
     * @todo 3.0 Remove this. PersisterHelper should fix it somehow
2035
     */
2036 38
    public function getTypeOfField($fieldName)
2037
    {
2038 38
        return isset($this->fieldMappings[$fieldName])
2039 38
            ? $this->fieldMappings[$fieldName]['type']
2040 38
            : null;
2041
    }
2042
2043
    /**
2044
     * Gets the type of a column.
2045
     *
2046
     * @param string $columnName
2047
     *
2048
     * @return \Doctrine\DBAL\Types\Type|string|null
2049
     *
2050
     * @deprecated 3.0 remove this. this method is bogous and unreliable, since it cannot resolve the type of a column
2051
     *             that is derived by a referenced field on a different entity.
2052
     */
2053
    public function getTypeOfColumn($columnName)
2054
    {
2055
        return $this->getTypeOfField($this->getFieldName($columnName));
2056
    }
2057
2058
    /**
2059
     * Gets the name of the primary table.
2060
     *
2061
     * @return string
2062
     */
2063 1463
    public function getTableName()
2064
    {
2065 1463
        return $this->table['name'];
2066
    }
2067
2068
    /**
2069
     * Gets primary table's schema name.
2070
     *
2071
     * @return string|null
2072
     */
2073 13
    public function getSchemaName()
2074
    {
2075 13
        return isset($this->table['schema']) ? $this->table['schema'] : null;
2076
    }
2077
2078
    /**
2079
     * Gets the table name to use for temporary identifier tables of this class.
2080
     *
2081
     * @return string
2082
     */
2083 7
    public function getTemporaryIdTableName()
2084
    {
2085
        // replace dots with underscores because PostgreSQL creates temporary tables in a special schema
2086 7
        return str_replace('.', '_', $this->getTableName() . '_id_tmp');
2087
    }
2088
2089
    /**
2090
     * Sets the mapped subclasses of this class.
2091
     *
2092
     * @param array $subclasses The names of all mapped subclasses.
2093
     *
2094
     * @return void
2095
     */
2096 2
    public function setSubclasses(array $subclasses)
2097
    {
2098 2
        foreach ($subclasses as $subclass) {
2099 2
            $this->subClasses[] = $this->fullyQualifiedClassName($subclass);
2100
        }
2101 2
    }
2102
2103
    /**
2104
     * Sets the parent class names.
2105
     * Assumes that the class names in the passed array are in the order:
2106
     * directParent -> directParentParent -> directParentParentParent ... -> root.
2107
     *
2108
     * @param array $classNames
2109
     *
2110
     * @return void
2111
     */
2112 407
    public function setParentClasses(array $classNames)
2113
    {
2114 407
        $this->parentClasses = $classNames;
2115
2116 407
        if (count($classNames) > 0) {
2117 79
            $this->rootEntityName = array_pop($classNames);
2118
        }
2119 407
    }
2120
2121
    /**
2122
     * Sets the inheritance type used by the class and its subclasses.
2123
     *
2124
     * @param integer $type
2125
     *
2126
     * @return void
2127
     *
2128
     * @throws MappingException
2129
     */
2130 169
    public function setInheritanceType($type)
2131
    {
2132 169
        if ( ! $this->_isInheritanceType($type)) {
2133
            throw MappingException::invalidInheritanceType($this->name, $type);
2134
        }
2135
2136 169
        $this->inheritanceType = $type;
2137 169
    }
2138
2139
    /**
2140
     * Sets the association to override association mapping of property for an entity relationship.
2141
     *
2142
     * @param string $fieldName
2143
     * @param array  $overrideMapping
2144
     *
2145
     * @return void
2146
     *
2147
     * @throws MappingException
2148
     */
2149 20
    public function setAssociationOverride($fieldName, array $overrideMapping)
2150
    {
2151 20
        if ( ! isset($this->associationMappings[$fieldName])) {
2152 1
            throw MappingException::invalidOverrideFieldName($this->name, $fieldName);
2153
        }
2154
2155 19
        $mapping = $this->associationMappings[$fieldName];
2156
2157 19
        if (isset($overrideMapping['joinColumns'])) {
2158 13
            $mapping['joinColumns'] = $overrideMapping['joinColumns'];
2159
        }
2160
2161 19
        if (isset($overrideMapping['inversedBy'])) {
2162 6
            $mapping['inversedBy'] = $overrideMapping['inversedBy'];
2163
        }
2164
2165 19
        if (isset($overrideMapping['joinTable'])) {
2166 12
            $mapping['joinTable'] = $overrideMapping['joinTable'];
2167
        }
2168
2169 19
        $mapping['joinColumnFieldNames']        = null;
2170 19
        $mapping['joinTableColumns']            = null;
2171 19
        $mapping['sourceToTargetKeyColumns']    = null;
2172 19
        $mapping['relationToSourceKeyColumns']  = null;
2173 19
        $mapping['relationToTargetKeyColumns']  = null;
2174
2175 19
        switch ($mapping['type']) {
2176 19
            case self::ONE_TO_ONE:
2177 1
                $mapping = $this->_validateAndCompleteOneToOneMapping($mapping);
2178 1
                break;
2179 18
            case self::ONE_TO_MANY:
2180
                $mapping = $this->_validateAndCompleteOneToManyMapping($mapping);
2181
                break;
2182 18
            case self::MANY_TO_ONE:
2183 12
                $mapping = $this->_validateAndCompleteOneToOneMapping($mapping);
2184 12
                break;
2185 18
            case self::MANY_TO_MANY:
2186 18
                $mapping = $this->_validateAndCompleteManyToManyMapping($mapping);
2187 18
                break;
2188
        }
2189
2190 19
        $this->associationMappings[$fieldName] = $mapping;
2191 19
    }
2192
2193
    /**
2194
     * Sets the override for a mapped field.
2195
     *
2196
     * @param string $fieldName
2197
     * @param array  $overrideMapping
2198
     *
2199
     * @return void
2200
     *
2201
     * @throws MappingException
2202
     */
2203 15
    public function setAttributeOverride($fieldName, array $overrideMapping)
2204
    {
2205 15
        if ( ! isset($this->fieldMappings[$fieldName])) {
2206 1
            throw MappingException::invalidOverrideFieldName($this->name, $fieldName);
2207
        }
2208
2209 14
        $mapping = $this->fieldMappings[$fieldName];
2210
2211 14
        if (isset($mapping['id'])) {
2212 12
            $overrideMapping['id'] = $mapping['id'];
2213
        }
2214
2215 14
        if ( ! isset($overrideMapping['type']) || $overrideMapping['type'] === null) {
2216 6
            $overrideMapping['type'] = $mapping['type'];
2217
        }
2218
2219 14
        if ( ! isset($overrideMapping['fieldName']) || $overrideMapping['fieldName'] === null) {
2220 5
            $overrideMapping['fieldName'] = $mapping['fieldName'];
2221
        }
2222
2223 14
        if ($overrideMapping['type'] !== $mapping['type']) {
2224 1
            throw MappingException::invalidOverrideFieldType($this->name, $fieldName);
2225
        }
2226
2227 13
        unset($this->fieldMappings[$fieldName]);
2228 13
        unset($this->fieldNames[$mapping['columnName']]);
2229 13
        unset($this->columnNames[$mapping['fieldName']]);
2230
2231 13
        $this->_validateAndCompleteFieldMapping($overrideMapping);
2232
2233 13
        $this->fieldMappings[$fieldName] = $overrideMapping;
2234 13
    }
2235
2236
    /**
2237
     * Checks whether a mapped field is inherited from an entity superclass.
2238
     *
2239
     * @param string $fieldName
2240
     *
2241
     * @return bool TRUE if the field is inherited, FALSE otherwise.
2242
     */
2243 367
    public function isInheritedField($fieldName)
2244
    {
2245 367
        return isset($this->fieldMappings[$fieldName]['inherited']);
2246
    }
2247
2248
    /**
2249
     * Checks if this entity is the root in any entity-inheritance-hierarchy.
2250
     *
2251
     * @return bool
2252
     */
2253 406
    public function isRootEntity()
2254
    {
2255 406
        return $this->name == $this->rootEntityName;
2256
    }
2257
2258
    /**
2259
     * Checks whether a mapped association field is inherited from a superclass.
2260
     *
2261
     * @param string $fieldName
2262
     *
2263
     * @return boolean TRUE if the field is inherited, FALSE otherwise.
2264
     */
2265 346
    public function isInheritedAssociation($fieldName)
2266
    {
2267 346
        return isset($this->associationMappings[$fieldName]['inherited']);
2268
    }
2269
2270 346
    public function isInheritedEmbeddedClass($fieldName)
2271
    {
2272 346
        return isset($this->embeddedClasses[$fieldName]['inherited']);
2273
    }
2274
2275
    /**
2276
     * Sets the name of the primary table the class is mapped to.
2277
     *
2278
     * @param string $tableName The table name.
2279
     *
2280
     * @return void
2281
     *
2282
     * @deprecated Use {@link setPrimaryTable}.
2283
     */
2284
    public function setTableName($tableName)
2285
    {
2286
        $this->table['name'] = $tableName;
2287
    }
2288
2289
    /**
2290
     * Sets the primary table definition. The provided array supports the
2291
     * following structure:
2292
     *
2293
     * name => <tableName> (optional, defaults to class name)
2294
     * indexes => array of indexes (optional)
2295
     * uniqueConstraints => array of constraints (optional)
2296
     *
2297
     * If a key is omitted, the current value is kept.
2298
     *
2299
     * @param array $table The table description.
2300
     *
2301
     * @return void
2302
     */
2303 322
    public function setPrimaryTable(array $table)
2304
    {
2305 322
        if (isset($table['name'])) {
2306
            // Split schema and table name from a table name like "myschema.mytable"
2307 259
            if (strpos($table['name'], '.') !== false) {
2308 9
                list($this->table['schema'], $table['name']) = explode('.', $table['name'], 2);
2309
            }
2310
2311 259
            if ($table['name'][0] === '`') {
2312 17
                $table['name']          = trim($table['name'], '`');
2313 17
                $this->table['quoted']  = true;
2314
            }
2315
2316 259
            $this->table['name'] = $table['name'];
2317
        }
2318
2319 322
        if (isset($table['schema'])) {
2320 6
            $this->table['schema'] = $table['schema'];
2321
        }
2322
2323 322
        if (isset($table['indexes'])) {
2324 15
            $this->table['indexes'] = $table['indexes'];
2325
        }
2326
2327 322
        if (isset($table['uniqueConstraints'])) {
2328 8
            $this->table['uniqueConstraints'] = $table['uniqueConstraints'];
2329
        }
2330
2331 322
        if (isset($table['options'])) {
2332 9
            $this->table['options'] = $table['options'];
2333
        }
2334 322
    }
2335
2336
    /**
2337
     * Checks whether the given type identifies an inheritance type.
2338
     *
2339
     * @param integer $type
2340
     *
2341
     * @return boolean TRUE if the given type identifies an inheritance type, FALSe otherwise.
2342
     */
2343 169
    private function _isInheritanceType($type)
2344
    {
2345 169
        return $type == self::INHERITANCE_TYPE_NONE ||
2346 105
                $type == self::INHERITANCE_TYPE_SINGLE_TABLE ||
2347 50
                $type == self::INHERITANCE_TYPE_JOINED ||
2348 169
                $type == self::INHERITANCE_TYPE_TABLE_PER_CLASS;
2349
    }
2350
2351
    /**
2352
     * Adds a mapped field to the class.
2353
     *
2354
     * @param array $mapping The field mapping.
2355
     *
2356
     * @return void
2357
     *
2358
     * @throws MappingException
2359
     */
2360 526
    public function mapField(array $mapping)
2361
    {
2362 526
        $this->_validateAndCompleteFieldMapping($mapping);
2363 524
        $this->assertFieldNotMapped($mapping['fieldName']);
2364
2365 523
        $this->fieldMappings[$mapping['fieldName']] = $mapping;
2366 523
    }
2367
2368
    /**
2369
     * INTERNAL:
2370
     * Adds an association mapping without completing/validating it.
2371
     * This is mainly used to add inherited association mappings to derived classes.
2372
     *
2373
     * @param array $mapping
2374
     *
2375
     * @return void
2376
     *
2377
     * @throws MappingException
2378
     */
2379 48
    public function addInheritedAssociationMapping(array $mapping/*, $owningClassName = null*/)
2380
    {
2381 48
        if (isset($this->associationMappings[$mapping['fieldName']])) {
2382 1
            throw MappingException::duplicateAssociationMapping($this->name, $mapping['fieldName']);
2383
        }
2384 48
        $this->associationMappings[$mapping['fieldName']] = $mapping;
2385 48
    }
2386
2387
    /**
2388
     * INTERNAL:
2389
     * Adds a field mapping without completing/validating it.
2390
     * This is mainly used to add inherited field mappings to derived classes.
2391
     *
2392
     * @param array $fieldMapping
2393
     *
2394
     * @return void
2395
     */
2396 107
    public function addInheritedFieldMapping(array $fieldMapping)
2397
    {
2398 107
        $this->fieldMappings[$fieldMapping['fieldName']] = $fieldMapping;
2399 107
        $this->columnNames[$fieldMapping['fieldName']] = $fieldMapping['columnName'];
0 ignored issues
show
Deprecated Code introduced by
The property Doctrine\ORM\Mapping\Cla...adataInfo::$columnNames has been deprecated with message: 3.0 Remove this.

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...
2400 107
        $this->fieldNames[$fieldMapping['columnName']] = $fieldMapping['fieldName'];
2401 107
    }
2402
2403
    /**
2404
     * INTERNAL:
2405
     * Adds a named query to this class.
2406
     *
2407
     * @param array $queryMapping
2408
     *
2409
     * @return void
2410
     *
2411
     * @throws MappingException
2412
     */
2413 29
    public function addNamedQuery(array $queryMapping)
2414
    {
2415 29
        if (!isset($queryMapping['name'])) {
2416 2
            throw MappingException::nameIsMandatoryForQueryMapping($this->name);
2417
        }
2418
2419 27
        if (isset($this->namedQueries[$queryMapping['name']])) {
2420 1
            throw MappingException::duplicateQueryMapping($this->name, $queryMapping['name']);
2421
        }
2422
2423 27
        if (!isset($queryMapping['query'])) {
2424
            throw MappingException::emptyQueryMapping($this->name, $queryMapping['name']);
2425
        }
2426
2427 27
        $name   = $queryMapping['name'];
2428 27
        $query  = $queryMapping['query'];
2429 27
        $dql    = str_replace('__CLASS__', $this->name, $query);
2430
2431 27
        $this->namedQueries[$name] = array(
2432 27
            'name'  => $name,
2433 27
            'query' => $query,
2434 27
            'dql'   => $dql,
2435
        );
2436 27
    }
2437
2438
    /**
2439
     * INTERNAL:
2440
     * Adds a named native query to this class.
2441
     *
2442
     * @param array $queryMapping
2443
     *
2444
     * @return void
2445
     *
2446
     * @throws MappingException
2447
     */
2448 39
    public function addNamedNativeQuery(array $queryMapping)
2449
    {
2450 39
        if (!isset($queryMapping['name'])) {
2451
            throw MappingException::nameIsMandatoryForQueryMapping($this->name);
2452
        }
2453
2454 39
        if (isset($this->namedNativeQueries[$queryMapping['name']])) {
2455 1
            throw MappingException::duplicateQueryMapping($this->name, $queryMapping['name']);
2456
        }
2457
2458 39
        if (!isset($queryMapping['query'])) {
2459
            throw MappingException::emptyQueryMapping($this->name, $queryMapping['name']);
2460
        }
2461
2462 39
        if (!isset($queryMapping['resultClass']) && !isset($queryMapping['resultSetMapping'])) {
2463
            throw MappingException::missingQueryMapping($this->name, $queryMapping['name']);
2464
        }
2465
2466 39
        $queryMapping['isSelfClass'] = false;
2467
2468 39
        if (isset($queryMapping['resultClass'])) {
2469 37
            if ($queryMapping['resultClass'] === '__CLASS__') {
2470
2471 11
                $queryMapping['isSelfClass'] = true;
2472 11
                $queryMapping['resultClass'] = $this->name;
2473
            }
2474
2475 37
            $queryMapping['resultClass'] = $this->fullyQualifiedClassName($queryMapping['resultClass']);
0 ignored issues
show
Bug introduced by
It seems like $queryMapping['resultClass'] can also be of type boolean; however, Doctrine\ORM\Mapping\Cla...llyQualifiedClassName() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2476 37
            $queryMapping['resultClass'] = ltrim($queryMapping['resultClass'], '\\');
2477
        }
2478
2479 39
        $this->namedNativeQueries[$queryMapping['name']] = $queryMapping;
2480 39
    }
2481
2482
    /**
2483
     * INTERNAL:
2484
     * Adds a sql result set mapping to this class.
2485
     *
2486
     * @param array $resultMapping
2487
     *
2488
     * @return void
2489
     *
2490
     * @throws MappingException
2491
     */
2492 39
    public function addSqlResultSetMapping(array $resultMapping)
2493
    {
2494 39
        if (!isset($resultMapping['name'])) {
2495
            throw MappingException::nameIsMandatoryForSqlResultSetMapping($this->name);
2496
        }
2497
2498 39
        if (isset($this->sqlResultSetMappings[$resultMapping['name']])) {
2499 1
            throw MappingException::duplicateResultSetMapping($this->name, $resultMapping['name']);
2500
        }
2501
2502 39
        if (isset($resultMapping['entities'])) {
2503 39
            foreach ($resultMapping['entities'] as $key => $entityResult) {
2504 39
                if (!isset($entityResult['entityClass'])) {
2505 1
                    throw MappingException::missingResultSetMappingEntity($this->name, $resultMapping['name']);
2506
                }
2507
2508 38
                $entityResult['isSelfClass'] = false;
2509 38
                if ($entityResult['entityClass'] === '__CLASS__') {
2510
2511 20
                    $entityResult['isSelfClass'] = true;
2512 20
                    $entityResult['entityClass'] = $this->name;
2513
2514
                }
2515
2516 38
                $entityResult['entityClass'] = $this->fullyQualifiedClassName($entityResult['entityClass']);
0 ignored issues
show
Bug introduced by
It seems like $entityResult['entityClass'] can also be of type boolean; however, Doctrine\ORM\Mapping\Cla...llyQualifiedClassName() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
2517
2518 38
                $resultMapping['entities'][$key]['entityClass'] = ltrim($entityResult['entityClass'], '\\');
2519 38
                $resultMapping['entities'][$key]['isSelfClass'] = $entityResult['isSelfClass'];
2520
2521 38
                if (isset($entityResult['fields'])) {
2522 34
                    foreach ($entityResult['fields'] as $k => $field) {
0 ignored issues
show
Bug introduced by
The expression $entityResult['fields'] of type boolean|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2523 34
                        if (!isset($field['name'])) {
2524
                            throw MappingException::missingResultSetMappingFieldName($this->name, $resultMapping['name']);
2525
                        }
2526
2527 34
                        if (!isset($field['column'])) {
2528 14
                            $fieldName = $field['name'];
2529 14
                            if (strpos($fieldName, '.')) {
2530 9
                                list(, $fieldName) = explode('.', $fieldName);
2531
                            }
2532
2533 38
                            $resultMapping['entities'][$key]['fields'][$k]['column'] = $fieldName;
2534
                        }
2535
                    }
2536
                }
2537
            }
2538
        }
2539
2540 38
        $this->sqlResultSetMappings[$resultMapping['name']] = $resultMapping;
2541 38
    }
2542
2543
    /**
2544
     * Adds a one-to-one mapping.
2545
     *
2546
     * @param array $mapping The mapping.
2547
     *
2548
     * @return void
2549
     */
2550 167
    public function mapOneToOne(array $mapping)
2551
    {
2552 167
        $mapping['type'] = self::ONE_TO_ONE;
2553
2554 167
        $mapping = $this->_validateAndCompleteOneToOneMapping($mapping);
2555
2556 164
        $this->_storeAssociationMapping($mapping);
2557 163
    }
2558
2559
    /**
2560
     * Adds a one-to-many mapping.
2561
     *
2562
     * @param array $mapping The mapping.
2563
     *
2564
     * @return void
2565
     */
2566 128
    public function mapOneToMany(array $mapping)
2567
    {
2568 128
        $mapping['type'] = self::ONE_TO_MANY;
2569
2570 128
        $mapping = $this->_validateAndCompleteOneToManyMapping($mapping);
2571
2572 127
        $this->_storeAssociationMapping($mapping);
2573 127
    }
2574
2575
    /**
2576
     * Adds a many-to-one mapping.
2577
     *
2578
     * @param array $mapping The mapping.
2579
     *
2580
     * @return void
2581
     */
2582 161
    public function mapManyToOne(array $mapping)
2583
    {
2584 161
        $mapping['type'] = self::MANY_TO_ONE;
2585
2586
        // A many-to-one mapping is essentially a one-one backreference
2587 161
        $mapping = $this->_validateAndCompleteOneToOneMapping($mapping);
2588
2589 156
        $this->_storeAssociationMapping($mapping);
2590 156
    }
2591
2592
    /**
2593
     * Adds a many-to-many mapping.
2594
     *
2595
     * @param array $mapping The mapping.
2596
     *
2597
     * @return void
2598
     */
2599 149
    public function mapManyToMany(array $mapping)
2600
    {
2601 149
        $mapping['type'] = self::MANY_TO_MANY;
2602
2603 149
        $mapping = $this->_validateAndCompleteManyToManyMapping($mapping);
2604
2605 147
        $this->_storeAssociationMapping($mapping);
2606 147
    }
2607
2608
    /**
2609
     * Stores the association mapping.
2610
     *
2611
     * @param array $assocMapping
2612
     *
2613
     * @return void
2614
     *
2615
     * @throws MappingException
2616
     */
2617 338
    protected function _storeAssociationMapping(array $assocMapping)
2618
    {
2619 338
        $sourceFieldName = $assocMapping['fieldName'];
2620
2621 338
        $this->assertFieldNotMapped($sourceFieldName);
2622
2623 337
        $this->associationMappings[$sourceFieldName] = $assocMapping;
2624 337
    }
2625
2626
    /**
2627
     * Registers a custom repository class for the entity class.
2628
     *
2629
     * @param string $repositoryClassName The class name of the custom mapper.
2630
     *
2631
     * @return void
2632
     */
2633 62
    public function setCustomRepositoryClass($repositoryClassName)
2634
    {
2635 62
        $this->customRepositoryClassName = $this->fullyQualifiedClassName($repositoryClassName);
2636 62
    }
2637
2638
    /**
2639
     * Dispatches the lifecycle event of the given entity to the registered
2640
     * lifecycle callbacks and lifecycle listeners.
2641
     *
2642
     * @deprecated Deprecated since version 2.4 in favor of \Doctrine\ORM\Event\ListenersInvoker
2643
     *
2644
     * @param string $lifecycleEvent The lifecycle event.
2645
     * @param object $entity         The Entity on which the event occurred.
2646
     *
2647
     * @return void
2648
     */
2649
    public function invokeLifecycleCallbacks($lifecycleEvent, $entity)
2650
    {
2651
        foreach ($this->lifecycleCallbacks[$lifecycleEvent] as $callback) {
2652
            $entity->$callback();
2653
        }
2654
    }
2655
2656
    /**
2657
     * Whether the class has any attached lifecycle listeners or callbacks for a lifecycle event.
2658
     *
2659
     * @param string $lifecycleEvent
2660
     *
2661
     * @return boolean
2662
     */
2663
    public function hasLifecycleCallbacks($lifecycleEvent)
2664
    {
2665
        return isset($this->lifecycleCallbacks[$lifecycleEvent]);
2666
    }
2667
2668
    /**
2669
     * Gets the registered lifecycle callbacks for an event.
2670
     *
2671
     * @param string $event
2672
     *
2673
     * @return array
2674
     */
2675
    public function getLifecycleCallbacks($event)
2676
    {
2677
        return isset($this->lifecycleCallbacks[$event]) ? $this->lifecycleCallbacks[$event] : array();
2678
    }
2679
2680
    /**
2681
     * Adds a lifecycle callback for entities of this class.
2682
     *
2683
     * @param string $callback
2684
     * @param string $event
2685
     *
2686
     * @return void
2687
     */
2688 41
    public function addLifecycleCallback($callback, $event)
2689
    {
2690 41
        if (isset($this->lifecycleCallbacks[$event]) && in_array($callback, $this->lifecycleCallbacks[$event])) {
2691 3
            return;
2692
        }
2693
2694 41
        $this->lifecycleCallbacks[$event][] = $callback;
2695 41
    }
2696
2697
    /**
2698
     * Sets the lifecycle callbacks for entities of this class.
2699
     * Any previously registered callbacks are overwritten.
2700
     *
2701
     * @param array $callbacks
2702
     *
2703
     * @return void
2704
     */
2705 122
    public function setLifecycleCallbacks(array $callbacks)
2706
    {
2707 122
        $this->lifecycleCallbacks = $callbacks;
2708 122
    }
2709
2710
    /**
2711
     * Adds a entity listener for entities of this class.
2712
     *
2713
     * @param string $eventName The entity lifecycle event.
2714
     * @param string $class     The listener class.
2715
     * @param string $method    The listener callback method.
2716
     *
2717
     * @throws \Doctrine\ORM\Mapping\MappingException
2718
     */
2719 35
    public function addEntityListener($eventName, $class, $method)
2720
    {
2721 35
        $class    = $this->fullyQualifiedClassName($class);
2722
2723
        $listener = array(
2724 35
            'class'  => $class,
2725 35
            'method' => $method,
2726
        );
2727
2728 35
        if ( ! class_exists($class)) {
2729 1
            throw MappingException::entityListenerClassNotFound($class, $this->name);
2730
        }
2731
2732 34
        if ( ! method_exists($class, $method)) {
2733 1
            throw MappingException::entityListenerMethodNotFound($class, $method, $this->name);
2734
        }
2735
2736 33
        if (isset($this->entityListeners[$eventName]) && in_array($listener, $this->entityListeners[$eventName])) {
2737 1
            throw MappingException::duplicateEntityListener($class, $method, $this->name);
2738
        }
2739
2740 33
        $this->entityListeners[$eventName][] = $listener;
2741 33
    }
2742
2743
    /**
2744
     * Sets the discriminator column definition.
2745
     *
2746
     * @param array $columnDef
2747
     *
2748
     * @return void
2749
     *
2750
     * @throws MappingException
2751
     *
2752
     * @see getDiscriminatorColumn()
2753
     */
2754 163
    public function setDiscriminatorColumn($columnDef)
2755
    {
2756 163
        if ($columnDef !== null) {
2757 109
            if ( ! isset($columnDef['name'])) {
2758 1
                throw MappingException::nameIsMandatoryForDiscriminatorColumns($this->name);
2759
            }
2760
2761 108
            if (isset($this->fieldNames[$columnDef['name']])) {
2762 1
                throw MappingException::duplicateColumnName($this->name, $columnDef['name']);
2763
            }
2764
2765 107
            if ( ! isset($columnDef['fieldName'])) {
2766 102
                $columnDef['fieldName'] = $columnDef['name'];
2767
            }
2768
2769 107
            if ( ! isset($columnDef['type'])) {
2770 2
                $columnDef['type'] = "string";
2771
            }
2772
2773 107
            if (in_array($columnDef['type'], array("boolean", "array", "object", "datetime", "time", "date"))) {
2774
                throw MappingException::invalidDiscriminatorColumnType($this->name, $columnDef['type']);
2775
            }
2776
2777 107
            $this->discriminatorColumn = $columnDef;
2778
        }
2779 161
    }
2780
2781
    /**
2782
     * Sets the discriminator values used by this class.
2783
     * Used for JOINED and SINGLE_TABLE inheritance mapping strategies.
2784
     *
2785
     * @param array $map
2786
     *
2787
     * @return void
2788
     */
2789 156
    public function setDiscriminatorMap(array $map)
2790
    {
2791 156
        foreach ($map as $value => $className) {
2792 103
            $this->addDiscriminatorMapClass($value, $className);
2793
        }
2794 156
    }
2795
2796
    /**
2797
     * Adds one entry of the discriminator map with a new class and corresponding name.
2798
     *
2799
     * @param string $name
2800
     * @param string $className
2801
     *
2802
     * @return void
2803
     *
2804
     * @throws MappingException
2805
     */
2806 104
    public function addDiscriminatorMapClass($name, $className)
2807
    {
2808 104
        $className = $this->fullyQualifiedClassName($className);
2809 104
        $className = ltrim($className, '\\');
2810
2811 104
        $this->discriminatorMap[$name] = $className;
2812
2813 104
        if ($this->name === $className) {
2814 75
            $this->discriminatorValue = $name;
2815
2816 75
            return;
2817
        }
2818
2819 103
        if ( ! (class_exists($className) || interface_exists($className))) {
2820
            throw MappingException::invalidClassInDiscriminatorMap($className, $this->name);
2821
        }
2822
2823 103
        if (is_subclass_of($className, $this->name) && ! in_array($className, $this->subClasses)) {
2824 94
            $this->subClasses[] = $className;
2825
        }
2826 103
    }
2827
2828
    /**
2829
     * Checks whether the class has a named query with the given query name.
2830
     *
2831
     * @param string $queryName
2832
     *
2833
     * @return boolean
2834
     */
2835 1
    public function hasNamedQuery($queryName)
2836
    {
2837 1
        return isset($this->namedQueries[$queryName]);
2838
    }
2839
2840
    /**
2841
     * Checks whether the class has a named native query with the given query name.
2842
     *
2843
     * @param string $queryName
2844
     *
2845
     * @return boolean
2846
     */
2847 1
    public function hasNamedNativeQuery($queryName)
2848
    {
2849 1
        return isset($this->namedNativeQueries[$queryName]);
2850
    }
2851
2852
    /**
2853
     * Checks whether the class has a named native query with the given query name.
2854
     *
2855
     * @param string $name
2856
     *
2857
     * @return boolean
2858
     */
2859 1
    public function hasSqlResultSetMapping($name)
2860
    {
2861 1
        return isset($this->sqlResultSetMappings[$name]);
2862
    }
2863
2864
    /**
2865
     * {@inheritDoc}
2866
     */
2867 341
    public function hasAssociation($fieldName)
2868
    {
2869 341
        return isset($this->associationMappings[$fieldName]);
2870
    }
2871
2872
    /**
2873
     * {@inheritDoc}
2874
     */
2875 1
    public function isSingleValuedAssociation($fieldName)
2876
    {
2877 1
        return isset($this->associationMappings[$fieldName])
2878 1
            && ($this->associationMappings[$fieldName]['type'] & self::TO_ONE);
2879
    }
2880
2881
    /**
2882
     * {@inheritDoc}
2883
     */
2884 1024
    public function isCollectionValuedAssociation($fieldName)
2885
    {
2886 1024
        return isset($this->associationMappings[$fieldName])
2887 1024
            && ! ($this->associationMappings[$fieldName]['type'] & self::TO_ONE);
2888
    }
2889
2890
    /**
2891
     * Is this an association that only has a single join column?
2892
     *
2893
     * @param string $fieldName
2894
     *
2895
     * @return bool
2896
     */
2897 35
    public function isAssociationWithSingleJoinColumn($fieldName)
2898
    {
2899 35
        return isset($this->associationMappings[$fieldName])
2900 35
            && isset($this->associationMappings[$fieldName]['joinColumns'][0])
2901 35
            && ! isset($this->associationMappings[$fieldName]['joinColumns'][1]);
2902
    }
2903
2904
    /**
2905
     * Returns the single association join column (if any).
2906
     *
2907
     * @param string $fieldName
2908
     *
2909
     * @return string
2910
     *
2911
     * @throws MappingException
2912
     */
2913 9
    public function getSingleAssociationJoinColumnName($fieldName)
2914
    {
2915 9
        if ( ! $this->isAssociationWithSingleJoinColumn($fieldName)) {
2916
            throw MappingException::noSingleAssociationJoinColumnFound($this->name, $fieldName);
2917
        }
2918
2919 9
        return $this->associationMappings[$fieldName]['joinColumns'][0]['name'];
2920
    }
2921
2922
    /**
2923
     * Returns the single association referenced join column name (if any).
2924
     *
2925
     * @param string $fieldName
2926
     *
2927
     * @return string
2928
     *
2929
     * @throws MappingException
2930
     */
2931 9
    public function getSingleAssociationReferencedJoinColumnName($fieldName)
2932
    {
2933 9
        if ( ! $this->isAssociationWithSingleJoinColumn($fieldName)) {
2934
            throw MappingException::noSingleAssociationJoinColumnFound($this->name, $fieldName);
2935
        }
2936
2937 9
        return $this->associationMappings[$fieldName]['joinColumns'][0]['referencedColumnName'];
2938
    }
2939
2940
    /**
2941
     * Used to retrieve a fieldname for either field or association from a given column.
2942
     *
2943
     * This method is used in foreign-key as primary-key contexts.
2944
     *
2945
     * @param string $columnName
2946
     *
2947
     * @return string
2948
     *
2949
     * @throws MappingException
2950
     */
2951 633
    public function getFieldForColumn($columnName)
2952
    {
2953 633
        if (isset($this->fieldNames[$columnName])) {
2954 633
            return $this->fieldNames[$columnName];
2955
        } else {
2956 33
            foreach ($this->associationMappings as $assocName => $mapping) {
2957 33
                if ($this->isAssociationWithSingleJoinColumn($assocName) &&
2958 33
                    $this->associationMappings[$assocName]['joinColumns'][0]['name'] == $columnName) {
2959
2960 33
                    return $assocName;
2961
                }
2962
            }
2963
2964
            throw MappingException::noFieldNameFoundForColumn($this->name, $columnName);
2965
        }
2966
    }
2967
2968
    /**
2969
     * Sets the ID generator used to generate IDs for instances of this class.
2970
     *
2971
     * @param \Doctrine\ORM\Id\AbstractIdGenerator $generator
2972
     *
2973
     * @return void
2974
     */
2975 409
    public function setIdGenerator($generator)
2976
    {
2977 409
        $this->idGenerator = $generator;
2978 409
    }
2979
2980
    /**
2981
     * Sets definition.
2982
     *
2983
     * @param array $definition
2984
     *
2985
     * @return void
2986
     */
2987 12
    public function setCustomGeneratorDefinition(array $definition)
2988
    {
2989 12
        $this->customGeneratorDefinition = $definition;
2990 12
    }
2991
2992
    /**
2993
     * Sets the definition of the sequence ID generator for this class.
2994
     *
2995
     * The definition must have the following structure:
2996
     * <code>
2997
     * array(
2998
     *     'sequenceName'   => 'name',
2999
     *     'allocationSize' => 20,
3000
     *     'initialValue'   => 1
3001
     *     'quoted'         => 1
3002
     * )
3003
     * </code>
3004
     *
3005
     * @param array $definition
3006
     *
3007
     * @return void
3008
     *
3009
     * @throws MappingException
3010
     */
3011 23
    public function setSequenceGeneratorDefinition(array $definition)
3012
    {
3013 23
        if ( ! isset($definition['sequenceName'])) {
3014 1
            throw MappingException::missingSequenceName($this->name);
3015
        }
3016
3017 22
        if ($definition['sequenceName'][0] == '`') {
3018 1
            $definition['sequenceName']   = trim($definition['sequenceName'], '`');
3019 1
            $definition['quoted'] = true;
3020
        }
3021
3022 22
        $this->sequenceGeneratorDefinition = $definition;
3023 22
    }
3024
3025
    /**
3026
     * Sets the version field mapping used for versioning. Sets the default
3027
     * value to use depending on the column type.
3028
     *
3029
     * @param array $mapping The version field mapping array.
3030
     *
3031
     * @return void
3032
     *
3033
     * @throws MappingException
3034
     */
3035 25
    public function setVersionMapping(array &$mapping)
3036
    {
3037 25
        $this->isVersioned = true;
3038 25
        $this->versionField = $mapping['fieldName'];
3039
3040 25
        if ( ! isset($mapping['default'])) {
3041 25
            if (in_array($mapping['type'], array('integer', 'bigint', 'smallint'))) {
3042 24
                $mapping['default'] = 1;
3043 2
            } else if ($mapping['type'] == 'datetime') {
3044 1
                $mapping['default'] = 'CURRENT_TIMESTAMP';
3045
            } else {
3046 1
                throw MappingException::unsupportedOptimisticLockingType($this->name, $mapping['fieldName'], $mapping['type']);
3047
            }
3048
        }
3049 24
    }
3050
3051
    /**
3052
     * Sets whether this class is to be versioned for optimistic locking.
3053
     *
3054
     * @param boolean $bool
3055
     *
3056
     * @return void
3057
     */
3058 122
    public function setVersioned($bool)
3059
    {
3060 122
        $this->isVersioned = $bool;
3061 122
    }
3062
3063
    /**
3064
     * Sets the name of the field that is to be used for versioning if this class is
3065
     * versioned for optimistic locking.
3066
     *
3067
     * @param string $versionField
3068
     *
3069
     * @return void
3070
     */
3071 122
    public function setVersionField($versionField)
3072
    {
3073 122
        $this->versionField = $versionField;
3074 122
    }
3075
3076
    /**
3077
     * Marks this class as read only, no change tracking is applied to it.
3078
     *
3079
     * @return void
3080
     */
3081 3
    public function markReadOnly()
3082
    {
3083 3
        $this->isReadOnly = true;
3084 3
    }
3085
3086
    /**
3087
     * {@inheritDoc}
3088
     */
3089
    public function getFieldNames()
3090
    {
3091
        return array_keys($this->fieldMappings);
3092
    }
3093
3094
    /**
3095
     * {@inheritDoc}
3096
     */
3097
    public function getAssociationNames()
3098
    {
3099
        return array_keys($this->associationMappings);
3100
    }
3101
3102
    /**
3103
     * {@inheritDoc}
3104
     *
3105
     * @throws InvalidArgumentException
3106
     */
3107 1
    public function getAssociationTargetClass($assocName)
3108
    {
3109 1
        if ( ! isset($this->associationMappings[$assocName])) {
3110
            throw new InvalidArgumentException("Association name expected, '" . $assocName ."' is not an association.");
3111
        }
3112
3113 1
        return $this->associationMappings[$assocName]['targetEntity'];
3114
    }
3115
3116
    /**
3117
     * {@inheritDoc}
3118
     */
3119 703
    public function getName()
3120
    {
3121 703
        return $this->name;
3122
    }
3123
3124
    /**
3125
     * Gets the (possibly quoted) identifier column names for safe use in an SQL statement.
3126
     *
3127
     * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy
3128
     *
3129
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
3130
     *
3131
     * @return array
3132
     */
3133
    public function getQuotedIdentifierColumnNames($platform)
3134
    {
3135
        $quotedColumnNames = array();
3136
3137
        foreach ($this->identifier as $idProperty) {
3138
            if (isset($this->fieldMappings[$idProperty])) {
3139
                $quotedColumnNames[] = isset($this->fieldMappings[$idProperty]['quoted'])
3140
                    ? $platform->quoteIdentifier($this->fieldMappings[$idProperty]['columnName'])
3141
                    : $this->fieldMappings[$idProperty]['columnName'];
3142
3143
                continue;
3144
            }
3145
3146
            // Association defined as Id field
3147
            $joinColumns            = $this->associationMappings[$idProperty]['joinColumns'];
3148
            $assocQuotedColumnNames = array_map(
3149
                function ($joinColumn) use ($platform) {
3150
                    return isset($joinColumn['quoted'])
3151
                        ? $platform->quoteIdentifier($joinColumn['name'])
3152
                        : $joinColumn['name'];
3153
                },
3154
                $joinColumns
3155
            );
3156
3157
            $quotedColumnNames = array_merge($quotedColumnNames, $assocQuotedColumnNames);
3158
        }
3159
3160
        return $quotedColumnNames;
3161
    }
3162
3163
    /**
3164
     * Gets the (possibly quoted) column name of a mapped field for safe use  in an SQL statement.
3165
     *
3166
     * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy
3167
     *
3168
     * @param string                                    $field
3169
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
3170
     *
3171
     * @return string
3172
     */
3173
    public function getQuotedColumnName($field, $platform)
3174
    {
3175
        return isset($this->fieldMappings[$field]['quoted'])
3176
            ? $platform->quoteIdentifier($this->fieldMappings[$field]['columnName'])
3177
            : $this->fieldMappings[$field]['columnName'];
3178
    }
3179
3180
    /**
3181
     * Gets the (possibly quoted) primary table name of this class for safe use in an SQL statement.
3182
     *
3183
     * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy
3184
     *
3185
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
3186
     *
3187
     * @return string
3188
     */
3189
    public function getQuotedTableName($platform)
3190
    {
3191
        return isset($this->table['quoted'])
3192
            ? $platform->quoteIdentifier($this->table['name'])
3193
            : $this->table['name'];
3194
    }
3195
3196
    /**
3197
     * Gets the (possibly quoted) name of the join table.
3198
     *
3199
     * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy
3200
     *
3201
     * @param array                                     $assoc
3202
     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
3203
     *
3204
     * @return string
3205
     */
3206
    public function getQuotedJoinTableName(array $assoc, $platform)
3207
    {
3208
        return isset($assoc['joinTable']['quoted'])
3209
            ? $platform->quoteIdentifier($assoc['joinTable']['name'])
3210
            : $assoc['joinTable']['name'];
3211
    }
3212
3213
    /**
3214
     * {@inheritDoc}
3215
     */
3216 12
    public function isAssociationInverseSide($fieldName)
3217
    {
3218 12
        return isset($this->associationMappings[$fieldName])
3219 12
            && ! $this->associationMappings[$fieldName]['isOwningSide'];
3220
    }
3221
3222
    /**
3223
     * {@inheritDoc}
3224
     */
3225
    public function getAssociationMappedByTargetField($fieldName)
3226
    {
3227
        return $this->associationMappings[$fieldName]['mappedBy'];
3228
    }
3229
3230
    /**
3231
     * @param string $targetClass
3232
     *
3233
     * @return array
3234
     */
3235 2
    public function getAssociationsByTargetClass($targetClass)
3236
    {
3237 2
        $relations = array();
3238
3239 2
        foreach ($this->associationMappings as $mapping) {
3240 2
            if ($mapping['targetEntity'] == $targetClass) {
3241 2
                $relations[$mapping['fieldName']] = $mapping;
3242
            }
3243
        }
3244
3245 2
        return $relations;
3246
    }
3247
3248
    /**
3249
     * @param  string|null $className
3250
     *
3251
     * @return string|null null if the input value is null
3252
     */
3253 475
    public function fullyQualifiedClassName($className)
3254
    {
3255 475
        if (empty($className)) {
3256 46
            return $className;
3257
        }
3258
3259 459
        if ($className !== null && strpos($className, '\\') === false && strlen($this->namespace) > 0) {
3260 348
            return $this->namespace . '\\' . $className;
3261
        }
3262
3263 229
        return $className;
3264
    }
3265
3266
    /**
3267
     * @param string $name
3268
     *
3269
     * @return mixed
3270
     */
3271 2
    public function getMetadataValue($name)
3272
    {
3273
3274 2
        if (isset($this->$name)) {
3275 2
            return $this->$name;
3276
        }
3277
3278
        return null;
3279
    }
3280
3281
    /**
3282
     * Map Embedded Class
3283
     *
3284
     * @param array $mapping
3285
     *
3286
     * @throws MappingException
3287
     * @return void
3288
     */
3289 26
    public function mapEmbedded(array $mapping)
3290
    {
3291 26
        $this->assertFieldNotMapped($mapping['fieldName']);
3292
3293 26
        $this->embeddedClasses[$mapping['fieldName']] = array(
3294 26
            'class' => $this->fullyQualifiedClassName($mapping['class']),
3295 26
            'columnPrefix' => $mapping['columnPrefix'],
3296 26
            'declaredField' => isset($mapping['declaredField']) ? $mapping['declaredField'] : null,
3297 26
            'originalField' => isset($mapping['originalField']) ? $mapping['originalField'] : null,
3298
        );
3299 26
    }
3300
3301
    /**
3302
     * Inline the embeddable class
3303
     *
3304
     * @param string            $property
3305
     * @param ClassMetadataInfo $embeddable
3306
     */
3307 10
    public function inlineEmbeddable($property, ClassMetadataInfo $embeddable)
3308
    {
3309 10
        foreach ($embeddable->fieldMappings as $fieldMapping) {
3310 10
            $fieldMapping['originalClass'] = isset($fieldMapping['originalClass'])
3311 4
                ? $fieldMapping['originalClass']
3312 10
                : $embeddable->name;
3313 10
            $fieldMapping['declaredField'] = isset($fieldMapping['declaredField'])
3314 4
                ? $property . '.' . $fieldMapping['declaredField']
3315 10
                : $property;
3316 10
            $fieldMapping['originalField'] = isset($fieldMapping['originalField'])
3317 4
                ? $fieldMapping['originalField']
3318 10
                : $fieldMapping['fieldName'];
3319 10
            $fieldMapping['fieldName'] = $property . "." . $fieldMapping['fieldName'];
3320
3321 10
            if (! empty($this->embeddedClasses[$property]['columnPrefix'])) {
3322 2
                $fieldMapping['columnName'] = $this->embeddedClasses[$property]['columnPrefix'] . $fieldMapping['columnName'];
3323 9
            } elseif ($this->embeddedClasses[$property]['columnPrefix'] !== false) {
3324 6
                $fieldMapping['columnName'] = $this->namingStrategy
3325 6
                    ->embeddedFieldToColumnName(
3326
                        $property,
3327 6
                        $fieldMapping['columnName'],
3328 6
                        $this->reflClass->name,
3329 6
                        $embeddable->reflClass->name
3330
                    );
3331
            }
3332
3333 10
            $this->mapField($fieldMapping);
3334
        }
3335 10
    }
3336
3337
    /**
3338
     * @param string $fieldName
3339
     * @throws MappingException
3340
     */
3341 561
    private function assertFieldNotMapped($fieldName)
3342
    {
3343 561
        if (isset($this->fieldMappings[$fieldName]) ||
3344 561
            isset($this->associationMappings[$fieldName]) ||
3345 561
            isset($this->embeddedClasses[$fieldName])) {
3346
3347 2
            throw MappingException::duplicateFieldMapping($this->name, $fieldName);
3348
        }
3349 561
    }
3350
3351
    /**
3352
     * Gets the sequence name based on class metadata.
3353
     *
3354
     * @param AbstractPlatform $platform
3355
     * @return string
3356
     *
3357
     * @todo Sequence names should be computed in DBAL depending on the platform
3358
     */
3359 3
    public function getSequenceName(AbstractPlatform $platform)
3360
    {
3361 3
        $sequencePrefix = $this->getSequencePrefix($platform);
3362 3
        $columnName     = $this->getSingleIdentifierColumnName();
3363 3
        $sequenceName   = $sequencePrefix . '_' . $columnName . '_seq';
3364
3365 3
        return $sequenceName;
3366
    }
3367
3368
    /**
3369
     * Gets the sequence name prefix based on class metadata.
3370
     *
3371
     * @param AbstractPlatform $platform
3372
     * @return string
3373
     *
3374
     * @todo Sequence names should be computed in DBAL depending on the platform
3375
     */
3376 3
    public function getSequencePrefix(AbstractPlatform $platform)
3377
    {
3378 3
        $tableName      = $this->getTableName();
3379 3
        $sequencePrefix = $tableName;
3380
3381
        // Prepend the schema name to the table name if there is one
3382 3
        if ($schemaName = $this->getSchemaName()) {
3383 3
            $sequencePrefix = $schemaName . '.' . $tableName;
3384
3385 3
            if ( ! $platform->supportsSchemas() && $platform->canEmulateSchemas()) {
3386 3
                $sequencePrefix = $schemaName . '__' . $tableName;
3387
            }
3388
        }
3389
3390 3
        return $sequencePrefix;
3391
    }
3392
}
3393