vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php line 984

Open in your IDE?
  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. namespace Doctrine\ORM\Mapping;
  20. use BadMethodCallException;
  21. use Doctrine\DBAL\Platforms\AbstractPlatform;
  22. use Doctrine\DBAL\Types\Type;
  23. use Doctrine\Instantiator\Instantiator;
  24. use Doctrine\Instantiator\InstantiatorInterface;
  25. use Doctrine\ORM\Cache\CacheException;
  26. use Doctrine\ORM\Id\AbstractIdGenerator;
  27. use Doctrine\Persistence\Mapping\ClassMetadata;
  28. use Doctrine\Persistence\Mapping\ReflectionService;
  29. use InvalidArgumentException;
  30. use ReflectionClass;
  31. use ReflectionProperty;
  32. use RuntimeException;
  33. use function array_diff;
  34. use function array_flip;
  35. use function array_intersect;
  36. use function array_keys;
  37. use function array_map;
  38. use function array_merge;
  39. use function array_pop;
  40. use function array_values;
  41. use function class_exists;
  42. use function count;
  43. use function explode;
  44. use function gettype;
  45. use function in_array;
  46. use function interface_exists;
  47. use function is_array;
  48. use function is_subclass_of;
  49. use function ltrim;
  50. use function method_exists;
  51. use function spl_object_hash;
  52. use function str_replace;
  53. use function strpos;
  54. use function strtolower;
  55. use function trait_exists;
  56. use function trim;
  57. /**
  58.  * A <tt>ClassMetadata</tt> instance holds all the object-relational mapping metadata
  59.  * of an entity and its associations.
  60.  *
  61.  * Once populated, ClassMetadata instances are usually cached in a serialized form.
  62.  *
  63.  * <b>IMPORTANT NOTE:</b>
  64.  *
  65.  * The fields of this class are only public for 2 reasons:
  66.  * 1) To allow fast READ access.
  67.  * 2) To drastically reduce the size of a serialized instance (private/protected members
  68.  *    get the whole class name, namespace inclusive, prepended to every property in
  69.  *    the serialized representation).
  70.  */
  71. class ClassMetadataInfo implements ClassMetadata
  72. {
  73.     /* The inheritance mapping types */
  74.     /**
  75.      * NONE means the class does not participate in an inheritance hierarchy
  76.      * and therefore does not need an inheritance mapping type.
  77.      */
  78.     public const INHERITANCE_TYPE_NONE 1;
  79.     /**
  80.      * JOINED means the class will be persisted according to the rules of
  81.      * <tt>Class Table Inheritance</tt>.
  82.      */
  83.     public const INHERITANCE_TYPE_JOINED 2;
  84.     /**
  85.      * SINGLE_TABLE means the class will be persisted according to the rules of
  86.      * <tt>Single Table Inheritance</tt>.
  87.      */
  88.     public const INHERITANCE_TYPE_SINGLE_TABLE 3;
  89.     /**
  90.      * TABLE_PER_CLASS means the class will be persisted according to the rules
  91.      * of <tt>Concrete Table Inheritance</tt>.
  92.      */
  93.     public const INHERITANCE_TYPE_TABLE_PER_CLASS 4;
  94.     /* The Id generator types. */
  95.     /**
  96.      * AUTO means the generator type will depend on what the used platform prefers.
  97.      * Offers full portability.
  98.      */
  99.     public const GENERATOR_TYPE_AUTO 1;
  100.     /**
  101.      * SEQUENCE means a separate sequence object will be used. Platforms that do
  102.      * not have native sequence support may emulate it. Full portability is currently
  103.      * not guaranteed.
  104.      */
  105.     public const GENERATOR_TYPE_SEQUENCE 2;
  106.     /**
  107.      * TABLE means a separate table is used for id generation.
  108.      * Offers full portability.
  109.      */
  110.     public const GENERATOR_TYPE_TABLE 3;
  111.     /**
  112.      * IDENTITY means an identity column is used for id generation. The database
  113.      * will fill in the id column on insertion. Platforms that do not support
  114.      * native identity columns may emulate them. Full portability is currently
  115.      * not guaranteed.
  116.      */
  117.     public const GENERATOR_TYPE_IDENTITY 4;
  118.     /**
  119.      * NONE means the class does not have a generated id. That means the class
  120.      * must have a natural, manually assigned id.
  121.      */
  122.     public const GENERATOR_TYPE_NONE 5;
  123.     /**
  124.      * UUID means that a UUID/GUID expression is used for id generation. Full
  125.      * portability is currently not guaranteed.
  126.      */
  127.     public const GENERATOR_TYPE_UUID 6;
  128.     /**
  129.      * CUSTOM means that customer will use own ID generator that supposedly work
  130.      */
  131.     public const GENERATOR_TYPE_CUSTOM 7;
  132.     /**
  133.      * DEFERRED_IMPLICIT 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 for all entities that are in MANAGED state at commit-time.
  136.      *
  137.      * This is the default change tracking policy.
  138.      */
  139.     public const CHANGETRACKING_DEFERRED_IMPLICIT 1;
  140.     /**
  141.      * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time
  142.      * by doing a property-by-property comparison with the original data. This will
  143.      * be done only for entities that were explicitly saved (through persist() or a cascade).
  144.      */
  145.     public const CHANGETRACKING_DEFERRED_EXPLICIT 2;
  146.     /**
  147.      * NOTIFY means that Doctrine relies on the entities sending out notifications
  148.      * when their properties change. Such entity classes must implement
  149.      * the <tt>NotifyPropertyChanged</tt> interface.
  150.      */
  151.     public const CHANGETRACKING_NOTIFY 3;
  152.     /**
  153.      * Specifies that an association is to be fetched when it is first accessed.
  154.      */
  155.     public const FETCH_LAZY 2;
  156.     /**
  157.      * Specifies that an association is to be fetched when the owner of the
  158.      * association is fetched.
  159.      */
  160.     public const FETCH_EAGER 3;
  161.     /**
  162.      * Specifies that an association is to be fetched lazy (on first access) and that
  163.      * commands such as Collection#count, Collection#slice are issued directly against
  164.      * the database if the collection is not yet initialized.
  165.      */
  166.     public const FETCH_EXTRA_LAZY 4;
  167.     /**
  168.      * Identifies a one-to-one association.
  169.      */
  170.     public const ONE_TO_ONE 1;
  171.     /**
  172.      * Identifies a many-to-one association.
  173.      */
  174.     public const MANY_TO_ONE 2;
  175.     /**
  176.      * Identifies a one-to-many association.
  177.      */
  178.     public const ONE_TO_MANY 4;
  179.     /**
  180.      * Identifies a many-to-many association.
  181.      */
  182.     public const MANY_TO_MANY 8;
  183.     /**
  184.      * Combined bitmask for to-one (single-valued) associations.
  185.      */
  186.     public const TO_ONE 3;
  187.     /**
  188.      * Combined bitmask for to-many (collection-valued) associations.
  189.      */
  190.     public const TO_MANY 12;
  191.     /**
  192.      * ReadOnly cache can do reads, inserts and deletes, cannot perform updates or employ any locks,
  193.      */
  194.     public const CACHE_USAGE_READ_ONLY 1;
  195.     /**
  196.      * Nonstrict Read Write Cache doesn’t employ any locks but can do inserts, update and deletes.
  197.      */
  198.     public const CACHE_USAGE_NONSTRICT_READ_WRITE 2;
  199.     /**
  200.      * Read Write Attempts to lock the entity before update/delete.
  201.      */
  202.     public const CACHE_USAGE_READ_WRITE 3;
  203.     /**
  204.      * READ-ONLY: The name of the entity class.
  205.      *
  206.      * @var string
  207.      */
  208.     public $name;
  209.     /**
  210.      * READ-ONLY: The namespace the entity class is contained in.
  211.      *
  212.      * @var string
  213.      * @todo Not really needed. Usage could be localized.
  214.      */
  215.     public $namespace;
  216.     /**
  217.      * READ-ONLY: The name of the entity class that is at the root of the mapped entity inheritance
  218.      * hierarchy. If the entity is not part of a mapped inheritance hierarchy this is the same
  219.      * as {@link $name}.
  220.      *
  221.      * @var string
  222.      */
  223.     public $rootEntityName;
  224.     /**
  225.      * READ-ONLY: The definition of custom generator. Only used for CUSTOM
  226.      * generator type
  227.      *
  228.      * The definition has the following structure:
  229.      * <code>
  230.      * array(
  231.      *     'class' => 'ClassName',
  232.      * )
  233.      * </code>
  234.      *
  235.      * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
  236.      * @var array<string, string>|null
  237.      */
  238.     public $customGeneratorDefinition;
  239.     /**
  240.      * The name of the custom repository class used for the entity class.
  241.      * (Optional).
  242.      *
  243.      * @var string|null
  244.      * @psalm-var ?class-string
  245.      */
  246.     public $customRepositoryClassName;
  247.     /**
  248.      * READ-ONLY: Whether this class describes the mapping of a mapped superclass.
  249.      *
  250.      * @var bool
  251.      */
  252.     public $isMappedSuperclass false;
  253.     /**
  254.      * READ-ONLY: Whether this class describes the mapping of an embeddable class.
  255.      *
  256.      * @var bool
  257.      */
  258.     public $isEmbeddedClass false;
  259.     /**
  260.      * READ-ONLY: The names of the parent classes (ancestors).
  261.      *
  262.      * @var array
  263.      */
  264.     public $parentClasses = [];
  265.     /**
  266.      * READ-ONLY: The names of all subclasses (descendants).
  267.      *
  268.      * @var array
  269.      */
  270.     public $subClasses = [];
  271.     /**
  272.      * READ-ONLY: The names of all embedded classes based on properties.
  273.      *
  274.      * @var array
  275.      */
  276.     public $embeddedClasses = [];
  277.     /**
  278.      * READ-ONLY: The named queries allowed to be called directly from Repository.
  279.      *
  280.      * @var array
  281.      */
  282.     public $namedQueries = [];
  283.     /**
  284.      * READ-ONLY: The named native queries allowed to be called directly from Repository.
  285.      *
  286.      * A native SQL named query definition has the following structure:
  287.      * <pre>
  288.      * array(
  289.      *     'name'               => <query name>,
  290.      *     'query'              => <sql query>,
  291.      *     'resultClass'        => <class of the result>,
  292.      *     'resultSetMapping'   => <name of a SqlResultSetMapping>
  293.      * )
  294.      * </pre>
  295.      *
  296.      * @var array
  297.      */
  298.     public $namedNativeQueries = [];
  299.     /**
  300.      * READ-ONLY: The mappings of the results of native SQL queries.
  301.      *
  302.      * A native result mapping definition has the following structure:
  303.      * <pre>
  304.      * array(
  305.      *     'name'               => <result name>,
  306.      *     'entities'           => array(<entity result mapping>),
  307.      *     'columns'            => array(<column result mapping>)
  308.      * )
  309.      * </pre>
  310.      *
  311.      * @var array
  312.      */
  313.     public $sqlResultSetMappings = [];
  314.     /**
  315.      * READ-ONLY: The field names of all fields that are part of the identifier/primary key
  316.      * of the mapped entity class.
  317.      *
  318.      * @var array
  319.      */
  320.     public $identifier = [];
  321.     /**
  322.      * READ-ONLY: The inheritance mapping type used by the class.
  323.      *
  324.      * @var int
  325.      */
  326.     public $inheritanceType self::INHERITANCE_TYPE_NONE;
  327.     /**
  328.      * READ-ONLY: The Id generator type used by the class.
  329.      *
  330.      * @var int
  331.      */
  332.     public $generatorType self::GENERATOR_TYPE_NONE;
  333.     /**
  334.      * READ-ONLY: The field mappings of the class.
  335.      * Keys are field names and values are mapping definitions.
  336.      *
  337.      * The mapping definition array has the following values:
  338.      *
  339.      * - <b>fieldName</b> (string)
  340.      * The name of the field in the Entity.
  341.      *
  342.      * - <b>type</b> (string)
  343.      * The type name of the mapped field. Can be one of Doctrine's mapping types
  344.      * or a custom mapping type.
  345.      *
  346.      * - <b>columnName</b> (string, optional)
  347.      * The column name. Optional. Defaults to the field name.
  348.      *
  349.      * - <b>length</b> (integer, optional)
  350.      * The database length of the column. Optional. Default value taken from
  351.      * the type.
  352.      *
  353.      * - <b>id</b> (boolean, optional)
  354.      * Marks the field as the primary key of the entity. Multiple fields of an
  355.      * entity can have the id attribute, forming a composite key.
  356.      *
  357.      * - <b>nullable</b> (boolean, optional)
  358.      * Whether the column is nullable. Defaults to FALSE.
  359.      *
  360.      * - <b>columnDefinition</b> (string, optional, schema-only)
  361.      * The SQL fragment that is used when generating the DDL for the column.
  362.      *
  363.      * - <b>precision</b> (integer, optional, schema-only)
  364.      * The precision of a decimal column. Only valid if the column type is decimal.
  365.      *
  366.      * - <b>scale</b> (integer, optional, schema-only)
  367.      * The scale of a decimal column. Only valid if the column type is decimal.
  368.      *
  369.      * - <b>'unique'</b> (string, optional, schema-only)
  370.      * Whether a unique constraint should be generated for the column.
  371.      *
  372.      * @var array
  373.      * @psalm-var array<string, array{type: string, fieldName: string, columnName: string, inherited: class-string}>
  374.      */
  375.     public $fieldMappings = [];
  376.     /**
  377.      * READ-ONLY: An array of field names. Used to look up field names from column names.
  378.      * Keys are column names and values are field names.
  379.      *
  380.      * @var array
  381.      */
  382.     public $fieldNames = [];
  383.     /**
  384.      * READ-ONLY: A map of field names to column names. Keys are field names and values column names.
  385.      * Used to look up column names from field names.
  386.      * This is the reverse lookup map of $_fieldNames.
  387.      *
  388.      * @deprecated 3.0 Remove this.
  389.      *
  390.      * @var mixed[]
  391.      */
  392.     public $columnNames = [];
  393.     /**
  394.      * READ-ONLY: The discriminator value of this class.
  395.      *
  396.      * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
  397.      * where a discriminator column is used.</b>
  398.      *
  399.      * @see discriminatorColumn
  400.      *
  401.      * @var mixed
  402.      */
  403.     public $discriminatorValue;
  404.     /**
  405.      * READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
  406.      *
  407.      * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
  408.      * where a discriminator column is used.</b>
  409.      *
  410.      * @see discriminatorColumn
  411.      *
  412.      * @var mixed
  413.      */
  414.     public $discriminatorMap = [];
  415.     /**
  416.      * READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE
  417.      * inheritance mappings.
  418.      *
  419.      * @var array
  420.      */
  421.     public $discriminatorColumn;
  422.     /**
  423.      * READ-ONLY: The primary table definition. The definition is an array with the
  424.      * following entries:
  425.      *
  426.      * name => <tableName>
  427.      * schema => <schemaName>
  428.      * indexes => array
  429.      * uniqueConstraints => array
  430.      *
  431.      * @var array
  432.      */
  433.     public $table;
  434.     /**
  435.      * READ-ONLY: The registered lifecycle callbacks for entities of this class.
  436.      *
  437.      * @var array[]
  438.      */
  439.     public $lifecycleCallbacks = [];
  440.     /**
  441.      * READ-ONLY: The registered entity listeners.
  442.      *
  443.      * @var array
  444.      */
  445.     public $entityListeners = [];
  446.     /**
  447.      * READ-ONLY: The association mappings of this class.
  448.      *
  449.      * The mapping definition array supports the following keys:
  450.      *
  451.      * - <b>fieldName</b> (string)
  452.      * The name of the field in the entity the association is mapped to.
  453.      *
  454.      * - <b>targetEntity</b> (string)
  455.      * The class name of the target entity. If it is fully-qualified it is used as is.
  456.      * If it is a simple, unqualified class name the namespace is assumed to be the same
  457.      * as the namespace of the source entity.
  458.      *
  459.      * - <b>mappedBy</b> (string, required for bidirectional associations)
  460.      * The name of the field that completes the bidirectional association on the owning side.
  461.      * This key must be specified on the inverse side of a bidirectional association.
  462.      *
  463.      * - <b>inversedBy</b> (string, required for bidirectional associations)
  464.      * The name of the field that completes the bidirectional association on the inverse side.
  465.      * This key must be specified on the owning side of a bidirectional association.
  466.      *
  467.      * - <b>cascade</b> (array, optional)
  468.      * The names of persistence operations to cascade on the association. The set of possible
  469.      * values are: "persist", "remove", "detach", "merge", "refresh", "all" (implies all others).
  470.      *
  471.      * - <b>orderBy</b> (array, one-to-many/many-to-many only)
  472.      * A map of field names (of the target entity) to sorting directions (ASC/DESC).
  473.      * Example: array('priority' => 'desc')
  474.      *
  475.      * - <b>fetch</b> (integer, optional)
  476.      * The fetching strategy to use for the association, usually defaults to FETCH_LAZY.
  477.      * Possible values are: ClassMetadata::FETCH_EAGER, ClassMetadata::FETCH_LAZY.
  478.      *
  479.      * - <b>joinTable</b> (array, optional, many-to-many only)
  480.      * Specification of the join table and its join columns (foreign keys).
  481.      * Only valid for many-to-many mappings. Note that one-to-many associations can be mapped
  482.      * through a join table by simply mapping the association as many-to-many with a unique
  483.      * constraint on the join table.
  484.      *
  485.      * - <b>indexBy</b> (string, optional, to-many only)
  486.      * Specification of a field on target-entity that is used to index the collection by.
  487.      * This field HAS to be either the primary key or a unique column. Otherwise the collection
  488.      * does not contain all the entities that are actually related.
  489.      *
  490.      * A join table definition has the following structure:
  491.      * <pre>
  492.      * array(
  493.      *     'name' => <join table name>,
  494.      *      'joinColumns' => array(<join column mapping from join table to source table>),
  495.      *      'inverseJoinColumns' => array(<join column mapping from join table to target table>)
  496.      * )
  497.      * </pre>
  498.      *
  499.      * @var array
  500.      */
  501.     public $associationMappings = [];
  502.     /**
  503.      * READ-ONLY: Flag indicating whether the identifier/primary key of the class is composite.
  504.      *
  505.      * @var bool
  506.      */
  507.     public $isIdentifierComposite false;
  508.     /**
  509.      * READ-ONLY: Flag indicating whether the identifier/primary key contains at least one foreign key association.
  510.      *
  511.      * This flag is necessary because some code blocks require special treatment of this cases.
  512.      *
  513.      * @var bool
  514.      */
  515.     public $containsForeignIdentifier false;
  516.     /**
  517.      * READ-ONLY: The ID generator used for generating IDs for this class.
  518.      *
  519.      * @var AbstractIdGenerator
  520.      * @todo Remove!
  521.      */
  522.     public $idGenerator;
  523.     /**
  524.      * READ-ONLY: The definition of the sequence generator of this class. Only used for the
  525.      * SEQUENCE generation strategy.
  526.      *
  527.      * The definition has the following structure:
  528.      * <code>
  529.      * array(
  530.      *     'sequenceName' => 'name',
  531.      *     'allocationSize' => 20,
  532.      *     'initialValue' => 1
  533.      * )
  534.      * </code>
  535.      *
  536.      * @var array
  537.      * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
  538.      */
  539.     public $sequenceGeneratorDefinition;
  540.     /**
  541.      * READ-ONLY: The definition of the table generator of this class. Only used for the
  542.      * TABLE generation strategy.
  543.      *
  544.      * @var array
  545.      * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
  546.      */
  547.     public $tableGeneratorDefinition;
  548.     /**
  549.      * READ-ONLY: The policy used for change-tracking on entities of this class.
  550.      *
  551.      * @var int
  552.      */
  553.     public $changeTrackingPolicy self::CHANGETRACKING_DEFERRED_IMPLICIT;
  554.     /**
  555.      * READ-ONLY: A flag for whether or not instances of this class are to be versioned
  556.      * with optimistic locking.
  557.      *
  558.      * @var bool
  559.      */
  560.     public $isVersioned;
  561.     /**
  562.      * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any).
  563.      *
  564.      * @var mixed
  565.      */
  566.     public $versionField;
  567.     /** @var mixed[] */
  568.     public $cache null;
  569.     /**
  570.      * The ReflectionClass instance of the mapped class.
  571.      *
  572.      * @var ReflectionClass
  573.      */
  574.     public $reflClass;
  575.     /**
  576.      * Is this entity marked as "read-only"?
  577.      *
  578.      * That means it is never considered for change-tracking in the UnitOfWork. It is a very helpful performance
  579.      * optimization for entities that are immutable, either in your domain or through the relation database
  580.      * (coming from a view, or a history table for example).
  581.      *
  582.      * @var bool
  583.      */
  584.     public $isReadOnly false;
  585.     /**
  586.      * NamingStrategy determining the default column and table names.
  587.      *
  588.      * @var NamingStrategy
  589.      */
  590.     protected $namingStrategy;
  591.     /**
  592.      * The ReflectionProperty instances of the mapped class.
  593.      *
  594.      * @var ReflectionProperty[]|null[]
  595.      */
  596.     public $reflFields = [];
  597.     /** @var InstantiatorInterface|null */
  598.     private $instantiator;
  599.     /**
  600.      * Initializes a new ClassMetadata instance that will hold the object-relational mapping
  601.      * metadata of the class with the given name.
  602.      *
  603.      * @param string $entityName The name of the entity class the new instance is used for.
  604.      */
  605.     public function __construct($entityName, ?NamingStrategy $namingStrategy null)
  606.     {
  607.         $this->name           $entityName;
  608.         $this->rootEntityName $entityName;
  609.         $this->namingStrategy $namingStrategy ?: new DefaultNamingStrategy();
  610.         $this->instantiator   = new Instantiator();
  611.     }
  612.     /**
  613.      * Gets the ReflectionProperties of the mapped class.
  614.      *
  615.      * @return ReflectionProperty[]|null[] An array of ReflectionProperty instances.
  616.      *
  617.      * @psalm-return array<ReflectionProperty|null>
  618.      */
  619.     public function getReflectionProperties()
  620.     {
  621.         return $this->reflFields;
  622.     }
  623.     /**
  624.      * Gets a ReflectionProperty for a specific field of the mapped class.
  625.      *
  626.      * @param string $name
  627.      *
  628.      * @return ReflectionProperty
  629.      */
  630.     public function getReflectionProperty($name)
  631.     {
  632.         return $this->reflFields[$name];
  633.     }
  634.     /**
  635.      * Gets the ReflectionProperty for the single identifier field.
  636.      *
  637.      * @return ReflectionProperty
  638.      *
  639.      * @throws BadMethodCallException If the class has a composite identifier.
  640.      */
  641.     public function getSingleIdReflectionProperty()
  642.     {
  643.         if ($this->isIdentifierComposite) {
  644.             throw new BadMethodCallException('Class ' $this->name ' has a composite identifier.');
  645.         }
  646.         return $this->reflFields[$this->identifier[0]];
  647.     }
  648.     /**
  649.      * Extracts the identifier values of an entity of this class.
  650.      *
  651.      * For composite identifiers, the identifier values are returned as an array
  652.      * with the same order as the field order in {@link identifier}.
  653.      *
  654.      * @param object $entity
  655.      *
  656.      * @return array
  657.      */
  658.     public function getIdentifierValues($entity)
  659.     {
  660.         if ($this->isIdentifierComposite) {
  661.             $id = [];
  662.             foreach ($this->identifier as $idField) {
  663.                 $value $this->reflFields[$idField]->getValue($entity);
  664.                 if ($value !== null) {
  665.                     $id[$idField] = $value;
  666.                 }
  667.             }
  668.             return $id;
  669.         }
  670.         $id    $this->identifier[0];
  671.         $value $this->reflFields[$id]->getValue($entity);
  672.         if ($value === null) {
  673.             return [];
  674.         }
  675.         return [$id => $value];
  676.     }
  677.     /**
  678.      * Populates the entity identifier of an entity.
  679.      *
  680.      * @param object $entity
  681.      * @param array  $id
  682.      *
  683.      * @return void
  684.      *
  685.      * @todo Rename to assignIdentifier()
  686.      */
  687.     public function setIdentifierValues($entity, array $id)
  688.     {
  689.         foreach ($id as $idField => $idValue) {
  690.             $this->reflFields[$idField]->setValue($entity$idValue);
  691.         }
  692.     }
  693.     /**
  694.      * Sets the specified field to the specified value on the given entity.
  695.      *
  696.      * @param object $entity
  697.      * @param string $field
  698.      * @param mixed  $value
  699.      *
  700.      * @return void
  701.      */
  702.     public function setFieldValue($entity$field$value)
  703.     {
  704.         $this->reflFields[$field]->setValue($entity$value);
  705.     }
  706.     /**
  707.      * Gets the specified field's value off the given entity.
  708.      *
  709.      * @param object $entity
  710.      * @param string $field
  711.      *
  712.      * @return mixed
  713.      */
  714.     public function getFieldValue($entity$field)
  715.     {
  716.         return $this->reflFields[$field]->getValue($entity);
  717.     }
  718.     /**
  719.      * Creates a string representation of this instance.
  720.      *
  721.      * @return string The string representation of this instance.
  722.      *
  723.      * @todo Construct meaningful string representation.
  724.      */
  725.     public function __toString()
  726.     {
  727.         return self::class . '@' spl_object_hash($this);
  728.     }
  729.     /**
  730.      * Determines which fields get serialized.
  731.      *
  732.      * It is only serialized what is necessary for best unserialization performance.
  733.      * That means any metadata properties that are not set or empty or simply have
  734.      * their default value are NOT serialized.
  735.      *
  736.      * Parts that are also NOT serialized because they can not be properly unserialized:
  737.      *      - reflClass (ReflectionClass)
  738.      *      - reflFields (ReflectionProperty array)
  739.      *
  740.      * @return string[] The names of all the fields that should be serialized.
  741.      */
  742.     public function __sleep()
  743.     {
  744.         // This metadata is always serialized/cached.
  745.         $serialized = [
  746.             'associationMappings',
  747.             'columnNames'//TODO: 3.0 Remove this. Can use fieldMappings[$fieldName]['columnName']
  748.             'fieldMappings',
  749.             'fieldNames',
  750.             'embeddedClasses',
  751.             'identifier',
  752.             'isIdentifierComposite'// TODO: REMOVE
  753.             'name',
  754.             'namespace'// TODO: REMOVE
  755.             'table',
  756.             'rootEntityName',
  757.             'idGenerator'//TODO: Does not really need to be serialized. Could be moved to runtime.
  758.         ];
  759.         // The rest of the metadata is only serialized if necessary.
  760.         if ($this->changeTrackingPolicy !== self::CHANGETRACKING_DEFERRED_IMPLICIT) {
  761.             $serialized[] = 'changeTrackingPolicy';
  762.         }
  763.         if ($this->customRepositoryClassName) {
  764.             $serialized[] = 'customRepositoryClassName';
  765.         }
  766.         if ($this->inheritanceType !== self::INHERITANCE_TYPE_NONE) {
  767.             $serialized[] = 'inheritanceType';
  768.             $serialized[] = 'discriminatorColumn';
  769.             $serialized[] = 'discriminatorValue';
  770.             $serialized[] = 'discriminatorMap';
  771.             $serialized[] = 'parentClasses';
  772.             $serialized[] = 'subClasses';
  773.         }
  774.         if ($this->generatorType !== self::GENERATOR_TYPE_NONE) {
  775.             $serialized[] = 'generatorType';
  776.             if ($this->generatorType === self::GENERATOR_TYPE_SEQUENCE) {
  777.                 $serialized[] = 'sequenceGeneratorDefinition';
  778.             }
  779.         }
  780.         if ($this->isMappedSuperclass) {
  781.             $serialized[] = 'isMappedSuperclass';
  782.         }
  783.         if ($this->isEmbeddedClass) {
  784.             $serialized[] = 'isEmbeddedClass';
  785.         }
  786.         if ($this->containsForeignIdentifier) {
  787.             $serialized[] = 'containsForeignIdentifier';
  788.         }
  789.         if ($this->isVersioned) {
  790.             $serialized[] = 'isVersioned';
  791.             $serialized[] = 'versionField';
  792.         }
  793.         if ($this->lifecycleCallbacks) {
  794.             $serialized[] = 'lifecycleCallbacks';
  795.         }
  796.         if ($this->entityListeners) {
  797.             $serialized[] = 'entityListeners';
  798.         }
  799.         if ($this->namedQueries) {
  800.             $serialized[] = 'namedQueries';
  801.         }
  802.         if ($this->namedNativeQueries) {
  803.             $serialized[] = 'namedNativeQueries';
  804.         }
  805.         if ($this->sqlResultSetMappings) {
  806.             $serialized[] = 'sqlResultSetMappings';
  807.         }
  808.         if ($this->isReadOnly) {
  809.             $serialized[] = 'isReadOnly';
  810.         }
  811.         if ($this->customGeneratorDefinition) {
  812.             $serialized[] = 'customGeneratorDefinition';
  813.         }
  814.         if ($this->cache) {
  815.             $serialized[] = 'cache';
  816.         }
  817.         return $serialized;
  818.     }
  819.     /**
  820.      * Creates a new instance of the mapped class, without invoking the constructor.
  821.      *
  822.      * @return object
  823.      */
  824.     public function newInstance()
  825.     {
  826.         return $this->instantiator->instantiate($this->name);
  827.     }
  828.     /**
  829.      * Restores some state that can not be serialized/unserialized.
  830.      *
  831.      * @param ReflectionService $reflService
  832.      *
  833.      * @return void
  834.      */
  835.     public function wakeupReflection($reflService)
  836.     {
  837.         // Restore ReflectionClass and properties
  838.         $this->reflClass    $reflService->getClass($this->name);
  839.         $this->instantiator $this->instantiator ?: new Instantiator();
  840.         $parentReflFields = [];
  841.         foreach ($this->embeddedClasses as $property => $embeddedClass) {
  842.             if (isset($embeddedClass['declaredField'])) {
  843.                 $parentReflFields[$property] = new ReflectionEmbeddedProperty(
  844.                     $parentReflFields[$embeddedClass['declaredField']],
  845.                     $reflService->getAccessibleProperty(
  846.                         $this->embeddedClasses[$embeddedClass['declaredField']]['class'],
  847.                         $embeddedClass['originalField']
  848.                     ),
  849.                     $this->embeddedClasses[$embeddedClass['declaredField']]['class']
  850.                 );
  851.                 continue;
  852.             }
  853.             $fieldRefl $reflService->getAccessibleProperty(
  854.                 $embeddedClass['declared'] ?? $this->name,
  855.                 $property
  856.             );
  857.             $parentReflFields[$property] = $fieldRefl;
  858.             $this->reflFields[$property] = $fieldRefl;
  859.         }
  860.         foreach ($this->fieldMappings as $field => $mapping) {
  861.             if (isset($mapping['declaredField']) && isset($parentReflFields[$mapping['declaredField']])) {
  862.                 $this->reflFields[$field] = new ReflectionEmbeddedProperty(
  863.                     $parentReflFields[$mapping['declaredField']],
  864.                     $reflService->getAccessibleProperty($mapping['originalClass'], $mapping['originalField']),
  865.                     $mapping['originalClass']
  866.                 );
  867.                 continue;
  868.             }
  869.             $this->reflFields[$field] = isset($mapping['declared'])
  870.                 ? $reflService->getAccessibleProperty($mapping['declared'], $field)
  871.                 : $reflService->getAccessibleProperty($this->name$field);
  872.         }
  873.         foreach ($this->associationMappings as $field => $mapping) {
  874.             $this->reflFields[$field] = isset($mapping['declared'])
  875.                 ? $reflService->getAccessibleProperty($mapping['declared'], $field)
  876.                 : $reflService->getAccessibleProperty($this->name$field);
  877.         }
  878.     }
  879.     /**
  880.      * Initializes a new ClassMetadata instance that will hold the object-relational mapping
  881.      * metadata of the class with the given name.
  882.      *
  883.      * @param ReflectionService $reflService The reflection service.
  884.      *
  885.      * @return void
  886.      */
  887.     public function initializeReflection($reflService)
  888.     {
  889.         $this->reflClass $reflService->getClass($this->name);
  890.         $this->namespace $reflService->getClassNamespace($this->name);
  891.         if ($this->reflClass) {
  892.             $this->name $this->rootEntityName $this->reflClass->getName();
  893.         }
  894.         $this->table['name'] = $this->namingStrategy->classToTableName($this->name);
  895.     }
  896.     /**
  897.      * Validates Identifier.
  898.      *
  899.      * @return void
  900.      *
  901.      * @throws MappingException
  902.      */
  903.     public function validateIdentifier()
  904.     {
  905.         if ($this->isMappedSuperclass || $this->isEmbeddedClass) {
  906.             return;
  907.         }
  908.         // Verify & complete identifier mapping
  909.         if (! $this->identifier) {
  910.             throw MappingException::identifierRequired($this->name);
  911.         }
  912.         if ($this->usesIdGenerator() && $this->isIdentifierComposite) {
  913.             throw MappingException::compositeKeyAssignedIdGeneratorRequired($this->name);
  914.         }
  915.     }
  916.     /**
  917.      * Validates association targets actually exist.
  918.      *
  919.      * @return void
  920.      *
  921.      * @throws MappingException
  922.      */
  923.     public function validateAssociations()
  924.     {
  925.         foreach ($this->associationMappings as $mapping) {
  926.             if (
  927.                 ! class_exists($mapping['targetEntity'])
  928.                 && ! interface_exists($mapping['targetEntity'])
  929.                 && ! trait_exists($mapping['targetEntity'])
  930.             ) {
  931.                 throw MappingException::invalidTargetEntityClass($mapping['targetEntity'], $this->name$mapping['fieldName']);
  932.             }
  933.         }
  934.     }
  935.     /**
  936.      * Validates lifecycle callbacks.
  937.      *
  938.      * @param ReflectionService $reflService
  939.      *
  940.      * @return void
  941.      *
  942.      * @throws MappingException
  943.      */
  944.     public function validateLifecycleCallbacks($reflService)
  945.     {
  946.         foreach ($this->lifecycleCallbacks as $callbacks) {
  947.             foreach ($callbacks as $callbackFuncName) {
  948.                 if (! $reflService->hasPublicMethod($this->name$callbackFuncName)) {
  949.                     throw MappingException::lifecycleCallbackMethodNotFound($this->name$callbackFuncName);
  950.                 }
  951.             }
  952.         }
  953.     }
  954.     /**
  955.      * {@inheritDoc}
  956.      */
  957.     public function getReflectionClass()
  958.     {
  959.         return $this->reflClass;
  960.     }
  961.     /**
  962.      * @param array $cache
  963.      *
  964.      * @return void
  965.      */
  966.     public function enableCache(array $cache)
  967.     {
  968.         if (! isset($cache['usage'])) {
  969.             $cache['usage'] = self::CACHE_USAGE_READ_ONLY;
  970.         }
  971.         if (! isset($cache['region'])) {
  972.             $cache['region'] = strtolower(str_replace('\\''_'$this->rootEntityName));
  973.         }
  974.         $this->cache $cache;
  975.     }
  976.     /**
  977.      * @param string $fieldName
  978.      * @param array  $cache
  979.      *
  980.      * @return void
  981.      */
  982.     public function enableAssociationCache($fieldName, array $cache)
  983.     {
  984.         $this->associationMappings[$fieldName]['cache'] = $this->getAssociationCacheDefaults($fieldName$cache);
  985.     }
  986.     /**
  987.      * @param string $fieldName
  988.      * @param array  $cache
  989.      *
  990.      * @return mixed[]
  991.      *
  992.      * @psalm-param array{usage: mixed, region: mixed} $cache
  993.      * @psalm-return array{usage: mixed, region: mixed}
  994.      */
  995.     public function getAssociationCacheDefaults($fieldName, array $cache)
  996.     {
  997.         if (! isset($cache['usage'])) {
  998.             $cache['usage'] = $this->cache['usage'] ?? self::CACHE_USAGE_READ_ONLY;
  999.         }
  1000.         if (! isset($cache['region'])) {
  1001.             $cache['region'] = strtolower(str_replace('\\''_'$this->rootEntityName)) . '__' $fieldName;
  1002.         }
  1003.         return $cache;
  1004.     }
  1005.     /**
  1006.      * Sets the change tracking policy used by this class.
  1007.      *
  1008.      * @param int $policy
  1009.      *
  1010.      * @return void
  1011.      */
  1012.     public function setChangeTrackingPolicy($policy)
  1013.     {
  1014.         $this->changeTrackingPolicy $policy;
  1015.     }
  1016.     /**
  1017.      * Whether the change tracking policy of this class is "deferred explicit".
  1018.      *
  1019.      * @return bool
  1020.      */
  1021.     public function isChangeTrackingDeferredExplicit()
  1022.     {
  1023.         return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_EXPLICIT;
  1024.     }
  1025.     /**
  1026.      * Whether the change tracking policy of this class is "deferred implicit".
  1027.      *
  1028.      * @return bool
  1029.      */
  1030.     public function isChangeTrackingDeferredImplicit()
  1031.     {
  1032.         return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_IMPLICIT;
  1033.     }
  1034.     /**
  1035.      * Whether the change tracking policy of this class is "notify".
  1036.      *
  1037.      * @return bool
  1038.      */
  1039.     public function isChangeTrackingNotify()
  1040.     {
  1041.         return $this->changeTrackingPolicy === self::CHANGETRACKING_NOTIFY;
  1042.     }
  1043.     /**
  1044.      * Checks whether a field is part of the identifier/primary key field(s).
  1045.      *
  1046.      * @param string $fieldName The field name.
  1047.      *
  1048.      * @return bool TRUE if the field is part of the table identifier/primary key field(s),
  1049.      * FALSE otherwise.
  1050.      */
  1051.     public function isIdentifier($fieldName)
  1052.     {
  1053.         if (! $this->identifier) {
  1054.             return false;
  1055.         }
  1056.         if (! $this->isIdentifierComposite) {
  1057.             return $fieldName === $this->identifier[0];
  1058.         }
  1059.         return in_array($fieldName$this->identifiertrue);
  1060.     }
  1061.     /**
  1062.      * Checks if the field is unique.
  1063.      *
  1064.      * @param string $fieldName The field name.
  1065.      *
  1066.      * @return bool TRUE if the field is unique, FALSE otherwise.
  1067.      */
  1068.     public function isUniqueField($fieldName)
  1069.     {
  1070.         $mapping $this->getFieldMapping($fieldName);
  1071.         return $mapping !== false && isset($mapping['unique']) && $mapping['unique'];
  1072.     }
  1073.     /**
  1074.      * Checks if the field is not null.
  1075.      *
  1076.      * @param string $fieldName The field name.
  1077.      *
  1078.      * @return bool TRUE if the field is not null, FALSE otherwise.
  1079.      */
  1080.     public function isNullable($fieldName)
  1081.     {
  1082.         $mapping $this->getFieldMapping($fieldName);
  1083.         return $mapping !== false && isset($mapping['nullable']) && $mapping['nullable'];
  1084.     }
  1085.     /**
  1086.      * Gets a column name for a field name.
  1087.      * If the column name for the field cannot be found, the given field name
  1088.      * is returned.
  1089.      *
  1090.      * @param string $fieldName The field name.
  1091.      *
  1092.      * @return string The column name.
  1093.      */
  1094.     public function getColumnName($fieldName)
  1095.     {
  1096.         return $this->columnNames[$fieldName] ?? $fieldName;
  1097.     }
  1098.     /**
  1099.      * Gets the mapping of a (regular) field that holds some data but not a
  1100.      * reference to another object.
  1101.      *
  1102.      * @param string $fieldName The field name.
  1103.      *
  1104.      * @return array The field mapping.
  1105.      *
  1106.      * @throws MappingException
  1107.      */
  1108.     public function getFieldMapping($fieldName)
  1109.     {
  1110.         if (! isset($this->fieldMappings[$fieldName])) {
  1111.             throw MappingException::mappingNotFound($this->name$fieldName);
  1112.         }
  1113.         return $this->fieldMappings[$fieldName];
  1114.     }
  1115.     /**
  1116.      * Gets the mapping of an association.
  1117.      *
  1118.      * @see ClassMetadataInfo::$associationMappings
  1119.      *
  1120.      * @param string $fieldName The field name that represents the association in
  1121.      *                          the object model.
  1122.      *
  1123.      * @return array The mapping.
  1124.      *
  1125.      * @throws MappingException
  1126.      */
  1127.     public function getAssociationMapping($fieldName)
  1128.     {
  1129.         if (! isset($this->associationMappings[$fieldName])) {
  1130.             throw MappingException::mappingNotFound($this->name$fieldName);
  1131.         }
  1132.         return $this->associationMappings[$fieldName];
  1133.     }
  1134.     /**
  1135.      * Gets all association mappings of the class.
  1136.      *
  1137.      * @return array
  1138.      */
  1139.     public function getAssociationMappings()
  1140.     {
  1141.         return $this->associationMappings;
  1142.     }
  1143.     /**
  1144.      * Gets the field name for a column name.
  1145.      * If no field name can be found the column name is returned.
  1146.      *
  1147.      * @param string $columnName The column name.
  1148.      *
  1149.      * @return string The column alias.
  1150.      */
  1151.     public function getFieldName($columnName)
  1152.     {
  1153.         return $this->fieldNames[$columnName] ?? $columnName;
  1154.     }
  1155.     /**
  1156.      * Gets the named query.
  1157.      *
  1158.      * @see ClassMetadataInfo::$namedQueries
  1159.      *
  1160.      * @param string $queryName The query name.
  1161.      *
  1162.      * @return string
  1163.      *
  1164.      * @throws MappingException
  1165.      */
  1166.     public function getNamedQuery($queryName)
  1167.     {
  1168.         if (! isset($this->namedQueries[$queryName])) {
  1169.             throw MappingException::queryNotFound($this->name$queryName);
  1170.         }
  1171.         return $this->namedQueries[$queryName]['dql'];
  1172.     }
  1173.     /**
  1174.      * Gets all named queries of the class.
  1175.      *
  1176.      * @return array
  1177.      */
  1178.     public function getNamedQueries()
  1179.     {
  1180.         return $this->namedQueries;
  1181.     }
  1182.     /**
  1183.      * Gets the named native query.
  1184.      *
  1185.      * @see ClassMetadataInfo::$namedNativeQueries
  1186.      *
  1187.      * @param string $queryName The query name.
  1188.      *
  1189.      * @return array
  1190.      *
  1191.      * @throws MappingException
  1192.      */
  1193.     public function getNamedNativeQuery($queryName)
  1194.     {
  1195.         if (! isset($this->namedNativeQueries[$queryName])) {
  1196.             throw MappingException::queryNotFound($this->name$queryName);
  1197.         }
  1198.         return $this->namedNativeQueries[$queryName];
  1199.     }
  1200.     /**
  1201.      * Gets all named native queries of the class.
  1202.      *
  1203.      * @return array
  1204.      */
  1205.     public function getNamedNativeQueries()
  1206.     {
  1207.         return $this->namedNativeQueries;
  1208.     }
  1209.     /**
  1210.      * Gets the result set mapping.
  1211.      *
  1212.      * @see ClassMetadataInfo::$sqlResultSetMappings
  1213.      *
  1214.      * @param string $name The result set mapping name.
  1215.      *
  1216.      * @return array
  1217.      *
  1218.      * @throws MappingException
  1219.      */
  1220.     public function getSqlResultSetMapping($name)
  1221.     {
  1222.         if (! isset($this->sqlResultSetMappings[$name])) {
  1223.             throw MappingException::resultMappingNotFound($this->name$name);
  1224.         }
  1225.         return $this->sqlResultSetMappings[$name];
  1226.     }
  1227.     /**
  1228.      * Gets all sql result set mappings of the class.
  1229.      *
  1230.      * @return array
  1231.      */
  1232.     public function getSqlResultSetMappings()
  1233.     {
  1234.         return $this->sqlResultSetMappings;
  1235.     }
  1236.     /**
  1237.      * Validates & completes the given field mapping.
  1238.      *
  1239.      * @param array $mapping The field mapping to validate & complete.
  1240.      *
  1241.      * @return void
  1242.      *
  1243.      * @throws MappingException
  1244.      */
  1245.     protected function _validateAndCompleteFieldMapping(array &$mapping)
  1246.     {
  1247.         // Check mandatory fields
  1248.         if (! isset($mapping['fieldName']) || ! $mapping['fieldName']) {
  1249.             throw MappingException::missingFieldName($this->name);
  1250.         }
  1251.         if (! isset($mapping['type'])) {
  1252.             // Default to string
  1253.             $mapping['type'] = 'string';
  1254.         }
  1255.         // Complete fieldName and columnName mapping
  1256.         if (! isset($mapping['columnName'])) {
  1257.             $mapping['columnName'] = $this->namingStrategy->propertyToColumnName($mapping['fieldName'], $this->name);
  1258.         }
  1259.         if ($mapping['columnName'][0] === '`') {
  1260.             $mapping['columnName'] = trim($mapping['columnName'], '`');
  1261.             $mapping['quoted']     = true;
  1262.         }
  1263.         $this->columnNames[$mapping['fieldName']] = $mapping['columnName'];
  1264.         if (isset($this->fieldNames[$mapping['columnName']]) || ($this->discriminatorColumn && $this->discriminatorColumn['name'] === $mapping['columnName'])) {
  1265.             throw MappingException::duplicateColumnName($this->name$mapping['columnName']);
  1266.         }
  1267.         $this->fieldNames[$mapping['columnName']] = $mapping['fieldName'];
  1268.         // Complete id mapping
  1269.         if (isset($mapping['id']) && $mapping['id'] === true) {
  1270.             if ($this->versionField === $mapping['fieldName']) {
  1271.                 throw MappingException::cannotVersionIdField($this->name$mapping['fieldName']);
  1272.             }
  1273.             if (! in_array($mapping['fieldName'], $this->identifier)) {
  1274.                 $this->identifier[] = $mapping['fieldName'];
  1275.             }
  1276.             // Check for composite key
  1277.             if (! $this->isIdentifierComposite && count($this->identifier) > 1) {
  1278.                 $this->isIdentifierComposite true;
  1279.             }
  1280.         }
  1281.         if (Type::hasType($mapping['type']) && Type::getType($mapping['type'])->canRequireSQLConversion()) {
  1282.             if (isset($mapping['id']) && $mapping['id'] === true) {
  1283.                  throw MappingException::sqlConversionNotAllowedForIdentifiers($this->name$mapping['fieldName'], $mapping['type']);
  1284.             }
  1285.             $mapping['requireSQLConversion'] = true;
  1286.         }
  1287.     }
  1288.     /**
  1289.      * Validates & completes the basic mapping information that is common to all
  1290.      * association mappings (one-to-one, many-ot-one, one-to-many, many-to-many).
  1291.      *
  1292.      * @param array $mapping The mapping.
  1293.      *
  1294.      * @return mixed[] The updated mapping.
  1295.      *
  1296.      * @throws MappingException If something is wrong with the mapping.
  1297.      *
  1298.      * @psalm-return array{
  1299.      *                   mappedBy: mixed,
  1300.      *                   inversedBy: mixed,
  1301.      *                   isOwningSide: bool,
  1302.      *                   sourceEntity: string,
  1303.      *                   targetEntity: string,
  1304.      *                   fieldName: mixed,
  1305.      *                   fetch: mixed,
  1306.      *                   cascade: array<array-key,string>,
  1307.      *                   isCascadeRemove: bool,
  1308.      *                   isCascadePersist: bool,
  1309.      *                   isCascadeRefresh: bool,
  1310.      *                   isCascadeMerge: bool,
  1311.      *                   isCascadeDetach: bool
  1312.      *               }
  1313.      */
  1314.     protected function _validateAndCompleteAssociationMapping(array $mapping)
  1315.     {
  1316.         if (! isset($mapping['mappedBy'])) {
  1317.             $mapping['mappedBy'] = null;
  1318.         }
  1319.         if (! isset($mapping['inversedBy'])) {
  1320.             $mapping['inversedBy'] = null;
  1321.         }
  1322.         $mapping['isOwningSide'] = true// assume owning side until we hit mappedBy
  1323.         if (empty($mapping['indexBy'])) {
  1324.             unset($mapping['indexBy']);
  1325.         }
  1326.         // If targetEntity is unqualified, assume it is in the same namespace as
  1327.         // the sourceEntity.
  1328.         $mapping['sourceEntity'] = $this->name;
  1329.         if (isset($mapping['targetEntity'])) {
  1330.             $mapping['targetEntity'] = $this->fullyQualifiedClassName($mapping['targetEntity']);
  1331.             $mapping['targetEntity'] = ltrim($mapping['targetEntity'], '\\');
  1332.         }
  1333.         if (($mapping['type'] & self::MANY_TO_ONE) > && isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) {
  1334.             throw MappingException::illegalOrphanRemoval($this->name$mapping['fieldName']);
  1335.         }
  1336.         // Complete id mapping
  1337.         if (isset($mapping['id']) && $mapping['id'] === true) {
  1338.             if (isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) {
  1339.                 throw MappingException::illegalOrphanRemovalOnIdentifierAssociation($this->name$mapping['fieldName']);
  1340.             }
  1341.             if (! in_array($mapping['fieldName'], $this->identifier)) {
  1342.                 if (isset($mapping['joinColumns']) && count($mapping['joinColumns']) >= 2) {
  1343.                     throw MappingException::cannotMapCompositePrimaryKeyEntitiesAsForeignId(
  1344.                         $mapping['targetEntity'],
  1345.                         $this->name,
  1346.                         $mapping['fieldName']
  1347.                     );
  1348.                 }
  1349.                 $this->identifier[]              = $mapping['fieldName'];
  1350.                 $this->containsForeignIdentifier true;
  1351.             }
  1352.             // Check for composite key
  1353.             if (! $this->isIdentifierComposite && count($this->identifier) > 1) {
  1354.                 $this->isIdentifierComposite true;
  1355.             }
  1356.             if ($this->cache && ! isset($mapping['cache'])) {
  1357.                 throw CacheException::nonCacheableEntityAssociation($this->name$mapping['fieldName']);
  1358.             }
  1359.         }
  1360.         // Mandatory attributes for both sides
  1361.         // Mandatory: fieldName, targetEntity
  1362.         if (! isset($mapping['fieldName']) || ! $mapping['fieldName']) {
  1363.             throw MappingException::missingFieldName($this->name);
  1364.         }
  1365.         if (! isset($mapping['targetEntity'])) {
  1366.             throw MappingException::missingTargetEntity($mapping['fieldName']);
  1367.         }
  1368.         // Mandatory and optional attributes for either side
  1369.         if (! $mapping['mappedBy']) {
  1370.             if (isset($mapping['joinTable']) && $mapping['joinTable']) {
  1371.                 if (isset($mapping['joinTable']['name']) && $mapping['joinTable']['name'][0] === '`') {
  1372.                     $mapping['joinTable']['name']   = trim($mapping['joinTable']['name'], '`');
  1373.                     $mapping['joinTable']['quoted'] = true;
  1374.                 }
  1375.             }
  1376.         } else {
  1377.             $mapping['isOwningSide'] = false;
  1378.         }
  1379.         if (isset($mapping['id']) && $mapping['id'] === true && $mapping['type'] & self::TO_MANY) {
  1380.             throw MappingException::illegalToManyIdentifierAssociation($this->name$mapping['fieldName']);
  1381.         }
  1382.         // Fetch mode. Default fetch mode to LAZY, if not set.
  1383.         if (! isset($mapping['fetch'])) {
  1384.             $mapping['fetch'] = self::FETCH_LAZY;
  1385.         }
  1386.         // Cascades
  1387.         $cascades = isset($mapping['cascade']) ? array_map('strtolower'$mapping['cascade']) : [];
  1388.         $allCascades = ['remove''persist''refresh''merge''detach'];
  1389.         if (in_array('all'$cascades)) {
  1390.             $cascades $allCascades;
  1391.         } elseif (count($cascades) !== count(array_intersect($cascades$allCascades))) {
  1392.             throw MappingException::invalidCascadeOption(
  1393.                 array_diff($cascades$allCascades),
  1394.                 $this->name,
  1395.                 $mapping['fieldName']
  1396.             );
  1397.         }
  1398.         $mapping['cascade']          = $cascades;
  1399.         $mapping['isCascadeRemove']  = in_array('remove'$cascades);
  1400.         $mapping['isCascadePersist'] = in_array('persist'$cascades);
  1401.         $mapping['isCascadeRefresh'] = in_array('refresh'$cascades);
  1402.         $mapping['isCascadeMerge']   = in_array('merge'$cascades);
  1403.         $mapping['isCascadeDetach']  = in_array('detach'$cascades);
  1404.         return $mapping;
  1405.     }
  1406.     /**
  1407.      * Validates & completes a one-to-one association mapping.
  1408.      *
  1409.      * @param array $mapping The mapping to validate & complete.
  1410.      *
  1411.      * @return mixed[] The validated & completed mapping.
  1412.      *
  1413.      * @throws RuntimeException
  1414.      * @throws MappingException
  1415.      *
  1416.      * @psalm-return array{isOwningSide: mixed, orphanRemoval: bool, isCascadeRemove: bool}
  1417.      */
  1418.     protected function _validateAndCompleteOneToOneMapping(array $mapping)
  1419.     {
  1420.         $mapping $this->_validateAndCompleteAssociationMapping($mapping);
  1421.         if (isset($mapping['joinColumns']) && $mapping['joinColumns']) {
  1422.             $mapping['isOwningSide'] = true;
  1423.         }
  1424.         if ($mapping['isOwningSide']) {
  1425.             if (empty($mapping['joinColumns'])) {
  1426.                 // Apply default join column
  1427.                 $mapping['joinColumns'] = [
  1428.                     [
  1429.                         'name' => $this->namingStrategy->joinColumnName($mapping['fieldName'], $this->name),
  1430.                         'referencedColumnName' => $this->namingStrategy->referenceColumnName(),
  1431.                     ],
  1432.                 ];
  1433.             }
  1434.             $uniqueConstraintColumns = [];
  1435.             foreach ($mapping['joinColumns'] as &$joinColumn) {
  1436.                 if ($mapping['type'] === self::ONE_TO_ONE && ! $this->isInheritanceTypeSingleTable()) {
  1437.                     if (count($mapping['joinColumns']) === 1) {
  1438.                         if (empty($mapping['id'])) {
  1439.                             $joinColumn['unique'] = true;
  1440.                         }
  1441.                     } else {
  1442.                         $uniqueConstraintColumns[] = $joinColumn['name'];
  1443.                     }
  1444.                 }
  1445.                 if (empty($joinColumn['name'])) {
  1446.                     $joinColumn['name'] = $this->namingStrategy->joinColumnName($mapping['fieldName'], $this->name);
  1447.                 }
  1448.                 if (empty($joinColumn['referencedColumnName'])) {
  1449.                     $joinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName();
  1450.                 }
  1451.                 if ($joinColumn['name'][0] === '`') {
  1452.                     $joinColumn['name']   = trim($joinColumn['name'], '`');
  1453.                     $joinColumn['quoted'] = true;
  1454.                 }
  1455.                 if ($joinColumn['referencedColumnName'][0] === '`') {
  1456.                     $joinColumn['referencedColumnName'] = trim($joinColumn['referencedColumnName'], '`');
  1457.                     $joinColumn['quoted']               = true;
  1458.                 }
  1459.                 $mapping['sourceToTargetKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName'];
  1460.                 $mapping['joinColumnFieldNames'][$joinColumn['name']]     = $joinColumn['fieldName'] ?? $joinColumn['name'];
  1461.             }
  1462.             if ($uniqueConstraintColumns) {
  1463.                 if (! $this->table) {
  1464.                     throw new RuntimeException('ClassMetadataInfo::setTable() has to be called before defining a one to one relationship.');
  1465.                 }
  1466.                 $this->table['uniqueConstraints'][$mapping['fieldName'] . '_uniq'] = ['columns' => $uniqueConstraintColumns];
  1467.             }
  1468.             $mapping['targetToSourceKeyColumns'] = array_flip($mapping['sourceToTargetKeyColumns']);
  1469.         }
  1470.         $mapping['orphanRemoval']   = isset($mapping['orphanRemoval']) && $mapping['orphanRemoval'];
  1471.         $mapping['isCascadeRemove'] = $mapping['orphanRemoval'] || $mapping['isCascadeRemove'];
  1472.         if ($mapping['orphanRemoval']) {
  1473.             unset($mapping['unique']);
  1474.         }
  1475.         if (isset($mapping['id']) && $mapping['id'] === true && ! $mapping['isOwningSide']) {
  1476.             throw MappingException::illegalInverseIdentifierAssociation($this->name$mapping['fieldName']);
  1477.         }
  1478.         return $mapping;
  1479.     }
  1480.     /**
  1481.      * Validates & completes a one-to-many association mapping.
  1482.      *
  1483.      * @param array $mapping The mapping to validate and complete.
  1484.      *
  1485.      * @return mixed[] The validated and completed mapping.
  1486.      *
  1487.      * @throws MappingException
  1488.      * @throws InvalidArgumentException
  1489.      *
  1490.      * @psalm-return array{
  1491.      *                   mappedBy: mixed,
  1492.      *                   inversedBy: mixed,
  1493.      *                   isOwningSide: bool,
  1494.      *                   sourceEntity: string,
  1495.      *                   targetEntity: string,
  1496.      *                   fieldName: mixed,
  1497.      *                   fetch: int|mixed,
  1498.      *                   cascade: array<array-key,string>,
  1499.      *                   isCascadeRemove: bool,
  1500.      *                   isCascadePersist: bool,
  1501.      *                   isCascadeRefresh: bool,
  1502.      *                   isCascadeMerge: bool,
  1503.      *                   isCascadeDetach: bool,
  1504.      *                   orphanRemoval: bool
  1505.      *               }
  1506.      */
  1507.     protected function _validateAndCompleteOneToManyMapping(array $mapping)
  1508.     {
  1509.         $mapping $this->_validateAndCompleteAssociationMapping($mapping);
  1510.         // OneToMany-side MUST be inverse (must have mappedBy)
  1511.         if (! isset($mapping['mappedBy'])) {
  1512.             throw MappingException::oneToManyRequiresMappedBy($mapping['fieldName']);
  1513.         }
  1514.         $mapping['orphanRemoval']   = isset($mapping['orphanRemoval']) && $mapping['orphanRemoval'];
  1515.         $mapping['isCascadeRemove'] = $mapping['orphanRemoval'] || $mapping['isCascadeRemove'];
  1516.         $this->assertMappingOrderBy($mapping);
  1517.         return $mapping;
  1518.     }
  1519.     /**
  1520.      * Validates & completes a many-to-many association mapping.
  1521.      *
  1522.      * @param array $mapping The mapping to validate & complete.
  1523.      *
  1524.      * @return mixed[] The validated & completed mapping.
  1525.      *
  1526.      * @throws InvalidArgumentException
  1527.      *
  1528.      * @psalm-return array{isOwningSide: mixed, orphanRemoval: bool}
  1529.      */
  1530.     protected function _validateAndCompleteManyToManyMapping(array $mapping)
  1531.     {
  1532.         $mapping $this->_validateAndCompleteAssociationMapping($mapping);
  1533.         if ($mapping['isOwningSide']) {
  1534.             // owning side MUST have a join table
  1535.             if (! isset($mapping['joinTable']['name'])) {
  1536.                 $mapping['joinTable']['name'] = $this->namingStrategy->joinTableName($mapping['sourceEntity'], $mapping['targetEntity'], $mapping['fieldName']);
  1537.             }
  1538.             $selfReferencingEntityWithoutJoinColumns $mapping['sourceEntity'] === $mapping['targetEntity']
  1539.                 && (! (isset($mapping['joinTable']['joinColumns']) || isset($mapping['joinTable']['inverseJoinColumns'])));
  1540.             if (! isset($mapping['joinTable']['joinColumns'])) {
  1541.                 $mapping['joinTable']['joinColumns'] = [
  1542.                     [
  1543.                         'name' => $this->namingStrategy->joinKeyColumnName($mapping['sourceEntity'], $selfReferencingEntityWithoutJoinColumns 'source' null),
  1544.                         'referencedColumnName' => $this->namingStrategy->referenceColumnName(),
  1545.                         'onDelete' => 'CASCADE',
  1546.                     ],
  1547.                 ];
  1548.             }
  1549.             if (! isset($mapping['joinTable']['inverseJoinColumns'])) {
  1550.                 $mapping['joinTable']['inverseJoinColumns'] = [
  1551.                     [
  1552.                         'name' => $this->namingStrategy->joinKeyColumnName($mapping['targetEntity'], $selfReferencingEntityWithoutJoinColumns 'target' null),
  1553.                         'referencedColumnName' => $this->namingStrategy->referenceColumnName(),
  1554.                         'onDelete' => 'CASCADE',
  1555.                     ],
  1556.                 ];
  1557.             }
  1558.             $mapping['joinTableColumns'] = [];
  1559.             foreach ($mapping['joinTable']['joinColumns'] as &$joinColumn) {
  1560.                 if (empty($joinColumn['name'])) {
  1561.                     $joinColumn['name'] = $this->namingStrategy->joinKeyColumnName($mapping['sourceEntity'], $joinColumn['referencedColumnName']);
  1562.                 }
  1563.                 if (empty($joinColumn['referencedColumnName'])) {
  1564.                     $joinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName();
  1565.                 }
  1566.                 if ($joinColumn['name'][0] === '`') {
  1567.                     $joinColumn['name']   = trim($joinColumn['name'], '`');
  1568.                     $joinColumn['quoted'] = true;
  1569.                 }
  1570.                 if ($joinColumn['referencedColumnName'][0] === '`') {
  1571.                     $joinColumn['referencedColumnName'] = trim($joinColumn['referencedColumnName'], '`');
  1572.                     $joinColumn['quoted']               = true;
  1573.                 }
  1574.                 if (isset($joinColumn['onDelete']) && strtolower($joinColumn['onDelete']) === 'cascade') {
  1575.                     $mapping['isOnDeleteCascade'] = true;
  1576.                 }
  1577.                 $mapping['relationToSourceKeyColumns'][$joinColumn['name']] = $joinColumn['referencedColumnName'];
  1578.                 $mapping['joinTableColumns'][]                              = $joinColumn['name'];
  1579.             }
  1580.             foreach ($mapping['joinTable']['inverseJoinColumns'] as &$inverseJoinColumn) {
  1581.                 if (empty($inverseJoinColumn['name'])) {
  1582.                     $inverseJoinColumn['name'] = $this->namingStrategy->joinKeyColumnName($mapping['targetEntity'], $inverseJoinColumn['referencedColumnName']);
  1583.                 }
  1584.                 if (empty($inverseJoinColumn['referencedColumnName'])) {
  1585.                     $inverseJoinColumn['referencedColumnName'] = $this->namingStrategy->referenceColumnName();
  1586.                 }
  1587.                 if ($inverseJoinColumn['name'][0] === '`') {
  1588.                     $inverseJoinColumn['name']   = trim($inverseJoinColumn['name'], '`');
  1589.                     $inverseJoinColumn['quoted'] = true;
  1590.                 }
  1591.                 if ($inverseJoinColumn['referencedColumnName'][0] === '`') {
  1592.                     $inverseJoinColumn['referencedColumnName'] = trim($inverseJoinColumn['referencedColumnName'], '`');
  1593.                     $inverseJoinColumn['quoted']               = true;
  1594.                 }
  1595.                 if (isset($inverseJoinColumn['onDelete']) && strtolower($inverseJoinColumn['onDelete']) === 'cascade') {
  1596.                     $mapping['isOnDeleteCascade'] = true;
  1597.                 }
  1598.                 $mapping['relationToTargetKeyColumns'][$inverseJoinColumn['name']] = $inverseJoinColumn['referencedColumnName'];
  1599.                 $mapping['joinTableColumns'][]                                     = $inverseJoinColumn['name'];
  1600.             }
  1601.         }
  1602.         $mapping['orphanRemoval'] = isset($mapping['orphanRemoval']) && $mapping['orphanRemoval'];
  1603.         $this->assertMappingOrderBy($mapping);
  1604.         return $mapping;
  1605.     }
  1606.     /**
  1607.      * {@inheritDoc}
  1608.      */
  1609.     public function getIdentifierFieldNames()
  1610.     {
  1611.         return $this->identifier;
  1612.     }
  1613.     /**
  1614.      * Gets the name of the single id field. Note that this only works on
  1615.      * entity classes that have a single-field pk.
  1616.      *
  1617.      * @return string
  1618.      *
  1619.      * @throws MappingException If the class doesn't have an identifier or it has a composite primary key.
  1620.      */
  1621.     public function getSingleIdentifierFieldName()
  1622.     {
  1623.         if ($this->isIdentifierComposite) {
  1624.             throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->name);
  1625.         }
  1626.         if (! isset($this->identifier[0])) {
  1627.             throw MappingException::noIdDefined($this->name);
  1628.         }
  1629.         return $this->identifier[0];
  1630.     }
  1631.     /**
  1632.      * Gets the column name of the single id column. Note that this only works on
  1633.      * entity classes that have a single-field pk.
  1634.      *
  1635.      * @return string
  1636.      *
  1637.      * @throws MappingException If the class doesn't have an identifier or it has a composite primary key.
  1638.      */
  1639.     public function getSingleIdentifierColumnName()
  1640.     {
  1641.         return $this->getColumnName($this->getSingleIdentifierFieldName());
  1642.     }
  1643.     /**
  1644.      * INTERNAL:
  1645.      * Sets the mapped identifier/primary key fields of this class.
  1646.      * Mainly used by the ClassMetadataFactory to assign inherited identifiers.
  1647.      *
  1648.      * @param array $identifier
  1649.      *
  1650.      * @return void
  1651.      */
  1652.     public function setIdentifier(array $identifier)
  1653.     {
  1654.         $this->identifier            $identifier;
  1655.         $this->isIdentifierComposite = (count($this->identifier) > 1);
  1656.     }
  1657.     /**
  1658.      * {@inheritDoc}
  1659.      */
  1660.     public function getIdentifier()
  1661.     {
  1662.         return $this->identifier;
  1663.     }
  1664.     /**
  1665.      * {@inheritDoc}
  1666.      */
  1667.     public function hasField($fieldName)
  1668.     {
  1669.         return isset($this->fieldMappings[$fieldName]) || isset($this->embeddedClasses[$fieldName]);
  1670.     }
  1671.     /**
  1672.      * Gets an array containing all the column names.
  1673.      *
  1674.      * @param array|null $fieldNames
  1675.      *
  1676.      * @return mixed[]
  1677.      *
  1678.      * @psalm-return list<string>
  1679.      */
  1680.     public function getColumnNames(?array $fieldNames null)
  1681.     {
  1682.         if ($fieldNames === null) {
  1683.             return array_keys($this->fieldNames);
  1684.         }
  1685.         return array_values(array_map([$this'getColumnName'], $fieldNames));
  1686.     }
  1687.     /**
  1688.      * Returns an array with all the identifier column names.
  1689.      *
  1690.      * @return array
  1691.      */
  1692.     public function getIdentifierColumnNames()
  1693.     {
  1694.         $columnNames = [];
  1695.         foreach ($this->identifier as $idProperty) {
  1696.             if (isset($this->fieldMappings[$idProperty])) {
  1697.                 $columnNames[] = $this->fieldMappings[$idProperty]['columnName'];
  1698.                 continue;
  1699.             }
  1700.             // Association defined as Id field
  1701.             $joinColumns      $this->associationMappings[$idProperty]['joinColumns'];
  1702.             $assocColumnNames array_map(static function ($joinColumn) {
  1703.                 return $joinColumn['name'];
  1704.             }, $joinColumns);
  1705.             $columnNames array_merge($columnNames$assocColumnNames);
  1706.         }
  1707.         return $columnNames;
  1708.     }
  1709.     /**
  1710.      * Sets the type of Id generator to use for the mapped class.
  1711.      *
  1712.      * @param int $generatorType
  1713.      *
  1714.      * @return void
  1715.      */
  1716.     public function setIdGeneratorType($generatorType)
  1717.     {
  1718.         $this->generatorType $generatorType;
  1719.     }
  1720.     /**
  1721.      * Checks whether the mapped class uses an Id generator.
  1722.      *
  1723.      * @return bool TRUE if the mapped class uses an Id generator, FALSE otherwise.
  1724.      */
  1725.     public function usesIdGenerator()
  1726.     {
  1727.         return $this->generatorType !== self::GENERATOR_TYPE_NONE;
  1728.     }
  1729.     /**
  1730.      * @return bool
  1731.      */
  1732.     public function isInheritanceTypeNone()
  1733.     {
  1734.         return $this->inheritanceType === self::INHERITANCE_TYPE_NONE;
  1735.     }
  1736.     /**
  1737.      * Checks whether the mapped class uses the JOINED inheritance mapping strategy.
  1738.      *
  1739.      * @return bool TRUE if the class participates in a JOINED inheritance mapping,
  1740.      * FALSE otherwise.
  1741.      */
  1742.     public function isInheritanceTypeJoined()
  1743.     {
  1744.         return $this->inheritanceType === self::INHERITANCE_TYPE_JOINED;
  1745.     }
  1746.     /**
  1747.      * Checks whether the mapped class uses the SINGLE_TABLE inheritance mapping strategy.
  1748.      *
  1749.      * @return bool TRUE if the class participates in a SINGLE_TABLE inheritance mapping,
  1750.      * FALSE otherwise.
  1751.      */
  1752.     public function isInheritanceTypeSingleTable()
  1753.     {
  1754.         return $this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_TABLE;
  1755.     }
  1756.     /**
  1757.      * Checks whether the mapped class uses the TABLE_PER_CLASS inheritance mapping strategy.
  1758.      *
  1759.      * @return bool TRUE if the class participates in a TABLE_PER_CLASS inheritance mapping,
  1760.      * FALSE otherwise.
  1761.      */
  1762.     public function isInheritanceTypeTablePerClass()
  1763.     {
  1764.         return $this->inheritanceType === self::INHERITANCE_TYPE_TABLE_PER_CLASS;
  1765.     }
  1766.     /**
  1767.      * Checks whether the class uses an identity column for the Id generation.
  1768.      *
  1769.      * @return bool TRUE if the class uses the IDENTITY generator, FALSE otherwise.
  1770.      */
  1771.     public function isIdGeneratorIdentity()
  1772.     {
  1773.         return $this->generatorType === self::GENERATOR_TYPE_IDENTITY;
  1774.     }
  1775.     /**
  1776.      * Checks whether the class uses a sequence for id generation.
  1777.      *
  1778.      * @return bool TRUE if the class uses the SEQUENCE generator, FALSE otherwise.
  1779.      */
  1780.     public function isIdGeneratorSequence()
  1781.     {
  1782.         return $this->generatorType === self::GENERATOR_TYPE_SEQUENCE;
  1783.     }
  1784.     /**
  1785.      * Checks whether the class uses a table for id generation.
  1786.      *
  1787.      * @return bool TRUE if the class uses the TABLE generator, FALSE otherwise.
  1788.      */
  1789.     public function isIdGeneratorTable()
  1790.     {
  1791.         return $this->generatorType === self::GENERATOR_TYPE_TABLE;
  1792.     }
  1793.     /**
  1794.      * Checks whether the class has a natural identifier/pk (which means it does
  1795.      * not use any Id generator.
  1796.      *
  1797.      * @return bool
  1798.      */
  1799.     public function isIdentifierNatural()
  1800.     {
  1801.         return $this->generatorType === self::GENERATOR_TYPE_NONE;
  1802.     }
  1803.     /**
  1804.      * Checks whether the class use a UUID for id generation.
  1805.      *
  1806.      * @return bool
  1807.      */
  1808.     public function isIdentifierUuid()
  1809.     {
  1810.         return $this->generatorType === self::GENERATOR_TYPE_UUID;
  1811.     }
  1812.     /**
  1813.      * Gets the type of a field.
  1814.      *
  1815.      * @param string $fieldName
  1816.      *
  1817.      * @return string|null
  1818.      *
  1819.      * @todo 3.0 Remove this. PersisterHelper should fix it somehow
  1820.      */
  1821.     public function getTypeOfField($fieldName)
  1822.     {
  1823.         return isset($this->fieldMappings[$fieldName])
  1824.             ? $this->fieldMappings[$fieldName]['type']
  1825.             : null;
  1826.     }
  1827.     /**
  1828.      * Gets the type of a column.
  1829.      *
  1830.      * @deprecated 3.0 remove this. this method is bogus and unreliable, since it cannot resolve the type of a column
  1831.      *             that is derived by a referenced field on a different entity.
  1832.      *
  1833.      * @param string $columnName
  1834.      *
  1835.      * @return string|null
  1836.      */
  1837.     public function getTypeOfColumn($columnName)
  1838.     {
  1839.         return $this->getTypeOfField($this->getFieldName($columnName));
  1840.     }
  1841.     /**
  1842.      * Gets the name of the primary table.
  1843.      *
  1844.      * @return string
  1845.      */
  1846.     public function getTableName()
  1847.     {
  1848.         return $this->table['name'];
  1849.     }
  1850.     /**
  1851.      * Gets primary table's schema name.
  1852.      *
  1853.      * @return string|null
  1854.      */
  1855.     public function getSchemaName()
  1856.     {
  1857.         return $this->table['schema'] ?? null;
  1858.     }
  1859.     /**
  1860.      * Gets the table name to use for temporary identifier tables of this class.
  1861.      *
  1862.      * @return string
  1863.      */
  1864.     public function getTemporaryIdTableName()
  1865.     {
  1866.         // replace dots with underscores because PostgreSQL creates temporary tables in a special schema
  1867.         return str_replace('.''_'$this->getTableName() . '_id_tmp');
  1868.     }
  1869.     /**
  1870.      * Sets the mapped subclasses of this class.
  1871.      *
  1872.      * @param array $subclasses The names of all mapped subclasses.
  1873.      *
  1874.      * @return void
  1875.      */
  1876.     public function setSubclasses(array $subclasses)
  1877.     {
  1878.         foreach ($subclasses as $subclass) {
  1879.             $this->subClasses[] = $this->fullyQualifiedClassName($subclass);
  1880.         }
  1881.     }
  1882.     /**
  1883.      * Sets the parent class names.
  1884.      * Assumes that the class names in the passed array are in the order:
  1885.      * directParent -> directParentParent -> directParentParentParent ... -> root.
  1886.      *
  1887.      * @param array $classNames
  1888.      *
  1889.      * @return void
  1890.      */
  1891.     public function setParentClasses(array $classNames)
  1892.     {
  1893.         $this->parentClasses $classNames;
  1894.         if (count($classNames) > 0) {
  1895.             $this->rootEntityName array_pop($classNames);
  1896.         }
  1897.     }
  1898.     /**
  1899.      * Sets the inheritance type used by the class and its subclasses.
  1900.      *
  1901.      * @param int $type
  1902.      *
  1903.      * @return void
  1904.      *
  1905.      * @throws MappingException
  1906.      */
  1907.     public function setInheritanceType($type)
  1908.     {
  1909.         if (! $this->_isInheritanceType($type)) {
  1910.             throw MappingException::invalidInheritanceType($this->name$type);
  1911.         }
  1912.         $this->inheritanceType $type;
  1913.     }
  1914.     /**
  1915.      * Sets the association to override association mapping of property for an entity relationship.
  1916.      *
  1917.      * @param string $fieldName
  1918.      * @param array  $overrideMapping
  1919.      *
  1920.      * @return void
  1921.      *
  1922.      * @throws MappingException
  1923.      */
  1924.     public function setAssociationOverride($fieldName, array $overrideMapping)
  1925.     {
  1926.         if (! isset($this->associationMappings[$fieldName])) {
  1927.             throw MappingException::invalidOverrideFieldName($this->name$fieldName);
  1928.         }
  1929.         $mapping $this->associationMappings[$fieldName];
  1930.         //if (isset($mapping['inherited']) && (count($overrideMapping) !== 1 || ! isset($overrideMapping['fetch']))) {
  1931.             // TODO: Deprecate overriding the fetch mode via association override for 3.0,
  1932.             // users should do this with a listener and a custom attribute/annotation
  1933.             // TODO: Enable this exception in 2.8
  1934.             //throw MappingException::illegalOverrideOfInheritedProperty($this->name, $fieldName);
  1935.         //}
  1936.         if (isset($overrideMapping['joinColumns'])) {
  1937.             $mapping['joinColumns'] = $overrideMapping['joinColumns'];
  1938.         }
  1939.         if (isset($overrideMapping['inversedBy'])) {
  1940.             $mapping['inversedBy'] = $overrideMapping['inversedBy'];
  1941.         }
  1942.         if (isset($overrideMapping['joinTable'])) {
  1943.             $mapping['joinTable'] = $overrideMapping['joinTable'];
  1944.         }
  1945.         if (isset($overrideMapping['fetch'])) {
  1946.             $mapping['fetch'] = $overrideMapping['fetch'];
  1947.         }
  1948.         $mapping['joinColumnFieldNames']       = null;
  1949.         $mapping['joinTableColumns']           = null;
  1950.         $mapping['sourceToTargetKeyColumns']   = null;
  1951.         $mapping['relationToSourceKeyColumns'] = null;
  1952.         $mapping['relationToTargetKeyColumns'] = null;
  1953.         switch ($mapping['type']) {
  1954.             case self::ONE_TO_ONE:
  1955.                 $mapping $this->_validateAndCompleteOneToOneMapping($mapping);
  1956.                 break;
  1957.             case self::ONE_TO_MANY:
  1958.                 $mapping $this->_validateAndCompleteOneToManyMapping($mapping);
  1959.                 break;
  1960.             case self::MANY_TO_ONE:
  1961.                 $mapping $this->_validateAndCompleteOneToOneMapping($mapping);
  1962.                 break;
  1963.             case self::MANY_TO_MANY:
  1964.                 $mapping $this->_validateAndCompleteManyToManyMapping($mapping);
  1965.                 break;
  1966.         }
  1967.         $this->associationMappings[$fieldName] = $mapping;
  1968.     }
  1969.     /**
  1970.      * Sets the override for a mapped field.
  1971.      *
  1972.      * @param string $fieldName
  1973.      * @param array  $overrideMapping
  1974.      *
  1975.      * @return void
  1976.      *
  1977.      * @throws MappingException
  1978.      */
  1979.     public function setAttributeOverride($fieldName, array $overrideMapping)
  1980.     {
  1981.         if (! isset($this->fieldMappings[$fieldName])) {
  1982.             throw MappingException::invalidOverrideFieldName($this->name$fieldName);
  1983.         }
  1984.         $mapping $this->fieldMappings[$fieldName];
  1985.         //if (isset($mapping['inherited'])) {
  1986.             // TODO: Enable this exception in 2.8
  1987.             //throw MappingException::illegalOverrideOfInheritedProperty($this->name, $fieldName);
  1988.         //}
  1989.         if (isset($mapping['id'])) {
  1990.             $overrideMapping['id'] = $mapping['id'];
  1991.         }
  1992.         if (! isset($overrideMapping['type'])) {
  1993.             $overrideMapping['type'] = $mapping['type'];
  1994.         }
  1995.         if (! isset($overrideMapping['fieldName'])) {
  1996.             $overrideMapping['fieldName'] = $mapping['fieldName'];
  1997.         }
  1998.         if ($overrideMapping['type'] !== $mapping['type']) {
  1999.             throw MappingException::invalidOverrideFieldType($this->name$fieldName);
  2000.         }
  2001.         unset($this->fieldMappings[$fieldName]);
  2002.         unset($this->fieldNames[$mapping['columnName']]);
  2003.         unset($this->columnNames[$mapping['fieldName']]);
  2004.         $this->_validateAndCompleteFieldMapping($overrideMapping);
  2005.         $this->fieldMappings[$fieldName] = $overrideMapping;
  2006.     }
  2007.     /**
  2008.      * Checks whether a mapped field is inherited from an entity superclass.
  2009.      *
  2010.      * @param string $fieldName
  2011.      *
  2012.      * @return bool TRUE if the field is inherited, FALSE otherwise.
  2013.      */
  2014.     public function isInheritedField($fieldName)
  2015.     {
  2016.         return isset($this->fieldMappings[$fieldName]['inherited']);
  2017.     }
  2018.     /**
  2019.      * Checks if this entity is the root in any entity-inheritance-hierarchy.
  2020.      *
  2021.      * @return bool
  2022.      */
  2023.     public function isRootEntity()
  2024.     {
  2025.         return $this->name === $this->rootEntityName;
  2026.     }
  2027.     /**
  2028.      * Checks whether a mapped association field is inherited from a superclass.
  2029.      *
  2030.      * @param string $fieldName
  2031.      *
  2032.      * @return bool TRUE if the field is inherited, FALSE otherwise.
  2033.      */
  2034.     public function isInheritedAssociation($fieldName)
  2035.     {
  2036.         return isset($this->associationMappings[$fieldName]['inherited']);
  2037.     }
  2038.     public function isInheritedEmbeddedClass($fieldName)
  2039.     {
  2040.         return isset($this->embeddedClasses[$fieldName]['inherited']);
  2041.     }
  2042.     /**
  2043.      * Sets the name of the primary table the class is mapped to.
  2044.      *
  2045.      * @deprecated Use {@link setPrimaryTable}.
  2046.      *
  2047.      * @param string $tableName The table name.
  2048.      *
  2049.      * @return void
  2050.      */
  2051.     public function setTableName($tableName)
  2052.     {
  2053.         $this->table['name'] = $tableName;
  2054.     }
  2055.     /**
  2056.      * Sets the primary table definition. The provided array supports the
  2057.      * following structure:
  2058.      *
  2059.      * name => <tableName> (optional, defaults to class name)
  2060.      * indexes => array of indexes (optional)
  2061.      * uniqueConstraints => array of constraints (optional)
  2062.      *
  2063.      * If a key is omitted, the current value is kept.
  2064.      *
  2065.      * @param array $table The table description.
  2066.      *
  2067.      * @return void
  2068.      */
  2069.     public function setPrimaryTable(array $table)
  2070.     {
  2071.         if (isset($table['name'])) {
  2072.             // Split schema and table name from a table name like "myschema.mytable"
  2073.             if (strpos($table['name'], '.') !== false) {
  2074.                 [$this->table['schema'], $table['name']] = explode('.'$table['name'], 2);
  2075.             }
  2076.             if ($table['name'][0] === '`') {
  2077.                 $table['name']         = trim($table['name'], '`');
  2078.                 $this->table['quoted'] = true;
  2079.             }
  2080.             $this->table['name'] = $table['name'];
  2081.         }
  2082.         if (isset($table['quoted'])) {
  2083.             $this->table['quoted'] = $table['quoted'];
  2084.         }
  2085.         if (isset($table['schema'])) {
  2086.             $this->table['schema'] = $table['schema'];
  2087.         }
  2088.         if (isset($table['indexes'])) {
  2089.             $this->table['indexes'] = $table['indexes'];
  2090.         }
  2091.         if (isset($table['uniqueConstraints'])) {
  2092.             $this->table['uniqueConstraints'] = $table['uniqueConstraints'];
  2093.         }
  2094.         if (isset($table['options'])) {
  2095.             $this->table['options'] = $table['options'];
  2096.         }
  2097.     }
  2098.     /**
  2099.      * Checks whether the given type identifies an inheritance type.
  2100.      *
  2101.      * @param int $type
  2102.      *
  2103.      * @return bool TRUE if the given type identifies an inheritance type, FALSe otherwise.
  2104.      */
  2105.     private function _isInheritanceType($type)
  2106.     {
  2107.         return $type === self::INHERITANCE_TYPE_NONE ||
  2108.                 $type === self::INHERITANCE_TYPE_SINGLE_TABLE ||
  2109.                 $type === self::INHERITANCE_TYPE_JOINED ||
  2110.                 $type === self::INHERITANCE_TYPE_TABLE_PER_CLASS;
  2111.     }
  2112.     /**
  2113.      * Adds a mapped field to the class.
  2114.      *
  2115.      * @param array $mapping The field mapping.
  2116.      *
  2117.      * @return void
  2118.      *
  2119.      * @throws MappingException
  2120.      */
  2121.     public function mapField(array $mapping)
  2122.     {
  2123.         $this->_validateAndCompleteFieldMapping($mapping);
  2124.         $this->assertFieldNotMapped($mapping['fieldName']);
  2125.         $this->fieldMappings[$mapping['fieldName']] = $mapping;
  2126.     }
  2127.     /**
  2128.      * INTERNAL:
  2129.      * Adds an association mapping without completing/validating it.
  2130.      * This is mainly used to add inherited association mappings to derived classes.
  2131.      *
  2132.      * @param array $mapping
  2133.      *
  2134.      * @return void
  2135.      *
  2136.      * @throws MappingException
  2137.      */
  2138.     public function addInheritedAssociationMapping(array $mapping/*, $owningClassName = null*/)
  2139.     {
  2140.         if (isset($this->associationMappings[$mapping['fieldName']])) {
  2141.             throw MappingException::duplicateAssociationMapping($this->name$mapping['fieldName']);
  2142.         }
  2143.         $this->associationMappings[$mapping['fieldName']] = $mapping;
  2144.     }
  2145.     /**
  2146.      * INTERNAL:
  2147.      * Adds a field mapping without completing/validating it.
  2148.      * This is mainly used to add inherited field mappings to derived classes.
  2149.      *
  2150.      * @param array $fieldMapping
  2151.      *
  2152.      * @return void
  2153.      */
  2154.     public function addInheritedFieldMapping(array $fieldMapping)
  2155.     {
  2156.         $this->fieldMappings[$fieldMapping['fieldName']] = $fieldMapping;
  2157.         $this->columnNames[$fieldMapping['fieldName']]   = $fieldMapping['columnName'];
  2158.         $this->fieldNames[$fieldMapping['columnName']]   = $fieldMapping['fieldName'];
  2159.     }
  2160.     /**
  2161.      * INTERNAL:
  2162.      * Adds a named query to this class.
  2163.      *
  2164.      * @param array $queryMapping
  2165.      *
  2166.      * @return void
  2167.      *
  2168.      * @throws MappingException
  2169.      */
  2170.     public function addNamedQuery(array $queryMapping)
  2171.     {
  2172.         if (! isset($queryMapping['name'])) {
  2173.             throw MappingException::nameIsMandatoryForQueryMapping($this->name);
  2174.         }
  2175.         if (isset($this->namedQueries[$queryMapping['name']])) {
  2176.             throw MappingException::duplicateQueryMapping($this->name$queryMapping['name']);
  2177.         }
  2178.         if (! isset($queryMapping['query'])) {
  2179.             throw MappingException::emptyQueryMapping($this->name$queryMapping['name']);
  2180.         }
  2181.         $name  $queryMapping['name'];
  2182.         $query $queryMapping['query'];
  2183.         $dql   str_replace('__CLASS__'$this->name$query);
  2184.         $this->namedQueries[$name] = [
  2185.             'name'  => $name,
  2186.             'query' => $query,
  2187.             'dql'   => $dql,
  2188.         ];
  2189.     }
  2190.     /**
  2191.      * INTERNAL:
  2192.      * Adds a named native query to this class.
  2193.      *
  2194.      * @param array $queryMapping
  2195.      *
  2196.      * @return void
  2197.      *
  2198.      * @throws MappingException
  2199.      */
  2200.     public function addNamedNativeQuery(array $queryMapping)
  2201.     {
  2202.         if (! isset($queryMapping['name'])) {
  2203.             throw MappingException::nameIsMandatoryForQueryMapping($this->name);
  2204.         }
  2205.         if (isset($this->namedNativeQueries[$queryMapping['name']])) {
  2206.             throw MappingException::duplicateQueryMapping($this->name$queryMapping['name']);
  2207.         }
  2208.         if (! isset($queryMapping['query'])) {
  2209.             throw MappingException::emptyQueryMapping($this->name$queryMapping['name']);
  2210.         }
  2211.         if (! isset($queryMapping['resultClass']) && ! isset($queryMapping['resultSetMapping'])) {
  2212.             throw MappingException::missingQueryMapping($this->name$queryMapping['name']);
  2213.         }
  2214.         $queryMapping['isSelfClass'] = false;
  2215.         if (isset($queryMapping['resultClass'])) {
  2216.             if ($queryMapping['resultClass'] === '__CLASS__') {
  2217.                 $queryMapping['isSelfClass'] = true;
  2218.                 $queryMapping['resultClass'] = $this->name;
  2219.             }
  2220.             $queryMapping['resultClass'] = $this->fullyQualifiedClassName($queryMapping['resultClass']);
  2221.             $queryMapping['resultClass'] = ltrim($queryMapping['resultClass'], '\\');
  2222.         }
  2223.         $this->namedNativeQueries[$queryMapping['name']] = $queryMapping;
  2224.     }
  2225.     /**
  2226.      * INTERNAL:
  2227.      * Adds a sql result set mapping to this class.
  2228.      *
  2229.      * @param array $resultMapping
  2230.      *
  2231.      * @return void
  2232.      *
  2233.      * @throws MappingException
  2234.      */
  2235.     public function addSqlResultSetMapping(array $resultMapping)
  2236.     {
  2237.         if (! isset($resultMapping['name'])) {
  2238.             throw MappingException::nameIsMandatoryForSqlResultSetMapping($this->name);
  2239.         }
  2240.         if (isset($this->sqlResultSetMappings[$resultMapping['name']])) {
  2241.             throw MappingException::duplicateResultSetMapping($this->name$resultMapping['name']);
  2242.         }
  2243.         if (isset($resultMapping['entities'])) {
  2244.             foreach ($resultMapping['entities'] as $key => $entityResult) {
  2245.                 if (! isset($entityResult['entityClass'])) {
  2246.                     throw MappingException::missingResultSetMappingEntity($this->name$resultMapping['name']);
  2247.                 }
  2248.                 $entityResult['isSelfClass'] = false;
  2249.                 if ($entityResult['entityClass'] === '__CLASS__') {
  2250.                     $entityResult['isSelfClass'] = true;
  2251.                     $entityResult['entityClass'] = $this->name;
  2252.                 }
  2253.                 $entityResult['entityClass'] = $this->fullyQualifiedClassName($entityResult['entityClass']);
  2254.                 $resultMapping['entities'][$key]['entityClass'] = ltrim($entityResult['entityClass'], '\\');
  2255.                 $resultMapping['entities'][$key]['isSelfClass'] = $entityResult['isSelfClass'];
  2256.                 if (isset($entityResult['fields'])) {
  2257.                     foreach ($entityResult['fields'] as $k => $field) {
  2258.                         if (! isset($field['name'])) {
  2259.                             throw MappingException::missingResultSetMappingFieldName($this->name$resultMapping['name']);
  2260.                         }
  2261.                         if (! isset($field['column'])) {
  2262.                             $fieldName $field['name'];
  2263.                             if (strpos($fieldName'.')) {
  2264.                                 [, $fieldName] = explode('.'$fieldName);
  2265.                             }
  2266.                             $resultMapping['entities'][$key]['fields'][$k]['column'] = $fieldName;
  2267.                         }
  2268.                     }
  2269.                 }
  2270.             }
  2271.         }
  2272.         $this->sqlResultSetMappings[$resultMapping['name']] = $resultMapping;
  2273.     }
  2274.     /**
  2275.      * Adds a one-to-one mapping.
  2276.      *
  2277.      * @param array $mapping The mapping.
  2278.      *
  2279.      * @return void
  2280.      */
  2281.     public function mapOneToOne(array $mapping)
  2282.     {
  2283.         $mapping['type'] = self::ONE_TO_ONE;
  2284.         $mapping $this->_validateAndCompleteOneToOneMapping($mapping);
  2285.         $this->_storeAssociationMapping($mapping);
  2286.     }
  2287.     /**
  2288.      * Adds a one-to-many mapping.
  2289.      *
  2290.      * @param array $mapping The mapping.
  2291.      *
  2292.      * @return void
  2293.      */
  2294.     public function mapOneToMany(array $mapping)
  2295.     {
  2296.         $mapping['type'] = self::ONE_TO_MANY;
  2297.         $mapping $this->_validateAndCompleteOneToManyMapping($mapping);
  2298.         $this->_storeAssociationMapping($mapping);
  2299.     }
  2300.     /**
  2301.      * Adds a many-to-one mapping.
  2302.      *
  2303.      * @param array $mapping The mapping.
  2304.      *
  2305.      * @return void
  2306.      */
  2307.     public function mapManyToOne(array $mapping)
  2308.     {
  2309.         $mapping['type'] = self::MANY_TO_ONE;
  2310.         // A many-to-one mapping is essentially a one-one backreference
  2311.         $mapping $this->_validateAndCompleteOneToOneMapping($mapping);
  2312.         $this->_storeAssociationMapping($mapping);
  2313.     }
  2314.     /**
  2315.      * Adds a many-to-many mapping.
  2316.      *
  2317.      * @param array $mapping The mapping.
  2318.      *
  2319.      * @return void
  2320.      */
  2321.     public function mapManyToMany(array $mapping)
  2322.     {
  2323.         $mapping['type'] = self::MANY_TO_MANY;
  2324.         $mapping $this->_validateAndCompleteManyToManyMapping($mapping);
  2325.         $this->_storeAssociationMapping($mapping);
  2326.     }
  2327.     /**
  2328.      * Stores the association mapping.
  2329.      *
  2330.      * @param array $assocMapping
  2331.      *
  2332.      * @return void
  2333.      *
  2334.      * @throws MappingException
  2335.      */
  2336.     protected function _storeAssociationMapping(array $assocMapping)
  2337.     {
  2338.         $sourceFieldName $assocMapping['fieldName'];
  2339.         $this->assertFieldNotMapped($sourceFieldName);
  2340.         $this->associationMappings[$sourceFieldName] = $assocMapping;
  2341.     }
  2342.     /**
  2343.      * Registers a custom repository class for the entity class.
  2344.      *
  2345.      * @param string $repositoryClassName The class name of the custom mapper.
  2346.      *
  2347.      * @return void
  2348.      *
  2349.      * @psalm-param class-string $repositoryClassName
  2350.      */
  2351.     public function setCustomRepositoryClass($repositoryClassName)
  2352.     {
  2353.         $this->customRepositoryClassName $this->fullyQualifiedClassName($repositoryClassName);
  2354.     }
  2355.     /**
  2356.      * Dispatches the lifecycle event of the given entity to the registered
  2357.      * lifecycle callbacks and lifecycle listeners.
  2358.      *
  2359.      * @deprecated Deprecated since version 2.4 in favor of \Doctrine\ORM\Event\ListenersInvoker
  2360.      *
  2361.      * @param string $lifecycleEvent The lifecycle event.
  2362.      * @param object $entity         The Entity on which the event occurred.
  2363.      *
  2364.      * @return void
  2365.      */
  2366.     public function invokeLifecycleCallbacks($lifecycleEvent$entity)
  2367.     {
  2368.         foreach ($this->lifecycleCallbacks[$lifecycleEvent] as $callback) {
  2369.             $entity->$callback();
  2370.         }
  2371.     }
  2372.     /**
  2373.      * Whether the class has any attached lifecycle listeners or callbacks for a lifecycle event.
  2374.      *
  2375.      * @param string $lifecycleEvent
  2376.      *
  2377.      * @return bool
  2378.      */
  2379.     public function hasLifecycleCallbacks($lifecycleEvent)
  2380.     {
  2381.         return isset($this->lifecycleCallbacks[$lifecycleEvent]);
  2382.     }
  2383.     /**
  2384.      * Gets the registered lifecycle callbacks for an event.
  2385.      *
  2386.      * @param string $event
  2387.      *
  2388.      * @return array
  2389.      */
  2390.     public function getLifecycleCallbacks($event)
  2391.     {
  2392.         return $this->lifecycleCallbacks[$event] ?? [];
  2393.     }
  2394.     /**
  2395.      * Adds a lifecycle callback for entities of this class.
  2396.      *
  2397.      * @param string $callback
  2398.      * @param string $event
  2399.      *
  2400.      * @return void
  2401.      */
  2402.     public function addLifecycleCallback($callback$event)
  2403.     {
  2404.         if (isset($this->lifecycleCallbacks[$event]) && in_array($callback$this->lifecycleCallbacks[$event])) {
  2405.             return;
  2406.         }
  2407.         $this->lifecycleCallbacks[$event][] = $callback;
  2408.     }
  2409.     /**
  2410.      * Sets the lifecycle callbacks for entities of this class.
  2411.      * Any previously registered callbacks are overwritten.
  2412.      *
  2413.      * @param array $callbacks
  2414.      *
  2415.      * @return void
  2416.      */
  2417.     public function setLifecycleCallbacks(array $callbacks)
  2418.     {
  2419.         $this->lifecycleCallbacks $callbacks;
  2420.     }
  2421.     /**
  2422.      * Adds a entity listener for entities of this class.
  2423.      *
  2424.      * @param string $eventName The entity lifecycle event.
  2425.      * @param string $class     The listener class.
  2426.      * @param string $method    The listener callback method.
  2427.      *
  2428.      * @throws MappingException
  2429.      */
  2430.     public function addEntityListener($eventName$class$method)
  2431.     {
  2432.         $class $this->fullyQualifiedClassName($class);
  2433.         $listener = [
  2434.             'class'  => $class,
  2435.             'method' => $method,
  2436.         ];
  2437.         if (! class_exists($class)) {
  2438.             throw MappingException::entityListenerClassNotFound($class$this->name);
  2439.         }
  2440.         if (! method_exists($class$method)) {
  2441.             throw MappingException::entityListenerMethodNotFound($class$method$this->name);
  2442.         }
  2443.         if (isset($this->entityListeners[$eventName]) && in_array($listener$this->entityListeners[$eventName])) {
  2444.             throw MappingException::duplicateEntityListener($class$method$this->name);
  2445.         }
  2446.         $this->entityListeners[$eventName][] = $listener;
  2447.     }
  2448.     /**
  2449.      * Sets the discriminator column definition.
  2450.      *
  2451.      * @see getDiscriminatorColumn()
  2452.      *
  2453.      * @param array $columnDef
  2454.      *
  2455.      * @return void
  2456.      *
  2457.      * @throws MappingException
  2458.      */
  2459.     public function setDiscriminatorColumn($columnDef)
  2460.     {
  2461.         if ($columnDef !== null) {
  2462.             if (! isset($columnDef['name'])) {
  2463.                 throw MappingException::nameIsMandatoryForDiscriminatorColumns($this->name);
  2464.             }
  2465.             if (isset($this->fieldNames[$columnDef['name']])) {
  2466.                 throw MappingException::duplicateColumnName($this->name$columnDef['name']);
  2467.             }
  2468.             if (! isset($columnDef['fieldName'])) {
  2469.                 $columnDef['fieldName'] = $columnDef['name'];
  2470.             }
  2471.             if (! isset($columnDef['type'])) {
  2472.                 $columnDef['type'] = 'string';
  2473.             }
  2474.             if (in_array($columnDef['type'], ['boolean''array''object''datetime''time''date'])) {
  2475.                 throw MappingException::invalidDiscriminatorColumnType($this->name$columnDef['type']);
  2476.             }
  2477.             $this->discriminatorColumn $columnDef;
  2478.         }
  2479.     }
  2480.     /**
  2481.      * Sets the discriminator values used by this class.
  2482.      * Used for JOINED and SINGLE_TABLE inheritance mapping strategies.
  2483.      *
  2484.      * @param array $map
  2485.      *
  2486.      * @return void
  2487.      */
  2488.     public function setDiscriminatorMap(array $map)
  2489.     {
  2490.         foreach ($map as $value => $className) {
  2491.             $this->addDiscriminatorMapClass($value$className);
  2492.         }
  2493.     }
  2494.     /**
  2495.      * Adds one entry of the discriminator map with a new class and corresponding name.
  2496.      *
  2497.      * @param string $name
  2498.      * @param string $className
  2499.      *
  2500.      * @return void
  2501.      *
  2502.      * @throws MappingException
  2503.      */
  2504.     public function addDiscriminatorMapClass($name$className)
  2505.     {
  2506.         $className $this->fullyQualifiedClassName($className);
  2507.         $className ltrim($className'\\');
  2508.         $this->discriminatorMap[$name] = $className;
  2509.         if ($this->name === $className) {
  2510.             $this->discriminatorValue $name;
  2511.             return;
  2512.         }
  2513.         if (! (class_exists($className) || interface_exists($className))) {
  2514.             throw MappingException::invalidClassInDiscriminatorMap($className$this->name);
  2515.         }
  2516.         if (is_subclass_of($className$this->name) && ! in_array($className$this->subClasses)) {
  2517.             $this->subClasses[] = $className;
  2518.         }
  2519.     }
  2520.     /**
  2521.      * Checks whether the class has a named query with the given query name.
  2522.      *
  2523.      * @param string $queryName
  2524.      *
  2525.      * @return bool
  2526.      */
  2527.     public function hasNamedQuery($queryName)
  2528.     {
  2529.         return isset($this->namedQueries[$queryName]);
  2530.     }
  2531.     /**
  2532.      * Checks whether the class has a named native query with the given query name.
  2533.      *
  2534.      * @param string $queryName
  2535.      *
  2536.      * @return bool
  2537.      */
  2538.     public function hasNamedNativeQuery($queryName)
  2539.     {
  2540.         return isset($this->namedNativeQueries[$queryName]);
  2541.     }
  2542.     /**
  2543.      * Checks whether the class has a named native query with the given query name.
  2544.      *
  2545.      * @param string $name
  2546.      *
  2547.      * @return bool
  2548.      */
  2549.     public function hasSqlResultSetMapping($name)
  2550.     {
  2551.         return isset($this->sqlResultSetMappings[$name]);
  2552.     }
  2553.     /**
  2554.      * {@inheritDoc}
  2555.      */
  2556.     public function hasAssociation($fieldName)
  2557.     {
  2558.         return isset($this->associationMappings[$fieldName]);
  2559.     }
  2560.     /**
  2561.      * {@inheritDoc}
  2562.      */
  2563.     public function isSingleValuedAssociation($fieldName)
  2564.     {
  2565.         return isset($this->associationMappings[$fieldName])
  2566.             && ($this->associationMappings[$fieldName]['type'] & self::TO_ONE);
  2567.     }
  2568.     /**
  2569.      * {@inheritDoc}
  2570.      */
  2571.     public function isCollectionValuedAssociation($fieldName)
  2572.     {
  2573.         return isset($this->associationMappings[$fieldName])
  2574.             && ! ($this->associationMappings[$fieldName]['type'] & self::TO_ONE);
  2575.     }
  2576.     /**
  2577.      * Is this an association that only has a single join column?
  2578.      *
  2579.      * @param string $fieldName
  2580.      *
  2581.      * @return bool
  2582.      */
  2583.     public function isAssociationWithSingleJoinColumn($fieldName)
  2584.     {
  2585.         return isset($this->associationMappings[$fieldName])
  2586.             && isset($this->associationMappings[$fieldName]['joinColumns'][0])
  2587.             && ! isset($this->associationMappings[$fieldName]['joinColumns'][1]);
  2588.     }
  2589.     /**
  2590.      * Returns the single association join column (if any).
  2591.      *
  2592.      * @param string $fieldName
  2593.      *
  2594.      * @return string
  2595.      *
  2596.      * @throws MappingException
  2597.      */
  2598.     public function getSingleAssociationJoinColumnName($fieldName)
  2599.     {
  2600.         if (! $this->isAssociationWithSingleJoinColumn($fieldName)) {
  2601.             throw MappingException::noSingleAssociationJoinColumnFound($this->name$fieldName);
  2602.         }
  2603.         return $this->associationMappings[$fieldName]['joinColumns'][0]['name'];
  2604.     }
  2605.     /**
  2606.      * Returns the single association referenced join column name (if any).
  2607.      *
  2608.      * @param string $fieldName
  2609.      *
  2610.      * @return string
  2611.      *
  2612.      * @throws MappingException
  2613.      */
  2614.     public function getSingleAssociationReferencedJoinColumnName($fieldName)
  2615.     {
  2616.         if (! $this->isAssociationWithSingleJoinColumn($fieldName)) {
  2617.             throw MappingException::noSingleAssociationJoinColumnFound($this->name$fieldName);
  2618.         }
  2619.         return $this->associationMappings[$fieldName]['joinColumns'][0]['referencedColumnName'];
  2620.     }
  2621.     /**
  2622.      * Used to retrieve a fieldname for either field or association from a given column.
  2623.      *
  2624.      * This method is used in foreign-key as primary-key contexts.
  2625.      *
  2626.      * @param string $columnName
  2627.      *
  2628.      * @return string
  2629.      *
  2630.      * @throws MappingException
  2631.      */
  2632.     public function getFieldForColumn($columnName)
  2633.     {
  2634.         if (isset($this->fieldNames[$columnName])) {
  2635.             return $this->fieldNames[$columnName];
  2636.         }
  2637.         foreach ($this->associationMappings as $assocName => $mapping) {
  2638.             if (
  2639.                 $this->isAssociationWithSingleJoinColumn($assocName) &&
  2640.                 $this->associationMappings[$assocName]['joinColumns'][0]['name'] === $columnName
  2641.             ) {
  2642.                 return $assocName;
  2643.             }
  2644.         }
  2645.         throw MappingException::noFieldNameFoundForColumn($this->name$columnName);
  2646.     }
  2647.     /**
  2648.      * Sets the ID generator used to generate IDs for instances of this class.
  2649.      *
  2650.      * @param AbstractIdGenerator $generator
  2651.      *
  2652.      * @return void
  2653.      */
  2654.     public function setIdGenerator($generator)
  2655.     {
  2656.         $this->idGenerator $generator;
  2657.     }
  2658.     /**
  2659.      * Sets definition.
  2660.      *
  2661.      * @param array $definition
  2662.      *
  2663.      * @return void
  2664.      */
  2665.     public function setCustomGeneratorDefinition(array $definition)
  2666.     {
  2667.         $this->customGeneratorDefinition $definition;
  2668.     }
  2669.     /**
  2670.      * Sets the definition of the sequence ID generator for this class.
  2671.      *
  2672.      * The definition must have the following structure:
  2673.      * <code>
  2674.      * array(
  2675.      *     'sequenceName'   => 'name',
  2676.      *     'allocationSize' => 20,
  2677.      *     'initialValue'   => 1
  2678.      *     'quoted'         => 1
  2679.      * )
  2680.      * </code>
  2681.      *
  2682.      * @param array $definition
  2683.      *
  2684.      * @return void
  2685.      *
  2686.      * @throws MappingException
  2687.      */
  2688.     public function setSequenceGeneratorDefinition(array $definition)
  2689.     {
  2690.         if (! isset($definition['sequenceName']) || trim($definition['sequenceName']) === '') {
  2691.             throw MappingException::missingSequenceName($this->name);
  2692.         }
  2693.         if ($definition['sequenceName'][0] === '`') {
  2694.             $definition['sequenceName'] = trim($definition['sequenceName'], '`');
  2695.             $definition['quoted']       = true;
  2696.         }
  2697.         if (! isset($definition['allocationSize']) || trim($definition['allocationSize']) === '') {
  2698.             $definition['allocationSize'] = '1';
  2699.         }
  2700.         if (! isset($definition['initialValue']) || trim($definition['initialValue']) === '') {
  2701.             $definition['initialValue'] = '1';
  2702.         }
  2703.         $this->sequenceGeneratorDefinition $definition;
  2704.     }
  2705.     /**
  2706.      * Sets the version field mapping used for versioning. Sets the default
  2707.      * value to use depending on the column type.
  2708.      *
  2709.      * @param array $mapping The version field mapping array.
  2710.      *
  2711.      * @return void
  2712.      *
  2713.      * @throws MappingException
  2714.      */
  2715.     public function setVersionMapping(array &$mapping)
  2716.     {
  2717.         $this->isVersioned  true;
  2718.         $this->versionField $mapping['fieldName'];
  2719.         if (! isset($mapping['default'])) {
  2720.             if (in_array($mapping['type'], ['integer''bigint''smallint'])) {
  2721.                 $mapping['default'] = 1;
  2722.             } elseif ($mapping['type'] === 'datetime') {
  2723.                 $mapping['default'] = 'CURRENT_TIMESTAMP';
  2724.             } else {
  2725.                 throw MappingException::unsupportedOptimisticLockingType($this->name$mapping['fieldName'], $mapping['type']);
  2726.             }
  2727.         }
  2728.     }
  2729.     /**
  2730.      * Sets whether this class is to be versioned for optimistic locking.
  2731.      *
  2732.      * @param bool $bool
  2733.      *
  2734.      * @return void
  2735.      */
  2736.     public function setVersioned($bool)
  2737.     {
  2738.         $this->isVersioned $bool;
  2739.     }
  2740.     /**
  2741.      * Sets the name of the field that is to be used for versioning if this class is
  2742.      * versioned for optimistic locking.
  2743.      *
  2744.      * @param string $versionField
  2745.      *
  2746.      * @return void
  2747.      */
  2748.     public function setVersionField($versionField)
  2749.     {
  2750.         $this->versionField $versionField;
  2751.     }
  2752.     /**
  2753.      * Marks this class as read only, no change tracking is applied to it.
  2754.      *
  2755.      * @return void
  2756.      */
  2757.     public function markReadOnly()
  2758.     {
  2759.         $this->isReadOnly true;
  2760.     }
  2761.     /**
  2762.      * {@inheritDoc}
  2763.      */
  2764.     public function getFieldNames()
  2765.     {
  2766.         return array_keys($this->fieldMappings);
  2767.     }
  2768.     /**
  2769.      * {@inheritDoc}
  2770.      */
  2771.     public function getAssociationNames()
  2772.     {
  2773.         return array_keys($this->associationMappings);
  2774.     }
  2775.     /**
  2776.      * {@inheritDoc}
  2777.      *
  2778.      * @throws InvalidArgumentException
  2779.      */
  2780.     public function getAssociationTargetClass($assocName)
  2781.     {
  2782.         if (! isset($this->associationMappings[$assocName])) {
  2783.             throw new InvalidArgumentException("Association name expected, '" $assocName "' is not an association.");
  2784.         }
  2785.         return $this->associationMappings[$assocName]['targetEntity'];
  2786.     }
  2787.     /**
  2788.      * {@inheritDoc}
  2789.      */
  2790.     public function getName()
  2791.     {
  2792.         return $this->name;
  2793.     }
  2794.     /**
  2795.      * Gets the (possibly quoted) identifier column names for safe use in an SQL statement.
  2796.      *
  2797.      * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy
  2798.      *
  2799.      * @param AbstractPlatform $platform
  2800.      *
  2801.      * @return array
  2802.      */
  2803.     public function getQuotedIdentifierColumnNames($platform)
  2804.     {
  2805.         $quotedColumnNames = [];
  2806.         foreach ($this->identifier as $idProperty) {
  2807.             if (isset($this->fieldMappings[$idProperty])) {
  2808.                 $quotedColumnNames[] = isset($this->fieldMappings[$idProperty]['quoted'])
  2809.                     ? $platform->quoteIdentifier($this->fieldMappings[$idProperty]['columnName'])
  2810.                     : $this->fieldMappings[$idProperty]['columnName'];
  2811.                 continue;
  2812.             }
  2813.             // Association defined as Id field
  2814.             $joinColumns            $this->associationMappings[$idProperty]['joinColumns'];
  2815.             $assocQuotedColumnNames array_map(
  2816.                 static function ($joinColumn) use ($platform) {
  2817.                     return isset($joinColumn['quoted'])
  2818.                         ? $platform->quoteIdentifier($joinColumn['name'])
  2819.                         : $joinColumn['name'];
  2820.                 },
  2821.                 $joinColumns
  2822.             );
  2823.             $quotedColumnNames array_merge($quotedColumnNames$assocQuotedColumnNames);
  2824.         }
  2825.         return $quotedColumnNames;
  2826.     }
  2827.     /**
  2828.      * Gets the (possibly quoted) column name of a mapped field for safe use  in an SQL statement.
  2829.      *
  2830.      * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy
  2831.      *
  2832.      * @param string           $field
  2833.      * @param AbstractPlatform $platform
  2834.      *
  2835.      * @return string
  2836.      */
  2837.     public function getQuotedColumnName($field$platform)
  2838.     {
  2839.         return isset($this->fieldMappings[$field]['quoted'])
  2840.             ? $platform->quoteIdentifier($this->fieldMappings[$field]['columnName'])
  2841.             : $this->fieldMappings[$field]['columnName'];
  2842.     }
  2843.     /**
  2844.      * Gets the (possibly quoted) primary table name of this class for safe use in an SQL statement.
  2845.      *
  2846.      * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy
  2847.      *
  2848.      * @param AbstractPlatform $platform
  2849.      *
  2850.      * @return string
  2851.      */
  2852.     public function getQuotedTableName($platform)
  2853.     {
  2854.         return isset($this->table['quoted'])
  2855.             ? $platform->quoteIdentifier($this->table['name'])
  2856.             : $this->table['name'];
  2857.     }
  2858.     /**
  2859.      * Gets the (possibly quoted) name of the join table.
  2860.      *
  2861.      * @deprecated Deprecated since version 2.3 in favor of \Doctrine\ORM\Mapping\QuoteStrategy
  2862.      *
  2863.      * @param mixed[]          $assoc
  2864.      * @param AbstractPlatform $platform
  2865.      *
  2866.      * @return string
  2867.      */
  2868.     public function getQuotedJoinTableName(array $assoc$platform)
  2869.     {
  2870.         return isset($assoc['joinTable']['quoted'])
  2871.             ? $platform->quoteIdentifier($assoc['joinTable']['name'])
  2872.             : $assoc['joinTable']['name'];
  2873.     }
  2874.     /**
  2875.      * {@inheritDoc}
  2876.      */
  2877.     public function isAssociationInverseSide($fieldName)
  2878.     {
  2879.         return isset($this->associationMappings[$fieldName])
  2880.             && ! $this->associationMappings[$fieldName]['isOwningSide'];
  2881.     }
  2882.     /**
  2883.      * {@inheritDoc}
  2884.      */
  2885.     public function getAssociationMappedByTargetField($fieldName)
  2886.     {
  2887.         return $this->associationMappings[$fieldName]['mappedBy'];
  2888.     }
  2889.     /**
  2890.      * @param string $targetClass
  2891.      *
  2892.      * @return array
  2893.      */
  2894.     public function getAssociationsByTargetClass($targetClass)
  2895.     {
  2896.         $relations = [];
  2897.         foreach ($this->associationMappings as $mapping) {
  2898.             if ($mapping['targetEntity'] === $targetClass) {
  2899.                 $relations[$mapping['fieldName']] = $mapping;
  2900.             }
  2901.         }
  2902.         return $relations;
  2903.     }
  2904.     /**
  2905.      * @param  string|null $className
  2906.      *
  2907.      * @return string|null null if the input value is null
  2908.      *
  2909.      * @psalm-param ?class-string $className
  2910.      */
  2911.     public function fullyQualifiedClassName($className)
  2912.     {
  2913.         if (empty($className)) {
  2914.             return $className;
  2915.         }
  2916.         if ($className !== null && strpos($className'\\') === false && $this->namespace) {
  2917.             return $this->namespace '\\' $className;
  2918.         }
  2919.         return $className;
  2920.     }
  2921.     /**
  2922.      * @param string $name
  2923.      *
  2924.      * @return mixed
  2925.      */
  2926.     public function getMetadataValue($name)
  2927.     {
  2928.         if (isset($this->$name)) {
  2929.             return $this->$name;
  2930.         }
  2931.         return null;
  2932.     }
  2933.     /**
  2934.      * Map Embedded Class
  2935.      *
  2936.      * @param array $mapping
  2937.      *
  2938.      * @return void
  2939.      *
  2940.      * @throws MappingException
  2941.      */
  2942.     public function mapEmbedded(array $mapping)
  2943.     {
  2944.         $this->assertFieldNotMapped($mapping['fieldName']);
  2945.         $this->embeddedClasses[$mapping['fieldName']] = [
  2946.             'class' => $this->fullyQualifiedClassName($mapping['class']),
  2947.             'columnPrefix' => $mapping['columnPrefix'],
  2948.             'declaredField' => $mapping['declaredField'] ?? null,
  2949.             'originalField' => $mapping['originalField'] ?? null,
  2950.         ];
  2951.     }
  2952.     /**
  2953.      * Inline the embeddable class
  2954.      *
  2955.      * @param string $property
  2956.      */
  2957.     public function inlineEmbeddable($propertyClassMetadataInfo $embeddable)
  2958.     {
  2959.         foreach ($embeddable->fieldMappings as $fieldMapping) {
  2960.             $fieldMapping['originalClass'] = $fieldMapping['originalClass'] ?? $embeddable->name;
  2961.             $fieldMapping['declaredField'] = isset($fieldMapping['declaredField'])
  2962.                 ? $property '.' $fieldMapping['declaredField']
  2963.                 : $property;
  2964.             $fieldMapping['originalField'] = $fieldMapping['originalField'] ?? $fieldMapping['fieldName'];
  2965.             $fieldMapping['fieldName']     = $property '.' $fieldMapping['fieldName'];
  2966.             if (! empty($this->embeddedClasses[$property]['columnPrefix'])) {
  2967.                 $fieldMapping['columnName'] = $this->embeddedClasses[$property]['columnPrefix'] . $fieldMapping['columnName'];
  2968.             } elseif ($this->embeddedClasses[$property]['columnPrefix'] !== false) {
  2969.                 $fieldMapping['columnName'] = $this->namingStrategy
  2970.                     ->embeddedFieldToColumnName(
  2971.                         $property,
  2972.                         $fieldMapping['columnName'],
  2973.                         $this->reflClass->name,
  2974.                         $embeddable->reflClass->name
  2975.                     );
  2976.             }
  2977.             $this->mapField($fieldMapping);
  2978.         }
  2979.     }
  2980.     /**
  2981.      * @param string $fieldName
  2982.      *
  2983.      * @throws MappingException
  2984.      */
  2985.     private function assertFieldNotMapped($fieldName)
  2986.     {
  2987.         if (
  2988.             isset($this->fieldMappings[$fieldName]) ||
  2989.             isset($this->associationMappings[$fieldName]) ||
  2990.             isset($this->embeddedClasses[$fieldName])
  2991.         ) {
  2992.             throw MappingException::duplicateFieldMapping($this->name$fieldName);
  2993.         }
  2994.     }
  2995.     /**
  2996.      * Gets the sequence name based on class metadata.
  2997.      *
  2998.      * @return string
  2999.      *
  3000.      * @todo Sequence names should be computed in DBAL depending on the platform
  3001.      */
  3002.     public function getSequenceName(AbstractPlatform $platform)
  3003.     {
  3004.         $sequencePrefix $this->getSequencePrefix($platform);
  3005.         $columnName     $this->getSingleIdentifierColumnName();
  3006.         return $sequencePrefix '_' $columnName '_seq';
  3007.     }
  3008.     /**
  3009.      * Gets the sequence name prefix based on class metadata.
  3010.      *
  3011.      * @return string
  3012.      *
  3013.      * @todo Sequence names should be computed in DBAL depending on the platform
  3014.      */
  3015.     public function getSequencePrefix(AbstractPlatform $platform)
  3016.     {
  3017.         $tableName      $this->getTableName();
  3018.         $sequencePrefix $tableName;
  3019.         // Prepend the schema name to the table name if there is one
  3020.         if ($schemaName $this->getSchemaName()) {
  3021.             $sequencePrefix $schemaName '.' $tableName;
  3022.             if (! $platform->supportsSchemas() && $platform->canEmulateSchemas()) {
  3023.                 $sequencePrefix $schemaName '__' $tableName;
  3024.             }
  3025.         }
  3026.         return $sequencePrefix;
  3027.     }
  3028.     /**
  3029.      * @param array $mapping
  3030.      */
  3031.     private function assertMappingOrderBy(array $mapping)
  3032.     {
  3033.         if (isset($mapping['orderBy']) && ! is_array($mapping['orderBy'])) {
  3034.             throw new InvalidArgumentException("'orderBy' is expected to be an array, not " gettype($mapping['orderBy']));
  3035.         }
  3036.     }
  3037. }