vendor/doctrine/orm/src/Mapping/ClassMetadata.php line 900

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ORM\Mapping;
  4. use BackedEnum;
  5. use BadMethodCallException;
  6. use Doctrine\DBAL\Platforms\AbstractPlatform;
  7. use Doctrine\Instantiator\Instantiator;
  8. use Doctrine\Instantiator\InstantiatorInterface;
  9. use Doctrine\ORM\Cache\Exception\NonCacheableEntityAssociation;
  10. use Doctrine\ORM\EntityRepository;
  11. use Doctrine\ORM\Id\AbstractIdGenerator;
  12. use Doctrine\Persistence\Mapping\ClassMetadata as PersistenceClassMetadata;
  13. use Doctrine\Persistence\Mapping\ReflectionService;
  14. use InvalidArgumentException;
  15. use LogicException;
  16. use ReflectionClass;
  17. use ReflectionNamedType;
  18. use ReflectionProperty;
  19. use Stringable;
  20. use function array_diff;
  21. use function array_intersect;
  22. use function array_key_exists;
  23. use function array_keys;
  24. use function array_map;
  25. use function array_merge;
  26. use function array_pop;
  27. use function array_values;
  28. use function assert;
  29. use function class_exists;
  30. use function count;
  31. use function enum_exists;
  32. use function explode;
  33. use function in_array;
  34. use function interface_exists;
  35. use function is_string;
  36. use function is_subclass_of;
  37. use function ltrim;
  38. use function method_exists;
  39. use function spl_object_id;
  40. use function str_contains;
  41. use function str_replace;
  42. use function strtolower;
  43. use function trait_exists;
  44. use function trim;
  45. /**
  46.  * A <tt>ClassMetadata</tt> instance holds all the object-relational mapping metadata
  47.  * of an entity and its associations.
  48.  *
  49.  * Once populated, ClassMetadata instances are usually cached in a serialized form.
  50.  *
  51.  * <b>IMPORTANT NOTE:</b>
  52.  *
  53.  * The fields of this class are only public for 2 reasons:
  54.  * 1) To allow fast READ access.
  55.  * 2) To drastically reduce the size of a serialized instance (private/protected members
  56.  *    get the whole class name, namespace inclusive, prepended to every property in
  57.  *    the serialized representation).
  58.  *
  59.  * @psalm-type ConcreteAssociationMapping = OneToOneOwningSideMapping|OneToOneInverseSideMapping|ManyToOneAssociationMapping|OneToManyAssociationMapping|ManyToManyOwningSideMapping|ManyToManyInverseSideMapping
  60.  * @template-covariant T of object
  61.  * @template-implements PersistenceClassMetadata<T>
  62.  */
  63. class ClassMetadata implements PersistenceClassMetadataStringable
  64. {
  65.     /* The inheritance mapping types */
  66.     /**
  67.      * NONE means the class does not participate in an inheritance hierarchy
  68.      * and therefore does not need an inheritance mapping type.
  69.      */
  70.     public const INHERITANCE_TYPE_NONE 1;
  71.     /**
  72.      * JOINED means the class will be persisted according to the rules of
  73.      * <tt>Class Table Inheritance</tt>.
  74.      */
  75.     public const INHERITANCE_TYPE_JOINED 2;
  76.     /**
  77.      * SINGLE_TABLE means the class will be persisted according to the rules of
  78.      * <tt>Single Table Inheritance</tt>.
  79.      */
  80.     public const INHERITANCE_TYPE_SINGLE_TABLE 3;
  81.     /* The Id generator types. */
  82.     /**
  83.      * AUTO means the generator type will depend on what the used platform prefers.
  84.      * Offers full portability.
  85.      */
  86.     public const GENERATOR_TYPE_AUTO 1;
  87.     /**
  88.      * SEQUENCE means a separate sequence object will be used. Platforms that do
  89.      * not have native sequence support may emulate it. Full portability is currently
  90.      * not guaranteed.
  91.      */
  92.     public const GENERATOR_TYPE_SEQUENCE 2;
  93.     /**
  94.      * IDENTITY means an identity column is used for id generation. The database
  95.      * will fill in the id column on insertion. Platforms that do not support
  96.      * native identity columns may emulate them. Full portability is currently
  97.      * not guaranteed.
  98.      */
  99.     public const GENERATOR_TYPE_IDENTITY 4;
  100.     /**
  101.      * NONE means the class does not have a generated id. That means the class
  102.      * must have a natural, manually assigned id.
  103.      */
  104.     public const GENERATOR_TYPE_NONE 5;
  105.     /**
  106.      * CUSTOM means that customer will use own ID generator that supposedly work
  107.      */
  108.     public const GENERATOR_TYPE_CUSTOM 7;
  109.     /**
  110.      * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time
  111.      * by doing a property-by-property comparison with the original data. This will
  112.      * be done for all entities that are in MANAGED state at commit-time.
  113.      *
  114.      * This is the default change tracking policy.
  115.      */
  116.     public const CHANGETRACKING_DEFERRED_IMPLICIT 1;
  117.     /**
  118.      * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time
  119.      * by doing a property-by-property comparison with the original data. This will
  120.      * be done only for entities that were explicitly saved (through persist() or a cascade).
  121.      */
  122.     public const CHANGETRACKING_DEFERRED_EXPLICIT 2;
  123.     /**
  124.      * Specifies that an association is to be fetched when it is first accessed.
  125.      */
  126.     public const FETCH_LAZY 2;
  127.     /**
  128.      * Specifies that an association is to be fetched when the owner of the
  129.      * association is fetched.
  130.      */
  131.     public const FETCH_EAGER 3;
  132.     /**
  133.      * Specifies that an association is to be fetched lazy (on first access) and that
  134.      * commands such as Collection#count, Collection#slice are issued directly against
  135.      * the database if the collection is not yet initialized.
  136.      */
  137.     public const FETCH_EXTRA_LAZY 4;
  138.     /**
  139.      * Identifies a one-to-one association.
  140.      */
  141.     public const ONE_TO_ONE 1;
  142.     /**
  143.      * Identifies a many-to-one association.
  144.      */
  145.     public const MANY_TO_ONE 2;
  146.     /**
  147.      * Identifies a one-to-many association.
  148.      */
  149.     public const ONE_TO_MANY 4;
  150.     /**
  151.      * Identifies a many-to-many association.
  152.      */
  153.     public const MANY_TO_MANY 8;
  154.     /**
  155.      * Combined bitmask for to-one (single-valued) associations.
  156.      */
  157.     public const TO_ONE 3;
  158.     /**
  159.      * Combined bitmask for to-many (collection-valued) associations.
  160.      */
  161.     public const TO_MANY 12;
  162.     /**
  163.      * ReadOnly cache can do reads, inserts and deletes, cannot perform updates or employ any locks,
  164.      */
  165.     public const CACHE_USAGE_READ_ONLY 1;
  166.     /**
  167.      * Nonstrict Read Write Cache doesn’t employ any locks but can do inserts, update and deletes.
  168.      */
  169.     public const CACHE_USAGE_NONSTRICT_READ_WRITE 2;
  170.     /**
  171.      * Read Write Attempts to lock the entity before update/delete.
  172.      */
  173.     public const CACHE_USAGE_READ_WRITE 3;
  174.     /**
  175.      * The value of this column is never generated by the database.
  176.      */
  177.     public const GENERATED_NEVER 0;
  178.     /**
  179.      * The value of this column is generated by the database on INSERT, but not on UPDATE.
  180.      */
  181.     public const GENERATED_INSERT 1;
  182.     /**
  183.      * The value of this column is generated by the database on both INSERT and UDPATE statements.
  184.      */
  185.     public const GENERATED_ALWAYS 2;
  186.     /**
  187.      * READ-ONLY: The namespace the entity class is contained in.
  188.      *
  189.      * @todo Not really needed. Usage could be localized.
  190.      */
  191.     public string|null $namespace null;
  192.     /**
  193.      * READ-ONLY: The name of the entity class that is at the root of the mapped entity inheritance
  194.      * hierarchy. If the entity is not part of a mapped inheritance hierarchy this is the same
  195.      * as {@link $name}.
  196.      *
  197.      * @psalm-var class-string
  198.      */
  199.     public string $rootEntityName;
  200.     /**
  201.      * READ-ONLY: The definition of custom generator. Only used for CUSTOM
  202.      * generator type
  203.      *
  204.      * The definition has the following structure:
  205.      * <code>
  206.      * array(
  207.      *     'class' => 'ClassName',
  208.      * )
  209.      * </code>
  210.      *
  211.      * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
  212.      * @var array<string, string>|null
  213.      */
  214.     public array|null $customGeneratorDefinition null;
  215.     /**
  216.      * The name of the custom repository class used for the entity class.
  217.      * (Optional).
  218.      *
  219.      * @psalm-var ?class-string<EntityRepository>
  220.      */
  221.     public string|null $customRepositoryClassName null;
  222.     /**
  223.      * READ-ONLY: Whether this class describes the mapping of a mapped superclass.
  224.      */
  225.     public bool $isMappedSuperclass false;
  226.     /**
  227.      * READ-ONLY: Whether this class describes the mapping of an embeddable class.
  228.      */
  229.     public bool $isEmbeddedClass false;
  230.     /**
  231.      * READ-ONLY: The names of the parent <em>entity</em> classes (ancestors), starting with the
  232.      * nearest one and ending with the root entity class.
  233.      *
  234.      * @psalm-var list<class-string>
  235.      */
  236.     public array $parentClasses = [];
  237.     /**
  238.      * READ-ONLY: For classes in inheritance mapping hierarchies, this field contains the names of all
  239.      * <em>entity</em> subclasses of this class. These may also be abstract classes.
  240.      *
  241.      * This list is used, for example, to enumerate all necessary tables in JTI when querying for root
  242.      * or subclass entities, or to gather all fields comprised in an entity inheritance tree.
  243.      *
  244.      * For classes that do not use STI/JTI, this list is empty.
  245.      *
  246.      * Implementation note:
  247.      *
  248.      * In PHP, there is no general way to discover all subclasses of a given class at runtime. For that
  249.      * reason, the list of classes given in the discriminator map at the root entity is considered
  250.      * authoritative. The discriminator map must contain all <em>concrete</em> classes that can
  251.      * appear in the particular inheritance hierarchy tree. Since there can be no instances of abstract
  252.      * entity classes, users are not required to list such classes with a discriminator value.
  253.      *
  254.      * The possibly remaining "gaps" for abstract entity classes are filled after the class metadata for the
  255.      * root entity has been loaded.
  256.      *
  257.      * For subclasses of such root entities, the list can be reused/passed downwards, it only needs to
  258.      * be filtered accordingly (only keep remaining subclasses)
  259.      *
  260.      * @psalm-var list<class-string>
  261.      */
  262.     public array $subClasses = [];
  263.     /**
  264.      * READ-ONLY: The names of all embedded classes based on properties.
  265.      *
  266.      * @psalm-var array<string, EmbeddedClassMapping>
  267.      */
  268.     public array $embeddedClasses = [];
  269.     /**
  270.      * READ-ONLY: The field names of all fields that are part of the identifier/primary key
  271.      * of the mapped entity class.
  272.      *
  273.      * @psalm-var list<string>
  274.      */
  275.     public array $identifier = [];
  276.     /**
  277.      * READ-ONLY: The inheritance mapping type used by the class.
  278.      *
  279.      * @psalm-var self::INHERITANCE_TYPE_*
  280.      */
  281.     public int $inheritanceType self::INHERITANCE_TYPE_NONE;
  282.     /**
  283.      * READ-ONLY: The Id generator type used by the class.
  284.      *
  285.      * @psalm-var self::GENERATOR_TYPE_*
  286.      */
  287.     public int $generatorType self::GENERATOR_TYPE_NONE;
  288.     /**
  289.      * READ-ONLY: The field mappings of the class.
  290.      * Keys are field names and values are FieldMapping instances
  291.      *
  292.      * @var array<string, FieldMapping>
  293.      */
  294.     public array $fieldMappings = [];
  295.     /**
  296.      * READ-ONLY: An array of field names. Used to look up field names from column names.
  297.      * Keys are column names and values are field names.
  298.      *
  299.      * @psalm-var array<string, string>
  300.      */
  301.     public array $fieldNames = [];
  302.     /**
  303.      * READ-ONLY: A map of field names to column names. Keys are field names and values column names.
  304.      * Used to look up column names from field names.
  305.      * This is the reverse lookup map of $_fieldNames.
  306.      *
  307.      * @deprecated 3.0 Remove this.
  308.      *
  309.      * @var mixed[]
  310.      */
  311.     public array $columnNames = [];
  312.     /**
  313.      * READ-ONLY: The discriminator value of this class.
  314.      *
  315.      * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
  316.      * where a discriminator column is used.</b>
  317.      *
  318.      * @see discriminatorColumn
  319.      */
  320.     public mixed $discriminatorValue null;
  321.     /**
  322.      * READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
  323.      *
  324.      * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
  325.      * where a discriminator column is used.</b>
  326.      *
  327.      * @see discriminatorColumn
  328.      *
  329.      * @var array<int|string, string>
  330.      *
  331.      * @psalm-var array<int|string, class-string>
  332.      */
  333.     public array $discriminatorMap = [];
  334.     /**
  335.      * READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE
  336.      * inheritance mappings.
  337.      */
  338.     public DiscriminatorColumnMapping|null $discriminatorColumn null;
  339.     /**
  340.      * READ-ONLY: The primary table definition. The definition is an array with the
  341.      * following entries:
  342.      *
  343.      * name => <tableName>
  344.      * schema => <schemaName>
  345.      * indexes => array
  346.      * uniqueConstraints => array
  347.      *
  348.      * @var mixed[]
  349.      * @psalm-var array{
  350.      *               name: string,
  351.      *               schema?: string,
  352.      *               indexes?: array,
  353.      *               uniqueConstraints?: array,
  354.      *               options?: array<string, mixed>,
  355.      *               quoted?: bool
  356.      *           }
  357.      */
  358.     public array $table;
  359.     /**
  360.      * READ-ONLY: The registered lifecycle callbacks for entities of this class.
  361.      *
  362.      * @psalm-var array<string, list<string>>
  363.      */
  364.     public array $lifecycleCallbacks = [];
  365.     /**
  366.      * READ-ONLY: The registered entity listeners.
  367.      *
  368.      * @psalm-var array<string, list<array{class: class-string, method: string}>>
  369.      */
  370.     public array $entityListeners = [];
  371.     /**
  372.      * READ-ONLY: The association mappings of this class.
  373.      *
  374.      * A join table definition has the following structure:
  375.      * <pre>
  376.      * array(
  377.      *     'name' => <join table name>,
  378.      *      'joinColumns' => array(<join column mapping from join table to source table>),
  379.      *      'inverseJoinColumns' => array(<join column mapping from join table to target table>)
  380.      * )
  381.      * </pre>
  382.      *
  383.      * @psalm-var array<string, ConcreteAssociationMapping>
  384.      */
  385.     public array $associationMappings = [];
  386.     /**
  387.      * READ-ONLY: Flag indicating whether the identifier/primary key of the class is composite.
  388.      */
  389.     public bool $isIdentifierComposite false;
  390.     /**
  391.      * READ-ONLY: Flag indicating whether the identifier/primary key contains at least one foreign key association.
  392.      *
  393.      * This flag is necessary because some code blocks require special treatment of this cases.
  394.      */
  395.     public bool $containsForeignIdentifier false;
  396.     /**
  397.      * READ-ONLY: Flag indicating whether the identifier/primary key contains at least one ENUM type.
  398.      *
  399.      * This flag is necessary because some code blocks require special treatment of this cases.
  400.      */
  401.     public bool $containsEnumIdentifier false;
  402.     /**
  403.      * READ-ONLY: The ID generator used for generating IDs for this class.
  404.      *
  405.      * @todo Remove!
  406.      */
  407.     public AbstractIdGenerator $idGenerator;
  408.     /**
  409.      * READ-ONLY: The definition of the sequence generator of this class. Only used for the
  410.      * SEQUENCE generation strategy.
  411.      *
  412.      * The definition has the following structure:
  413.      * <code>
  414.      * array(
  415.      *     'sequenceName' => 'name',
  416.      *     'allocationSize' => '20',
  417.      *     'initialValue' => '1'
  418.      * )
  419.      * </code>
  420.      *
  421.      * @var array<string, mixed>|null
  422.      * @psalm-var array{sequenceName: string, allocationSize: string, initialValue: string, quoted?: mixed}|null
  423.      * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
  424.      */
  425.     public array|null $sequenceGeneratorDefinition null;
  426.     /**
  427.      * READ-ONLY: The policy used for change-tracking on entities of this class.
  428.      */
  429.     public int $changeTrackingPolicy self::CHANGETRACKING_DEFERRED_IMPLICIT;
  430.     /**
  431.      * READ-ONLY: A Flag indicating whether one or more columns of this class
  432.      * have to be reloaded after insert / update operations.
  433.      */
  434.     public bool $requiresFetchAfterChange false;
  435.     /**
  436.      * READ-ONLY: A flag for whether or not instances of this class are to be versioned
  437.      * with optimistic locking.
  438.      */
  439.     public bool $isVersioned false;
  440.     /**
  441.      * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any).
  442.      */
  443.     public string|null $versionField null;
  444.     /** @var mixed[]|null */
  445.     public array|null $cache null;
  446.     /**
  447.      * The ReflectionClass instance of the mapped class.
  448.      *
  449.      * @var ReflectionClass<T>|null
  450.      */
  451.     public ReflectionClass|null $reflClass null;
  452.     /**
  453.      * Is this entity marked as "read-only"?
  454.      *
  455.      * That means it is never considered for change-tracking in the UnitOfWork. It is a very helpful performance
  456.      * optimization for entities that are immutable, either in your domain or through the relation database
  457.      * (coming from a view, or a history table for example).
  458.      */
  459.     public bool $isReadOnly false;
  460.     /**
  461.      * NamingStrategy determining the default column and table names.
  462.      */
  463.     protected NamingStrategy $namingStrategy;
  464.     /**
  465.      * The ReflectionProperty instances of the mapped class.
  466.      *
  467.      * @var array<string, ReflectionProperty|null>
  468.      */
  469.     public array $reflFields = [];
  470.     private InstantiatorInterface|null $instantiator null;
  471.     private readonly TypedFieldMapper $typedFieldMapper;
  472.     /**
  473.      * Initializes a new ClassMetadata instance that will hold the object-relational mapping
  474.      * metadata of the class with the given name.
  475.      *
  476.      * @param string $name The name of the entity class the new instance is used for.
  477.      * @psalm-param class-string<T> $name
  478.      */
  479.     public function __construct(public string $nameNamingStrategy|null $namingStrategy nullTypedFieldMapper|null $typedFieldMapper null)
  480.     {
  481.         $this->rootEntityName   $name;
  482.         $this->namingStrategy   $namingStrategy ?? new DefaultNamingStrategy();
  483.         $this->instantiator     = new Instantiator();
  484.         $this->typedFieldMapper $typedFieldMapper ?? new DefaultTypedFieldMapper();
  485.     }
  486.     /**
  487.      * Gets the ReflectionProperties of the mapped class.
  488.      *
  489.      * @return ReflectionProperty[]|null[] An array of ReflectionProperty instances.
  490.      * @psalm-return array<ReflectionProperty|null>
  491.      */
  492.     public function getReflectionProperties(): array
  493.     {
  494.         return $this->reflFields;
  495.     }
  496.     /**
  497.      * Gets a ReflectionProperty for a specific field of the mapped class.
  498.      */
  499.     public function getReflectionProperty(string $name): ReflectionProperty|null
  500.     {
  501.         return $this->reflFields[$name];
  502.     }
  503.     /**
  504.      * Gets the ReflectionProperty for the single identifier field.
  505.      *
  506.      * @throws BadMethodCallException If the class has a composite identifier.
  507.      */
  508.     public function getSingleIdReflectionProperty(): ReflectionProperty|null
  509.     {
  510.         if ($this->isIdentifierComposite) {
  511.             throw new BadMethodCallException('Class ' $this->name ' has a composite identifier.');
  512.         }
  513.         return $this->reflFields[$this->identifier[0]];
  514.     }
  515.     /**
  516.      * Extracts the identifier values of an entity of this class.
  517.      *
  518.      * For composite identifiers, the identifier values are returned as an array
  519.      * with the same order as the field order in {@link identifier}.
  520.      *
  521.      * @return array<string, mixed>
  522.      */
  523.     public function getIdentifierValues(object $entity): array
  524.     {
  525.         if ($this->isIdentifierComposite) {
  526.             $id = [];
  527.             foreach ($this->identifier as $idField) {
  528.                 $value $this->reflFields[$idField]->getValue($entity);
  529.                 if ($value !== null) {
  530.                     $id[$idField] = $value;
  531.                 }
  532.             }
  533.             return $id;
  534.         }
  535.         $id    $this->identifier[0];
  536.         $value $this->reflFields[$id]->getValue($entity);
  537.         if ($value === null) {
  538.             return [];
  539.         }
  540.         return [$id => $value];
  541.     }
  542.     /**
  543.      * Populates the entity identifier of an entity.
  544.      *
  545.      * @psalm-param array<string, mixed> $id
  546.      *
  547.      * @todo Rename to assignIdentifier()
  548.      */
  549.     public function setIdentifierValues(object $entity, array $id): void
  550.     {
  551.         foreach ($id as $idField => $idValue) {
  552.             $this->reflFields[$idField]->setValue($entity$idValue);
  553.         }
  554.     }
  555.     /**
  556.      * Sets the specified field to the specified value on the given entity.
  557.      */
  558.     public function setFieldValue(object $entitystring $fieldmixed $value): void
  559.     {
  560.         $this->reflFields[$field]->setValue($entity$value);
  561.     }
  562.     /**
  563.      * Gets the specified field's value off the given entity.
  564.      */
  565.     public function getFieldValue(object $entitystring $field): mixed
  566.     {
  567.         return $this->reflFields[$field]->getValue($entity);
  568.     }
  569.     /**
  570.      * Creates a string representation of this instance.
  571.      *
  572.      * @return string The string representation of this instance.
  573.      *
  574.      * @todo Construct meaningful string representation.
  575.      */
  576.     public function __toString(): string
  577.     {
  578.         return self::class . '@' spl_object_id($this);
  579.     }
  580.     /**
  581.      * Determines which fields get serialized.
  582.      *
  583.      * It is only serialized what is necessary for best unserialization performance.
  584.      * That means any metadata properties that are not set or empty or simply have
  585.      * their default value are NOT serialized.
  586.      *
  587.      * Parts that are also NOT serialized because they can not be properly unserialized:
  588.      *      - reflClass (ReflectionClass)
  589.      *      - reflFields (ReflectionProperty array)
  590.      *
  591.      * @return string[] The names of all the fields that should be serialized.
  592.      */
  593.     public function __sleep(): array
  594.     {
  595.         // This metadata is always serialized/cached.
  596.         $serialized = [
  597.             'associationMappings',
  598.             'columnNames'//TODO: 3.0 Remove this. Can use fieldMappings[$fieldName]['columnName']
  599.             'fieldMappings',
  600.             'fieldNames',
  601.             'embeddedClasses',
  602.             'identifier',
  603.             'isIdentifierComposite'// TODO: REMOVE
  604.             'name',
  605.             'namespace'// TODO: REMOVE
  606.             'table',
  607.             'rootEntityName',
  608.             'idGenerator'//TODO: Does not really need to be serialized. Could be moved to runtime.
  609.         ];
  610.         // The rest of the metadata is only serialized if necessary.
  611.         if ($this->changeTrackingPolicy !== self::CHANGETRACKING_DEFERRED_IMPLICIT) {
  612.             $serialized[] = 'changeTrackingPolicy';
  613.         }
  614.         if ($this->customRepositoryClassName) {
  615.             $serialized[] = 'customRepositoryClassName';
  616.         }
  617.         if ($this->inheritanceType !== self::INHERITANCE_TYPE_NONE) {
  618.             $serialized[] = 'inheritanceType';
  619.             $serialized[] = 'discriminatorColumn';
  620.             $serialized[] = 'discriminatorValue';
  621.             $serialized[] = 'discriminatorMap';
  622.             $serialized[] = 'parentClasses';
  623.             $serialized[] = 'subClasses';
  624.         }
  625.         if ($this->generatorType !== self::GENERATOR_TYPE_NONE) {
  626.             $serialized[] = 'generatorType';
  627.             if ($this->generatorType === self::GENERATOR_TYPE_SEQUENCE) {
  628.                 $serialized[] = 'sequenceGeneratorDefinition';
  629.             }
  630.         }
  631.         if ($this->isMappedSuperclass) {
  632.             $serialized[] = 'isMappedSuperclass';
  633.         }
  634.         if ($this->isEmbeddedClass) {
  635.             $serialized[] = 'isEmbeddedClass';
  636.         }
  637.         if ($this->containsForeignIdentifier) {
  638.             $serialized[] = 'containsForeignIdentifier';
  639.         }
  640.         if ($this->containsEnumIdentifier) {
  641.             $serialized[] = 'containsEnumIdentifier';
  642.         }
  643.         if ($this->isVersioned) {
  644.             $serialized[] = 'isVersioned';
  645.             $serialized[] = 'versionField';
  646.         }
  647.         if ($this->lifecycleCallbacks) {
  648.             $serialized[] = 'lifecycleCallbacks';
  649.         }
  650.         if ($this->entityListeners) {
  651.             $serialized[] = 'entityListeners';
  652.         }
  653.         if ($this->isReadOnly) {
  654.             $serialized[] = 'isReadOnly';
  655.         }
  656.         if ($this->customGeneratorDefinition) {
  657.             $serialized[] = 'customGeneratorDefinition';
  658.         }
  659.         if ($this->cache) {
  660.             $serialized[] = 'cache';
  661.         }
  662.         if ($this->requiresFetchAfterChange) {
  663.             $serialized[] = 'requiresFetchAfterChange';
  664.         }
  665.         return $serialized;
  666.     }
  667.     /**
  668.      * Creates a new instance of the mapped class, without invoking the constructor.
  669.      */
  670.     public function newInstance(): object
  671.     {
  672.         return $this->instantiator->instantiate($this->name);
  673.     }
  674.     /**
  675.      * Restores some state that can not be serialized/unserialized.
  676.      */
  677.     public function wakeupReflection(ReflectionService $reflService): void
  678.     {
  679.         // Restore ReflectionClass and properties
  680.         $this->reflClass    $reflService->getClass($this->name);
  681.         $this->instantiator $this->instantiator ?: new Instantiator();
  682.         $parentReflFields = [];
  683.         foreach ($this->embeddedClasses as $property => $embeddedClass) {
  684.             if (isset($embeddedClass->declaredField)) {
  685.                 assert($embeddedClass->originalField !== null);
  686.                 $childProperty $this->getAccessibleProperty(
  687.                     $reflService,
  688.                     $this->embeddedClasses[$embeddedClass->declaredField]->class,
  689.                     $embeddedClass->originalField,
  690.                 );
  691.                 assert($childProperty !== null);
  692.                 $parentReflFields[$property] = new ReflectionEmbeddedProperty(
  693.                     $parentReflFields[$embeddedClass->declaredField],
  694.                     $childProperty,
  695.                     $this->embeddedClasses[$embeddedClass->declaredField]->class,
  696.                 );
  697.                 continue;
  698.             }
  699.             $fieldRefl $this->getAccessibleProperty(
  700.                 $reflService,
  701.                 $embeddedClass->declared ?? $this->name,
  702.                 $property,
  703.             );
  704.             $parentReflFields[$property] = $fieldRefl;
  705.             $this->reflFields[$property] = $fieldRefl;
  706.         }
  707.         foreach ($this->fieldMappings as $field => $mapping) {
  708.             if (isset($mapping->declaredField) && isset($parentReflFields[$mapping->declaredField])) {
  709.                 assert($mapping->originalField !== null);
  710.                 assert($mapping->originalClass !== null);
  711.                 $childProperty $this->getAccessibleProperty($reflService$mapping->originalClass$mapping->originalField);
  712.                 assert($childProperty !== null);
  713.                 if (isset($mapping->enumType)) {
  714.                     $childProperty = new ReflectionEnumProperty(
  715.                         $childProperty,
  716.                         $mapping->enumType,
  717.                     );
  718.                 }
  719.                 $this->reflFields[$field] = new ReflectionEmbeddedProperty(
  720.                     $parentReflFields[$mapping->declaredField],
  721.                     $childProperty,
  722.                     $mapping->originalClass,
  723.                 );
  724.                 continue;
  725.             }
  726.             $this->reflFields[$field] = isset($mapping->declared)
  727.                 ? $this->getAccessibleProperty($reflService$mapping->declared$field)
  728.                 : $this->getAccessibleProperty($reflService$this->name$field);
  729.             if (isset($mapping->enumType) && $this->reflFields[$field] !== null) {
  730.                 $this->reflFields[$field] = new ReflectionEnumProperty(
  731.                     $this->reflFields[$field],
  732.                     $mapping->enumType,
  733.                 );
  734.             }
  735.         }
  736.         foreach ($this->associationMappings as $field => $mapping) {
  737.             $this->reflFields[$field] = isset($mapping->declared)
  738.                 ? $this->getAccessibleProperty($reflService$mapping->declared$field)
  739.                 : $this->getAccessibleProperty($reflService$this->name$field);
  740.         }
  741.     }
  742.     /**
  743.      * Initializes a new ClassMetadata instance that will hold the object-relational mapping
  744.      * metadata of the class with the given name.
  745.      *
  746.      * @param ReflectionService $reflService The reflection service.
  747.      */
  748.     public function initializeReflection(ReflectionService $reflService): void
  749.     {
  750.         $this->reflClass $reflService->getClass($this->name);
  751.         $this->namespace $reflService->getClassNamespace($this->name);
  752.         if ($this->reflClass) {
  753.             $this->name $this->rootEntityName $this->reflClass->name;
  754.         }
  755.         $this->table['name'] = $this->namingStrategy->classToTableName($this->name);
  756.     }
  757.     /**
  758.      * Validates Identifier.
  759.      *
  760.      * @throws MappingException
  761.      */
  762.     public function validateIdentifier(): void
  763.     {
  764.         if ($this->isMappedSuperclass || $this->isEmbeddedClass) {
  765.             return;
  766.         }
  767.         // Verify & complete identifier mapping
  768.         if (! $this->identifier) {
  769.             throw MappingException::identifierRequired($this->name);
  770.         }
  771.         if ($this->usesIdGenerator() && $this->isIdentifierComposite) {
  772.             throw MappingException::compositeKeyAssignedIdGeneratorRequired($this->name);
  773.         }
  774.     }
  775.     /**
  776.      * Validates association targets actually exist.
  777.      *
  778.      * @throws MappingException
  779.      */
  780.     public function validateAssociations(): void
  781.     {
  782.         foreach ($this->associationMappings as $mapping) {
  783.             if (
  784.                 ! class_exists($mapping->targetEntity)
  785.                 && ! interface_exists($mapping->targetEntity)
  786.                 && ! trait_exists($mapping->targetEntity)
  787.             ) {
  788.                 throw MappingException::invalidTargetEntityClass($mapping->targetEntity$this->name$mapping->fieldName);
  789.             }
  790.         }
  791.     }
  792.     /**
  793.      * Validates lifecycle callbacks.
  794.      *
  795.      * @throws MappingException
  796.      */
  797.     public function validateLifecycleCallbacks(ReflectionService $reflService): void
  798.     {
  799.         foreach ($this->lifecycleCallbacks as $callbacks) {
  800.             foreach ($callbacks as $callbackFuncName) {
  801.                 if (! $reflService->hasPublicMethod($this->name$callbackFuncName)) {
  802.                     throw MappingException::lifecycleCallbackMethodNotFound($this->name$callbackFuncName);
  803.                 }
  804.             }
  805.         }
  806.     }
  807.     /**
  808.      * {@inheritDoc}
  809.      *
  810.      * Can return null when using static reflection, in violation of the LSP
  811.      */
  812.     public function getReflectionClass(): ReflectionClass|null
  813.     {
  814.         return $this->reflClass;
  815.     }
  816.     /** @psalm-param array{usage?: mixed, region?: mixed} $cache */
  817.     public function enableCache(array $cache): void
  818.     {
  819.         if (! isset($cache['usage'])) {
  820.             $cache['usage'] = self::CACHE_USAGE_READ_ONLY;
  821.         }
  822.         if (! isset($cache['region'])) {
  823.             $cache['region'] = strtolower(str_replace('\\''_'$this->rootEntityName));
  824.         }
  825.         $this->cache $cache;
  826.     }
  827.     /** @psalm-param array{usage?: int, region?: string} $cache */
  828.     public function enableAssociationCache(string $fieldName, array $cache): void
  829.     {
  830.         $this->associationMappings[$fieldName]->cache $this->getAssociationCacheDefaults($fieldName$cache);
  831.     }
  832.     /**
  833.      * @psalm-param array{usage?: int, region?: string|null} $cache
  834.      *
  835.      * @return int[]|string[]
  836.      * @psalm-return array{usage: int, region: string|null}
  837.      */
  838.     public function getAssociationCacheDefaults(string $fieldName, array $cache): array
  839.     {
  840.         if (! isset($cache['usage'])) {
  841.             $cache['usage'] = $this->cache['usage'] ?? self::CACHE_USAGE_READ_ONLY;
  842.         }
  843.         if (! isset($cache['region'])) {
  844.             $cache['region'] = strtolower(str_replace('\\''_'$this->rootEntityName)) . '__' $fieldName;
  845.         }
  846.         return $cache;
  847.     }
  848.     /**
  849.      * Sets the change tracking policy used by this class.
  850.      */
  851.     public function setChangeTrackingPolicy(int $policy): void
  852.     {
  853.         $this->changeTrackingPolicy $policy;
  854.     }
  855.     /**
  856.      * Whether the change tracking policy of this class is "deferred explicit".
  857.      */
  858.     public function isChangeTrackingDeferredExplicit(): bool
  859.     {
  860.         return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_EXPLICIT;
  861.     }
  862.     /**
  863.      * Whether the change tracking policy of this class is "deferred implicit".
  864.      */
  865.     public function isChangeTrackingDeferredImplicit(): bool
  866.     {
  867.         return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_IMPLICIT;
  868.     }
  869.     /**
  870.      * Checks whether a field is part of the identifier/primary key field(s).
  871.      */
  872.     public function isIdentifier(string $fieldName): bool
  873.     {
  874.         if (! $this->identifier) {
  875.             return false;
  876.         }
  877.         if (! $this->isIdentifierComposite) {
  878.             return $fieldName === $this->identifier[0];
  879.         }
  880.         return in_array($fieldName$this->identifiertrue);
  881.     }
  882.     public function isUniqueField(string $fieldName): bool
  883.     {
  884.         $mapping $this->getFieldMapping($fieldName);
  885.         return $mapping !== false && isset($mapping->unique) && $mapping->unique;
  886.     }
  887.     public function isNullable(string $fieldName): bool
  888.     {
  889.         $mapping $this->getFieldMapping($fieldName);
  890.         return $mapping !== false && isset($mapping->nullable) && $mapping->nullable;
  891.     }
  892.     /**
  893.      * Gets a column name for a field name.
  894.      * If the column name for the field cannot be found, the given field name
  895.      * is returned.
  896.      */
  897.     public function getColumnName(string $fieldName): string
  898.     {
  899.         return $this->columnNames[$fieldName] ?? $fieldName;
  900.     }
  901.     /**
  902.      * Gets the mapping of a (regular) field that holds some data but not a
  903.      * reference to another object.
  904.      *
  905.      * @throws MappingException
  906.      */
  907.     public function getFieldMapping(string $fieldName): FieldMapping
  908.     {
  909.         if (! isset($this->fieldMappings[$fieldName])) {
  910.             throw MappingException::mappingNotFound($this->name$fieldName);
  911.         }
  912.         return $this->fieldMappings[$fieldName];
  913.     }
  914.     /**
  915.      * Gets the mapping of an association.
  916.      *
  917.      * @see ClassMetadata::$associationMappings
  918.      *
  919.      * @param string $fieldName The field name that represents the association in
  920.      *                          the object model.
  921.      *
  922.      * @throws MappingException
  923.      */
  924.     public function getAssociationMapping(string $fieldName): AssociationMapping
  925.     {
  926.         if (! isset($this->associationMappings[$fieldName])) {
  927.             throw MappingException::mappingNotFound($this->name$fieldName);
  928.         }
  929.         return $this->associationMappings[$fieldName];
  930.     }
  931.     /**
  932.      * Gets all association mappings of the class.
  933.      *
  934.      * @psalm-return array<string, AssociationMapping>
  935.      */
  936.     public function getAssociationMappings(): array
  937.     {
  938.         return $this->associationMappings;
  939.     }
  940.     /**
  941.      * Gets the field name for a column name.
  942.      * If no field name can be found the column name is returned.
  943.      *
  944.      * @return string The column alias.
  945.      */
  946.     public function getFieldName(string $columnName): string
  947.     {
  948.         return $this->fieldNames[$columnName] ?? $columnName;
  949.     }
  950.     /**
  951.      * Checks whether given property has type
  952.      */
  953.     private function isTypedProperty(string $name): bool
  954.     {
  955.         return isset($this->reflClass)
  956.                && $this->reflClass->hasProperty($name)
  957.                && $this->reflClass->getProperty($name)->hasType();
  958.     }
  959.     /**
  960.      * Validates & completes the given field mapping based on typed property.
  961.      *
  962.      * @param  array{fieldName: string, type?: string} $mapping The field mapping to validate & complete.
  963.      *
  964.      * @return array{fieldName: string, enumType?: class-string<BackedEnum>, type?: string} The updated mapping.
  965.      */
  966.     private function validateAndCompleteTypedFieldMapping(array $mapping): array
  967.     {
  968.         $field $this->reflClass->getProperty($mapping['fieldName']);
  969.         $mapping $this->typedFieldMapper->validateAndComplete($mapping$field);
  970.         return $mapping;
  971.     }
  972.     /**
  973.      * Validates & completes the basic mapping information based on typed property.
  974.      *
  975.      * @param array{type: self::ONE_TO_ONE|self::MANY_TO_ONE|self::ONE_TO_MANY|self::MANY_TO_MANY, fieldName: string, targetEntity?: class-string} $mapping The mapping.
  976.      *
  977.      * @return mixed[] The updated mapping.
  978.      */
  979.     private function validateAndCompleteTypedAssociationMapping(array $mapping): array
  980.     {
  981.         $type $this->reflClass->getProperty($mapping['fieldName'])->getType();
  982.         if ($type === null || ($mapping['type'] & self::TO_ONE) === 0) {
  983.             return $mapping;
  984.         }
  985.         if (! isset($mapping['targetEntity']) && $type instanceof ReflectionNamedType) {
  986.             $mapping['targetEntity'] = $type->getName();
  987.         }
  988.         return $mapping;
  989.     }
  990.     /**
  991.      * Validates & completes the given field mapping.
  992.      *
  993.      * @psalm-param array{
  994.      *     fieldName?: string,
  995.      *     columnName?: string,
  996.      *     id?: bool,
  997.      *     generated?: int,
  998.      *     enumType?: class-string,
  999.      * } $mapping The field mapping to validate & complete.
  1000.      *
  1001.      * @return FieldMapping The updated mapping.
  1002.      *
  1003.      * @throws MappingException
  1004.      */
  1005.     protected function validateAndCompleteFieldMapping(array $mapping): FieldMapping
  1006.     {
  1007.         // Check mandatory fields
  1008.         if (! isset($mapping['fieldName']) || ! $mapping['fieldName']) {
  1009.             throw MappingException::missingFieldName($this->name);
  1010.         }
  1011.         if ($this->isTypedProperty($mapping['fieldName'])) {
  1012.             $mapping $this->validateAndCompleteTypedFieldMapping($mapping);
  1013.         }
  1014.         if (! isset($mapping['type'])) {
  1015.             // Default to string
  1016.             $mapping['type'] = 'string';
  1017.         }
  1018.         // Complete fieldName and columnName mapping
  1019.         if (! isset($mapping['columnName'])) {
  1020.             $mapping['columnName'] = $this->namingStrategy->propertyToColumnName($mapping['fieldName'], $this->name);
  1021.         }
  1022.         $mapping FieldMapping::fromMappingArray($mapping);
  1023.         if ($mapping->columnName[0] === '`') {
  1024.             $mapping->columnName trim($mapping->columnName'`');
  1025.             $mapping->quoted     true;
  1026.         }
  1027.         $this->columnNames[$mapping->fieldName] = $mapping->columnName;
  1028.         if (isset($this->fieldNames[$mapping->columnName]) || ($this->discriminatorColumn && $this->discriminatorColumn->name === $mapping->columnName)) {
  1029.             throw MappingException::duplicateColumnName($this->name$mapping->columnName);
  1030.         }
  1031.         $this->fieldNames[$mapping->columnName] = $mapping->fieldName;
  1032.         // Complete id mapping
  1033.         if (isset($mapping->id) && $mapping->id === true) {
  1034.             if ($this->versionField === $mapping->fieldName) {
  1035.                 throw MappingException::cannotVersionIdField($this->name$mapping->fieldName);
  1036.             }
  1037.             if (! in_array($mapping->fieldName$this->identifiertrue)) {
  1038.                 $this->identifier[] = $mapping->fieldName;
  1039.             }
  1040.             // Check for composite key
  1041.             if (! $this->isIdentifierComposite && count($this->identifier) > 1) {
  1042.                 $this->isIdentifierComposite true;
  1043.             }
  1044.         }
  1045.         if (isset($mapping->generated)) {
  1046.             if (! in_array($mapping->generated, [self::GENERATED_NEVERself::GENERATED_INSERTself::GENERATED_ALWAYS])) {
  1047.                 throw MappingException::invalidGeneratedMode($mapping->generated);
  1048.             }
  1049.             if ($mapping->generated === self::GENERATED_NEVER) {
  1050.                 unset($mapping->generated);
  1051.             }
  1052.         }
  1053.         if (isset($mapping->enumType)) {
  1054.             if (! enum_exists($mapping->enumType)) {
  1055.                 throw MappingException::nonEnumTypeMapped($this->name$mapping->fieldName$mapping->enumType);
  1056.             }
  1057.             if (! empty($mapping->id)) {
  1058.                 $this->containsEnumIdentifier true;
  1059.             }
  1060.         }
  1061.         return $mapping;
  1062.     }
  1063.     /**
  1064.      * Validates & completes the basic mapping information that is common to all
  1065.      * association mappings (one-to-one, many-ot-one, one-to-many, many-to-many).
  1066.      *
  1067.      * @psalm-param array<string, mixed> $mapping The mapping.
  1068.      *
  1069.      * @return ConcreteAssociationMapping
  1070.      *
  1071.      * @throws MappingException If something is wrong with the mapping.
  1072.      */
  1073.     protected function _validateAndCompleteAssociationMapping(array $mapping): AssociationMapping
  1074.     {
  1075.         if (array_key_exists('mappedBy'$mapping) && $mapping['mappedBy'] === null) {
  1076.             unset($mapping['mappedBy']);
  1077.         }
  1078.         if (array_key_exists('inversedBy'$mapping) && $mapping['inversedBy'] === null) {
  1079.             unset($mapping['inversedBy']);
  1080.         }
  1081.         if (array_key_exists('joinColumns'$mapping) && in_array($mapping['joinColumns'], [null, []], true)) {
  1082.             unset($mapping['joinColumns']);
  1083.         }
  1084.         $mapping['isOwningSide'] = true// assume owning side until we hit mappedBy
  1085.         if (empty($mapping['indexBy'])) {
  1086.             unset($mapping['indexBy']);
  1087.         }
  1088.         // If targetEntity is unqualified, assume it is in the same namespace as
  1089.         // the sourceEntity.
  1090.         $mapping['sourceEntity'] = $this->name;
  1091.         if ($this->isTypedProperty($mapping['fieldName'])) {
  1092.             $mapping $this->validateAndCompleteTypedAssociationMapping($mapping);
  1093.         }
  1094.         if (isset($mapping['targetEntity'])) {
  1095.             $mapping['targetEntity'] = $this->fullyQualifiedClassName($mapping['targetEntity']);
  1096.             $mapping['targetEntity'] = ltrim($mapping['targetEntity'], '\\');
  1097.         }
  1098.         if (($mapping['type'] & self::MANY_TO_ONE) > && isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) {
  1099.             throw MappingException::illegalOrphanRemoval($this->name$mapping['fieldName']);
  1100.         }
  1101.         // Complete id mapping
  1102.         if (isset($mapping['id']) && $mapping['id'] === true) {
  1103.             if (isset($mapping['orphanRemoval']) && $mapping['orphanRemoval']) {
  1104.                 throw MappingException::illegalOrphanRemovalOnIdentifierAssociation($this->name$mapping['fieldName']);
  1105.             }
  1106.             if (! in_array($mapping['fieldName'], $this->identifiertrue)) {
  1107.                 if (isset($mapping['joinColumns']) && count($mapping['joinColumns']) >= 2) {
  1108.                     throw MappingException::cannotMapCompositePrimaryKeyEntitiesAsForeignId(
  1109.                         $mapping['targetEntity'],
  1110.                         $this->name,
  1111.                         $mapping['fieldName'],
  1112.                     );
  1113.                 }
  1114.                 assert(is_string($mapping['fieldName']));
  1115.                 $this->identifier[]              = $mapping['fieldName'];
  1116.                 $this->containsForeignIdentifier true;
  1117.             }
  1118.             // Check for composite key
  1119.             if (! $this->isIdentifierComposite && count($this->identifier) > 1) {
  1120.                 $this->isIdentifierComposite true;
  1121.             }
  1122.             if ($this->cache && ! isset($mapping['cache'])) {
  1123.                 throw NonCacheableEntityAssociation::fromEntityAndField(
  1124.                     $this->name,
  1125.                     $mapping['fieldName'],
  1126.                 );
  1127.             }
  1128.         }
  1129.         // Mandatory attributes for both sides
  1130.         // Mandatory: fieldName, targetEntity
  1131.         if (! isset($mapping['fieldName']) || ! $mapping['fieldName']) {
  1132.             throw MappingException::missingFieldName($this->name);
  1133.         }
  1134.         if (! isset($mapping['targetEntity'])) {
  1135.             throw MappingException::missingTargetEntity($mapping['fieldName']);
  1136.         }
  1137.         // Mandatory and optional attributes for either side
  1138.         if (! isset($mapping['mappedBy'])) {
  1139.             if (isset($mapping['joinTable'])) {
  1140.                 if (isset($mapping['joinTable']['name']) && $mapping['joinTable']['name'][0] === '`') {
  1141.                     $mapping['joinTable']['name']   = trim($mapping['joinTable']['name'], '`');
  1142.                     $mapping['joinTable']['quoted'] = true;
  1143.                 }
  1144.             }
  1145.         } else {
  1146.             $mapping['isOwningSide'] = false;
  1147.         }
  1148.         if (isset($mapping['id']) && $mapping['id'] === true && $mapping['type'] & self::TO_MANY) {
  1149.             throw MappingException::illegalToManyIdentifierAssociation($this->name$mapping['fieldName']);
  1150.         }
  1151.         // Fetch mode. Default fetch mode to LAZY, if not set.
  1152.         if (! isset($mapping['fetch'])) {
  1153.             $mapping['fetch'] = self::FETCH_LAZY;
  1154.         }
  1155.         // Cascades
  1156.         $cascades = isset($mapping['cascade']) ? array_map('strtolower'$mapping['cascade']) : [];
  1157.         $allCascades = ['remove''persist''refresh''detach'];
  1158.         if (in_array('all'$cascadestrue)) {
  1159.             $cascades $allCascades;
  1160.         } elseif (count($cascades) !== count(array_intersect($cascades$allCascades))) {
  1161.             throw MappingException::invalidCascadeOption(
  1162.                 array_diff($cascades$allCascades),
  1163.                 $this->name,
  1164.                 $mapping['fieldName'],
  1165.             );
  1166.         }
  1167.         $mapping['cascade'] = $cascades;
  1168.         switch ($mapping['type']) {
  1169.             case self::ONE_TO_ONE:
  1170.                 if (isset($mapping['joinColumns']) && $mapping['joinColumns'] && ! $mapping['isOwningSide']) {
  1171.                     throw MappingException::joinColumnNotAllowedOnOneToOneInverseSide(
  1172.                         $this->name,
  1173.                         $mapping['fieldName'],
  1174.                     );
  1175.                 }
  1176.                 return $mapping['isOwningSide'] ?
  1177.                     OneToOneOwningSideMapping::fromMappingArrayAndName(
  1178.                         $mapping,
  1179.                         $this->namingStrategy,
  1180.                         $this->name,
  1181.                         $this->table ?? null,
  1182.                         $this->isInheritanceTypeSingleTable(),
  1183.                     ) :
  1184.                     OneToOneInverseSideMapping::fromMappingArrayAndName($mapping$this->name);
  1185.             case self::MANY_TO_ONE:
  1186.                 return ManyToOneAssociationMapping::fromMappingArrayAndName(
  1187.                     $mapping,
  1188.                     $this->namingStrategy,
  1189.                     $this->name,
  1190.                     $this->table ?? null,
  1191.                     $this->isInheritanceTypeSingleTable(),
  1192.                 );
  1193.             case self::ONE_TO_MANY:
  1194.                 return OneToManyAssociationMapping::fromMappingArrayAndName($mapping$this->name);
  1195.             case self::MANY_TO_MANY:
  1196.                 if (isset($mapping['joinColumns'])) {
  1197.                     unset($mapping['joinColumns']);
  1198.                 }
  1199.                 return $mapping['isOwningSide'] ?
  1200.                     ManyToManyOwningSideMapping::fromMappingArrayAndNamingStrategy($mapping$this->namingStrategy) :
  1201.                     ManyToManyInverseSideMapping::fromMappingArray($mapping);
  1202.             default:
  1203.                 throw MappingException::invalidAssociationType(
  1204.                     $this->name,
  1205.                     $mapping['fieldName'],
  1206.                     $mapping['type'],
  1207.                 );
  1208.         }
  1209.     }
  1210.     /**
  1211.      * {@inheritDoc}
  1212.      */
  1213.     public function getIdentifierFieldNames(): array
  1214.     {
  1215.         return $this->identifier;
  1216.     }
  1217.     /**
  1218.      * Gets the name of the single id field. Note that this only works on
  1219.      * entity classes that have a single-field pk.
  1220.      *
  1221.      * @throws MappingException If the class doesn't have an identifier or it has a composite primary key.
  1222.      */
  1223.     public function getSingleIdentifierFieldName(): string
  1224.     {
  1225.         if ($this->isIdentifierComposite) {
  1226.             throw MappingException::singleIdNotAllowedOnCompositePrimaryKey($this->name);
  1227.         }
  1228.         if (! isset($this->identifier[0])) {
  1229.             throw MappingException::noIdDefined($this->name);
  1230.         }
  1231.         return $this->identifier[0];
  1232.     }
  1233.     /**
  1234.      * Gets the column name of the single id column. Note that this only works on
  1235.      * entity classes that have a single-field pk.
  1236.      *
  1237.      * @throws MappingException If the class doesn't have an identifier or it has a composite primary key.
  1238.      */
  1239.     public function getSingleIdentifierColumnName(): string
  1240.     {
  1241.         return $this->getColumnName($this->getSingleIdentifierFieldName());
  1242.     }
  1243.     /**
  1244.      * INTERNAL:
  1245.      * Sets the mapped identifier/primary key fields of this class.
  1246.      * Mainly used by the ClassMetadataFactory to assign inherited identifiers.
  1247.      *
  1248.      * @psalm-param list<mixed> $identifier
  1249.      */
  1250.     public function setIdentifier(array $identifier): void
  1251.     {
  1252.         $this->identifier            $identifier;
  1253.         $this->isIdentifierComposite = (count($this->identifier) > 1);
  1254.     }
  1255.     /**
  1256.      * {@inheritDoc}
  1257.      */
  1258.     public function getIdentifier(): array
  1259.     {
  1260.         return $this->identifier;
  1261.     }
  1262.     public function hasField(string $fieldName): bool
  1263.     {
  1264.         return isset($this->fieldMappings[$fieldName]) || isset($this->embeddedClasses[$fieldName]);
  1265.     }
  1266.     /**
  1267.      * Gets an array containing all the column names.
  1268.      *
  1269.      * @psalm-param list<string>|null $fieldNames
  1270.      *
  1271.      * @return mixed[]
  1272.      * @psalm-return list<string>
  1273.      */
  1274.     public function getColumnNames(array|null $fieldNames null): array
  1275.     {
  1276.         if ($fieldNames === null) {
  1277.             return array_keys($this->fieldNames);
  1278.         }
  1279.         return array_values(array_map($this->getColumnName(...), $fieldNames));
  1280.     }
  1281.     /**
  1282.      * Returns an array with all the identifier column names.
  1283.      *
  1284.      * @psalm-return list<string>
  1285.      */
  1286.     public function getIdentifierColumnNames(): array
  1287.     {
  1288.         $columnNames = [];
  1289.         foreach ($this->identifier as $idProperty) {
  1290.             if (isset($this->fieldMappings[$idProperty])) {
  1291.                 $columnNames[] = $this->fieldMappings[$idProperty]->columnName;
  1292.                 continue;
  1293.             }
  1294.             // Association defined as Id field
  1295.             assert($this->associationMappings[$idProperty]->isToOneOwningSide());
  1296.             $joinColumns      $this->associationMappings[$idProperty]->joinColumns;
  1297.             $assocColumnNames array_map(static fn (JoinColumnMapping $joinColumn): string => $joinColumn->name$joinColumns);
  1298.             $columnNames array_merge($columnNames$assocColumnNames);
  1299.         }
  1300.         return $columnNames;
  1301.     }
  1302.     /**
  1303.      * Sets the type of Id generator to use for the mapped class.
  1304.      *
  1305.      * @psalm-param self::GENERATOR_TYPE_* $generatorType
  1306.      */
  1307.     public function setIdGeneratorType(int $generatorType): void
  1308.     {
  1309.         $this->generatorType $generatorType;
  1310.     }
  1311.     /**
  1312.      * Checks whether the mapped class uses an Id generator.
  1313.      */
  1314.     public function usesIdGenerator(): bool
  1315.     {
  1316.         return $this->generatorType !== self::GENERATOR_TYPE_NONE;
  1317.     }
  1318.     public function isInheritanceTypeNone(): bool
  1319.     {
  1320.         return $this->inheritanceType === self::INHERITANCE_TYPE_NONE;
  1321.     }
  1322.     /**
  1323.      * Checks whether the mapped class uses the JOINED inheritance mapping strategy.
  1324.      *
  1325.      * @return bool TRUE if the class participates in a JOINED inheritance mapping,
  1326.      * FALSE otherwise.
  1327.      */
  1328.     public function isInheritanceTypeJoined(): bool
  1329.     {
  1330.         return $this->inheritanceType === self::INHERITANCE_TYPE_JOINED;
  1331.     }
  1332.     /**
  1333.      * Checks whether the mapped class uses the SINGLE_TABLE inheritance mapping strategy.
  1334.      *
  1335.      * @return bool TRUE if the class participates in a SINGLE_TABLE inheritance mapping,
  1336.      * FALSE otherwise.
  1337.      */
  1338.     public function isInheritanceTypeSingleTable(): bool
  1339.     {
  1340.         return $this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_TABLE;
  1341.     }
  1342.     /**
  1343.      * Checks whether the class uses an identity column for the Id generation.
  1344.      */
  1345.     public function isIdGeneratorIdentity(): bool
  1346.     {
  1347.         return $this->generatorType === self::GENERATOR_TYPE_IDENTITY;
  1348.     }
  1349.     /**
  1350.      * Checks whether the class uses a sequence for id generation.
  1351.      *
  1352.      * @psalm-assert-if-true !null $this->sequenceGeneratorDefinition
  1353.      */
  1354.     public function isIdGeneratorSequence(): bool
  1355.     {
  1356.         return $this->generatorType === self::GENERATOR_TYPE_SEQUENCE;
  1357.     }
  1358.     /**
  1359.      * Checks whether the class has a natural identifier/pk (which means it does
  1360.      * not use any Id generator.
  1361.      */
  1362.     public function isIdentifierNatural(): bool
  1363.     {
  1364.         return $this->generatorType === self::GENERATOR_TYPE_NONE;
  1365.     }
  1366.     /**
  1367.      * Gets the type of a field.
  1368.      *
  1369.      * @todo 3.0 Remove this. PersisterHelper should fix it somehow
  1370.      */
  1371.     public function getTypeOfField(string $fieldName): string|null
  1372.     {
  1373.         return isset($this->fieldMappings[$fieldName])
  1374.             ? $this->fieldMappings[$fieldName]->type
  1375.             null;
  1376.     }
  1377.     /**
  1378.      * Gets the name of the primary table.
  1379.      */
  1380.     public function getTableName(): string
  1381.     {
  1382.         return $this->table['name'];
  1383.     }
  1384.     /**
  1385.      * Gets primary table's schema name.
  1386.      */
  1387.     public function getSchemaName(): string|null
  1388.     {
  1389.         return $this->table['schema'] ?? null;
  1390.     }
  1391.     /**
  1392.      * Gets the table name to use for temporary identifier tables of this class.
  1393.      */
  1394.     public function getTemporaryIdTableName(): string
  1395.     {
  1396.         // replace dots with underscores because PostgreSQL creates temporary tables in a special schema
  1397.         return str_replace('.''_'$this->getTableName() . '_id_tmp');
  1398.     }
  1399.     /**
  1400.      * Sets the mapped subclasses of this class.
  1401.      *
  1402.      * @psalm-param list<string> $subclasses The names of all mapped subclasses.
  1403.      */
  1404.     public function setSubclasses(array $subclasses): void
  1405.     {
  1406.         foreach ($subclasses as $subclass) {
  1407.             $this->subClasses[] = $this->fullyQualifiedClassName($subclass);
  1408.         }
  1409.     }
  1410.     /**
  1411.      * Sets the parent class names. Only <em>entity</em> classes may be given.
  1412.      *
  1413.      * Assumes that the class names in the passed array are in the order:
  1414.      * directParent -> directParentParent -> directParentParentParent ... -> root.
  1415.      *
  1416.      * @psalm-param list<class-string> $classNames
  1417.      */
  1418.     public function setParentClasses(array $classNames): void
  1419.     {
  1420.         $this->parentClasses $classNames;
  1421.         if (count($classNames) > 0) {
  1422.             $this->rootEntityName array_pop($classNames);
  1423.         }
  1424.     }
  1425.     /**
  1426.      * Sets the inheritance type used by the class and its subclasses.
  1427.      *
  1428.      * @psalm-param self::INHERITANCE_TYPE_* $type
  1429.      *
  1430.      * @throws MappingException
  1431.      */
  1432.     public function setInheritanceType(int $type): void
  1433.     {
  1434.         if (! $this->isInheritanceType($type)) {
  1435.             throw MappingException::invalidInheritanceType($this->name$type);
  1436.         }
  1437.         $this->inheritanceType $type;
  1438.     }
  1439.     /**
  1440.      * Sets the association to override association mapping of property for an entity relationship.
  1441.      *
  1442.      * @psalm-param array<string, mixed> $overrideMapping
  1443.      *
  1444.      * @throws MappingException
  1445.      */
  1446.     public function setAssociationOverride(string $fieldName, array $overrideMapping): void
  1447.     {
  1448.         if (! isset($this->associationMappings[$fieldName])) {
  1449.             throw MappingException::invalidOverrideFieldName($this->name$fieldName);
  1450.         }
  1451.         $mapping $this->associationMappings[$fieldName]->toArray();
  1452.         if (isset($mapping['inherited'])) {
  1453.             throw MappingException::illegalOverrideOfInheritedProperty(
  1454.                 $this->name,
  1455.                 $fieldName,
  1456.                 $mapping['inherited'],
  1457.             );
  1458.         }
  1459.         if (isset($overrideMapping['joinColumns'])) {
  1460.             $mapping['joinColumns'] = $overrideMapping['joinColumns'];
  1461.         }
  1462.         if (isset($overrideMapping['inversedBy'])) {
  1463.             $mapping['inversedBy'] = $overrideMapping['inversedBy'];
  1464.         }
  1465.         if (isset($overrideMapping['joinTable'])) {
  1466.             $mapping['joinTable'] = $overrideMapping['joinTable'];
  1467.         }
  1468.         if (isset($overrideMapping['fetch'])) {
  1469.             $mapping['fetch'] = $overrideMapping['fetch'];
  1470.         }
  1471.         switch ($mapping['type']) {
  1472.             case self::ONE_TO_ONE:
  1473.             case self::MANY_TO_ONE:
  1474.                 $mapping['joinColumnFieldNames']     = [];
  1475.                 $mapping['sourceToTargetKeyColumns'] = [];
  1476.                 break;
  1477.             case self::MANY_TO_MANY:
  1478.                 $mapping['relationToSourceKeyColumns'] = [];
  1479.                 $mapping['relationToTargetKeyColumns'] = [];
  1480.                 break;
  1481.         }
  1482.         $this->associationMappings[$fieldName] = $this->_validateAndCompleteAssociationMapping($mapping);
  1483.     }
  1484.     /**
  1485.      * Sets the override for a mapped field.
  1486.      *
  1487.      * @psalm-param array<string, mixed> $overrideMapping
  1488.      *
  1489.      * @throws MappingException
  1490.      */
  1491.     public function setAttributeOverride(string $fieldName, array $overrideMapping): void
  1492.     {
  1493.         if (! isset($this->fieldMappings[$fieldName])) {
  1494.             throw MappingException::invalidOverrideFieldName($this->name$fieldName);
  1495.         }
  1496.         $mapping $this->fieldMappings[$fieldName];
  1497.         if (isset($mapping->inherited)) {
  1498.             throw MappingException::illegalOverrideOfInheritedProperty($this->name$fieldName$mapping->inherited);
  1499.         }
  1500.         if (isset($mapping->id)) {
  1501.             $overrideMapping['id'] = $mapping->id;
  1502.         }
  1503.         if (isset($mapping->declared)) {
  1504.             $overrideMapping['declared'] = $mapping->declared;
  1505.         }
  1506.         if (! isset($overrideMapping['type'])) {
  1507.             $overrideMapping['type'] = $mapping->type;
  1508.         }
  1509.         if (! isset($overrideMapping['fieldName'])) {
  1510.             $overrideMapping['fieldName'] = $mapping->fieldName;
  1511.         }
  1512.         if ($overrideMapping['type'] !== $mapping->type) {
  1513.             throw MappingException::invalidOverrideFieldType($this->name$fieldName);
  1514.         }
  1515.         unset($this->fieldMappings[$fieldName]);
  1516.         unset($this->fieldNames[$mapping->columnName]);
  1517.         unset($this->columnNames[$mapping->fieldName]);
  1518.         $overrideMapping $this->validateAndCompleteFieldMapping($overrideMapping);
  1519.         $this->fieldMappings[$fieldName] = $overrideMapping;
  1520.     }
  1521.     /**
  1522.      * Checks whether a mapped field is inherited from an entity superclass.
  1523.      */
  1524.     public function isInheritedField(string $fieldName): bool
  1525.     {
  1526.         return isset($this->fieldMappings[$fieldName]->inherited);
  1527.     }
  1528.     /**
  1529.      * Checks if this entity is the root in any entity-inheritance-hierarchy.
  1530.      */
  1531.     public function isRootEntity(): bool
  1532.     {
  1533.         return $this->name === $this->rootEntityName;
  1534.     }
  1535.     /**
  1536.      * Checks whether a mapped association field is inherited from a superclass.
  1537.      */
  1538.     public function isInheritedAssociation(string $fieldName): bool
  1539.     {
  1540.         return isset($this->associationMappings[$fieldName]->inherited);
  1541.     }
  1542.     public function isInheritedEmbeddedClass(string $fieldName): bool
  1543.     {
  1544.         return isset($this->embeddedClasses[$fieldName]->inherited);
  1545.     }
  1546.     /**
  1547.      * Sets the name of the primary table the class is mapped to.
  1548.      *
  1549.      * @deprecated Use {@link setPrimaryTable}.
  1550.      */
  1551.     public function setTableName(string $tableName): void
  1552.     {
  1553.         $this->table['name'] = $tableName;
  1554.     }
  1555.     /**
  1556.      * Sets the primary table definition. The provided array supports the
  1557.      * following structure:
  1558.      *
  1559.      * name => <tableName> (optional, defaults to class name)
  1560.      * indexes => array of indexes (optional)
  1561.      * uniqueConstraints => array of constraints (optional)
  1562.      *
  1563.      * If a key is omitted, the current value is kept.
  1564.      *
  1565.      * @psalm-param array<string, mixed> $table The table description.
  1566.      */
  1567.     public function setPrimaryTable(array $table): void
  1568.     {
  1569.         if (isset($table['name'])) {
  1570.             // Split schema and table name from a table name like "myschema.mytable"
  1571.             if (str_contains($table['name'], '.')) {
  1572.                 [$this->table['schema'], $table['name']] = explode('.'$table['name'], 2);
  1573.             }
  1574.             if ($table['name'][0] === '`') {
  1575.                 $table['name']         = trim($table['name'], '`');
  1576.                 $this->table['quoted'] = true;
  1577.             }
  1578.             $this->table['name'] = $table['name'];
  1579.         }
  1580.         if (isset($table['quoted'])) {
  1581.             $this->table['quoted'] = $table['quoted'];
  1582.         }
  1583.         if (isset($table['schema'])) {
  1584.             $this->table['schema'] = $table['schema'];
  1585.         }
  1586.         if (isset($table['indexes'])) {
  1587.             $this->table['indexes'] = $table['indexes'];
  1588.         }
  1589.         if (isset($table['uniqueConstraints'])) {
  1590.             $this->table['uniqueConstraints'] = $table['uniqueConstraints'];
  1591.         }
  1592.         if (isset($table['options'])) {
  1593.             $this->table['options'] = $table['options'];
  1594.         }
  1595.     }
  1596.     /**
  1597.      * Checks whether the given type identifies an inheritance type.
  1598.      */
  1599.     private function isInheritanceType(int $type): bool
  1600.     {
  1601.         return $type === self::INHERITANCE_TYPE_NONE ||
  1602.                 $type === self::INHERITANCE_TYPE_SINGLE_TABLE ||
  1603.                 $type === self::INHERITANCE_TYPE_JOINED;
  1604.     }
  1605.     /**
  1606.      * Adds a mapped field to the class.
  1607.      *
  1608.      * @psalm-param array<string, mixed> $mapping The field mapping.
  1609.      *
  1610.      * @throws MappingException
  1611.      */
  1612.     public function mapField(array $mapping): void
  1613.     {
  1614.         $mapping $this->validateAndCompleteFieldMapping($mapping);
  1615.         $this->assertFieldNotMapped($mapping->fieldName);
  1616.         if (isset($mapping->generated)) {
  1617.             $this->requiresFetchAfterChange true;
  1618.         }
  1619.         $this->fieldMappings[$mapping->fieldName] = $mapping;
  1620.     }
  1621.     /**
  1622.      * INTERNAL:
  1623.      * Adds an association mapping without completing/validating it.
  1624.      * This is mainly used to add inherited association mappings to derived classes.
  1625.      *
  1626.      * @param ConcreteAssociationMapping $mapping
  1627.      *
  1628.      * @throws MappingException
  1629.      */
  1630.     public function addInheritedAssociationMapping(AssociationMapping $mapping/*, $owningClassName = null*/): void
  1631.     {
  1632.         if (isset($this->associationMappings[$mapping->fieldName])) {
  1633.             throw MappingException::duplicateAssociationMapping($this->name$mapping->fieldName);
  1634.         }
  1635.         $this->associationMappings[$mapping->fieldName] = $mapping;
  1636.     }
  1637.     /**
  1638.      * INTERNAL:
  1639.      * Adds a field mapping without completing/validating it.
  1640.      * This is mainly used to add inherited field mappings to derived classes.
  1641.      */
  1642.     public function addInheritedFieldMapping(FieldMapping $fieldMapping): void
  1643.     {
  1644.         $this->fieldMappings[$fieldMapping->fieldName] = $fieldMapping;
  1645.         $this->columnNames[$fieldMapping->fieldName]   = $fieldMapping->columnName;
  1646.         $this->fieldNames[$fieldMapping->columnName]   = $fieldMapping->fieldName;
  1647.         if (isset($fieldMapping->generated)) {
  1648.             $this->requiresFetchAfterChange true;
  1649.         }
  1650.     }
  1651.     /**
  1652.      * Adds a one-to-one mapping.
  1653.      *
  1654.      * @param array<string, mixed> $mapping The mapping.
  1655.      */
  1656.     public function mapOneToOne(array $mapping): void
  1657.     {
  1658.         $mapping['type'] = self::ONE_TO_ONE;
  1659.         $mapping $this->_validateAndCompleteAssociationMapping($mapping);
  1660.         $this->_storeAssociationMapping($mapping);
  1661.     }
  1662.     /**
  1663.      * Adds a one-to-many mapping.
  1664.      *
  1665.      * @psalm-param array<string, mixed> $mapping The mapping.
  1666.      */
  1667.     public function mapOneToMany(array $mapping): void
  1668.     {
  1669.         $mapping['type'] = self::ONE_TO_MANY;
  1670.         $mapping $this->_validateAndCompleteAssociationMapping($mapping);
  1671.         $this->_storeAssociationMapping($mapping);
  1672.     }
  1673.     /**
  1674.      * Adds a many-to-one mapping.
  1675.      *
  1676.      * @psalm-param array<string, mixed> $mapping The mapping.
  1677.      */
  1678.     public function mapManyToOne(array $mapping): void
  1679.     {
  1680.         $mapping['type'] = self::MANY_TO_ONE;
  1681.         $mapping $this->_validateAndCompleteAssociationMapping($mapping);
  1682.         $this->_storeAssociationMapping($mapping);
  1683.     }
  1684.     /**
  1685.      * Adds a many-to-many mapping.
  1686.      *
  1687.      * @psalm-param array<string, mixed> $mapping The mapping.
  1688.      */
  1689.     public function mapManyToMany(array $mapping): void
  1690.     {
  1691.         $mapping['type'] = self::MANY_TO_MANY;
  1692.         $mapping $this->_validateAndCompleteAssociationMapping($mapping);
  1693.         $this->_storeAssociationMapping($mapping);
  1694.     }
  1695.     /**
  1696.      * Stores the association mapping.
  1697.      *
  1698.      * @param ConcreteAssociationMapping $assocMapping
  1699.      *
  1700.      * @throws MappingException
  1701.      */
  1702.     protected function _storeAssociationMapping(AssociationMapping $assocMapping): void
  1703.     {
  1704.         $sourceFieldName $assocMapping->fieldName;
  1705.         $this->assertFieldNotMapped($sourceFieldName);
  1706.         $this->associationMappings[$sourceFieldName] = $assocMapping;
  1707.     }
  1708.     /**
  1709.      * Registers a custom repository class for the entity class.
  1710.      *
  1711.      * @param string|null $repositoryClassName The class name of the custom mapper.
  1712.      * @psalm-param class-string<EntityRepository>|null $repositoryClassName
  1713.      */
  1714.     public function setCustomRepositoryClass(string|null $repositoryClassName): void
  1715.     {
  1716.         $this->customRepositoryClassName $this->fullyQualifiedClassName($repositoryClassName);
  1717.     }
  1718.     /**
  1719.      * Dispatches the lifecycle event of the given entity to the registered
  1720.      * lifecycle callbacks and lifecycle listeners.
  1721.      *
  1722.      * @deprecated Deprecated since version 2.4 in favor of \Doctrine\ORM\Event\ListenersInvoker
  1723.      *
  1724.      * @param string $lifecycleEvent The lifecycle event.
  1725.      */
  1726.     public function invokeLifecycleCallbacks(string $lifecycleEventobject $entity): void
  1727.     {
  1728.         foreach ($this->lifecycleCallbacks[$lifecycleEvent] as $callback) {
  1729.             $entity->$callback();
  1730.         }
  1731.     }
  1732.     /**
  1733.      * Whether the class has any attached lifecycle listeners or callbacks for a lifecycle event.
  1734.      */
  1735.     public function hasLifecycleCallbacks(string $lifecycleEvent): bool
  1736.     {
  1737.         return isset($this->lifecycleCallbacks[$lifecycleEvent]);
  1738.     }
  1739.     /**
  1740.      * Gets the registered lifecycle callbacks for an event.
  1741.      *
  1742.      * @return string[]
  1743.      * @psalm-return list<string>
  1744.      */
  1745.     public function getLifecycleCallbacks(string $event): array
  1746.     {
  1747.         return $this->lifecycleCallbacks[$event] ?? [];
  1748.     }
  1749.     /**
  1750.      * Adds a lifecycle callback for entities of this class.
  1751.      */
  1752.     public function addLifecycleCallback(string $callbackstring $event): void
  1753.     {
  1754.         if ($this->isEmbeddedClass) {
  1755.             throw MappingException::illegalLifecycleCallbackOnEmbeddedClass($callback$this->name);
  1756.         }
  1757.         if (isset($this->lifecycleCallbacks[$event]) && in_array($callback$this->lifecycleCallbacks[$event], true)) {
  1758.             return;
  1759.         }
  1760.         $this->lifecycleCallbacks[$event][] = $callback;
  1761.     }
  1762.     /**
  1763.      * Sets the lifecycle callbacks for entities of this class.
  1764.      * Any previously registered callbacks are overwritten.
  1765.      *
  1766.      * @psalm-param array<string, list<string>> $callbacks
  1767.      */
  1768.     public function setLifecycleCallbacks(array $callbacks): void
  1769.     {
  1770.         $this->lifecycleCallbacks $callbacks;
  1771.     }
  1772.     /**
  1773.      * Adds a entity listener for entities of this class.
  1774.      *
  1775.      * @param string $eventName The entity lifecycle event.
  1776.      * @param string $class     The listener class.
  1777.      * @param string $method    The listener callback method.
  1778.      *
  1779.      * @throws MappingException
  1780.      */
  1781.     public function addEntityListener(string $eventNamestring $classstring $method): void
  1782.     {
  1783.         $class $this->fullyQualifiedClassName($class);
  1784.         $listener = [
  1785.             'class'  => $class,
  1786.             'method' => $method,
  1787.         ];
  1788.         if (! class_exists($class)) {
  1789.             throw MappingException::entityListenerClassNotFound($class$this->name);
  1790.         }
  1791.         if (! method_exists($class$method)) {
  1792.             throw MappingException::entityListenerMethodNotFound($class$method$this->name);
  1793.         }
  1794.         if (isset($this->entityListeners[$eventName]) && in_array($listener$this->entityListeners[$eventName], true)) {
  1795.             throw MappingException::duplicateEntityListener($class$method$this->name);
  1796.         }
  1797.         $this->entityListeners[$eventName][] = $listener;
  1798.     }
  1799.     /**
  1800.      * Sets the discriminator column definition.
  1801.      *
  1802.      * @see getDiscriminatorColumn()
  1803.      *
  1804.      * @param DiscriminatorColumnMapping|mixed[]|null $columnDef
  1805.      * @psalm-param DiscriminatorColumnMapping|array{
  1806.      *     name: string|null,
  1807.      *     fieldName?: string|null,
  1808.      *     type?: string|null,
  1809.      *     length?: int|null,
  1810.      *     columnDefinition?: string|null,
  1811.      *     enumType?: class-string<BackedEnum>|null,
  1812.      *     options?: array<string, mixed>|null
  1813.      * }|null $columnDef
  1814.      *
  1815.      * @throws MappingException
  1816.      */
  1817.     public function setDiscriminatorColumn(DiscriminatorColumnMapping|array|null $columnDef): void
  1818.     {
  1819.         if ($columnDef instanceof DiscriminatorColumnMapping) {
  1820.             $this->discriminatorColumn $columnDef;
  1821.             return;
  1822.         }
  1823.         if ($columnDef !== null) {
  1824.             if (! isset($columnDef['name'])) {
  1825.                 throw MappingException::nameIsMandatoryForDiscriminatorColumns($this->name);
  1826.             }
  1827.             if (isset($this->fieldNames[$columnDef['name']])) {
  1828.                 throw MappingException::duplicateColumnName($this->name$columnDef['name']);
  1829.             }
  1830.             $columnDef['fieldName'] ??= $columnDef['name'];
  1831.             $columnDef['type']      ??= 'string';
  1832.             $columnDef['options']   ??= [];
  1833.             if (in_array($columnDef['type'], ['boolean''array''object''datetime''time''date'], true)) {
  1834.                 throw MappingException::invalidDiscriminatorColumnType($this->name$columnDef['type']);
  1835.             }
  1836.             $this->discriminatorColumn DiscriminatorColumnMapping::fromMappingArray($columnDef);
  1837.         }
  1838.     }
  1839.     final public function getDiscriminatorColumn(): DiscriminatorColumnMapping
  1840.     {
  1841.         if ($this->discriminatorColumn === null) {
  1842.             throw new LogicException('The discriminator column was not set.');
  1843.         }
  1844.         return $this->discriminatorColumn;
  1845.     }
  1846.     /**
  1847.      * Sets the discriminator values used by this class.
  1848.      * Used for JOINED and SINGLE_TABLE inheritance mapping strategies.
  1849.      *
  1850.      * @param array<int|string, string> $map
  1851.      */
  1852.     public function setDiscriminatorMap(array $map): void
  1853.     {
  1854.         foreach ($map as $value => $className) {
  1855.             $this->addDiscriminatorMapClass($value$className);
  1856.         }
  1857.     }
  1858.     /**
  1859.      * Adds one entry of the discriminator map with a new class and corresponding name.
  1860.      *
  1861.      * @throws MappingException
  1862.      */
  1863.     public function addDiscriminatorMapClass(int|string $namestring $className): void
  1864.     {
  1865.         $className $this->fullyQualifiedClassName($className);
  1866.         $className ltrim($className'\\');
  1867.         $this->discriminatorMap[$name] = $className;
  1868.         if ($this->name === $className) {
  1869.             $this->discriminatorValue $name;
  1870.             return;
  1871.         }
  1872.         if (! (class_exists($className) || interface_exists($className))) {
  1873.             throw MappingException::invalidClassInDiscriminatorMap($className$this->name);
  1874.         }
  1875.         $this->addSubClass($className);
  1876.     }
  1877.     /** @param array<class-string> $classes */
  1878.     public function addSubClasses(array $classes): void
  1879.     {
  1880.         foreach ($classes as $className) {
  1881.             $this->addSubClass($className);
  1882.         }
  1883.     }
  1884.     public function addSubClass(string $className): void
  1885.     {
  1886.         // By ignoring classes that are not subclasses of the current class, we simplify inheriting
  1887.         // the subclass list from a parent class at the beginning of \Doctrine\ORM\Mapping\ClassMetadataFactory::doLoadMetadata.
  1888.         if (is_subclass_of($className$this->name) && ! in_array($className$this->subClassestrue)) {
  1889.             $this->subClasses[] = $className;
  1890.         }
  1891.     }
  1892.     public function hasAssociation(string $fieldName): bool
  1893.     {
  1894.         return isset($this->associationMappings[$fieldName]);
  1895.     }
  1896.     public function isSingleValuedAssociation(string $fieldName): bool
  1897.     {
  1898.         return isset($this->associationMappings[$fieldName])
  1899.             && ($this->associationMappings[$fieldName]->isToOne());
  1900.     }
  1901.     public function isCollectionValuedAssociation(string $fieldName): bool
  1902.     {
  1903.         return isset($this->associationMappings[$fieldName])
  1904.             && ! $this->associationMappings[$fieldName]->isToOne();
  1905.     }
  1906.     /**
  1907.      * Is this an association that only has a single join column?
  1908.      */
  1909.     public function isAssociationWithSingleJoinColumn(string $fieldName): bool
  1910.     {
  1911.         return isset($this->associationMappings[$fieldName])
  1912.             && isset($this->associationMappings[$fieldName]->joinColumns[0])
  1913.             && ! isset($this->associationMappings[$fieldName]->joinColumns[1]);
  1914.     }
  1915.     /**
  1916.      * Returns the single association join column (if any).
  1917.      *
  1918.      * @throws MappingException
  1919.      */
  1920.     public function getSingleAssociationJoinColumnName(string $fieldName): string
  1921.     {
  1922.         if (! $this->isAssociationWithSingleJoinColumn($fieldName)) {
  1923.             throw MappingException::noSingleAssociationJoinColumnFound($this->name$fieldName);
  1924.         }
  1925.         $assoc $this->associationMappings[$fieldName];
  1926.         assert($assoc->isToOneOwningSide());
  1927.         return $assoc->joinColumns[0]->name;
  1928.     }
  1929.     /**
  1930.      * Returns the single association referenced join column name (if any).
  1931.      *
  1932.      * @throws MappingException
  1933.      */
  1934.     public function getSingleAssociationReferencedJoinColumnName(string $fieldName): string
  1935.     {
  1936.         if (! $this->isAssociationWithSingleJoinColumn($fieldName)) {
  1937.             throw MappingException::noSingleAssociationJoinColumnFound($this->name$fieldName);
  1938.         }
  1939.         $assoc $this->associationMappings[$fieldName];
  1940.         assert($assoc->isToOneOwningSide());
  1941.         return $assoc->joinColumns[0]->referencedColumnName;
  1942.     }
  1943.     /**
  1944.      * Used to retrieve a fieldname for either field or association from a given column.
  1945.      *
  1946.      * This method is used in foreign-key as primary-key contexts.
  1947.      *
  1948.      * @throws MappingException
  1949.      */
  1950.     public function getFieldForColumn(string $columnName): string
  1951.     {
  1952.         if (isset($this->fieldNames[$columnName])) {
  1953.             return $this->fieldNames[$columnName];
  1954.         }
  1955.         foreach ($this->associationMappings as $assocName => $mapping) {
  1956.             if (
  1957.                 $this->isAssociationWithSingleJoinColumn($assocName) &&
  1958.                 assert($this->associationMappings[$assocName]->isToOneOwningSide()) &&
  1959.                 $this->associationMappings[$assocName]->joinColumns[0]->name === $columnName
  1960.             ) {
  1961.                 return $assocName;
  1962.             }
  1963.         }
  1964.         throw MappingException::noFieldNameFoundForColumn($this->name$columnName);
  1965.     }
  1966.     /**
  1967.      * Sets the ID generator used to generate IDs for instances of this class.
  1968.      */
  1969.     public function setIdGenerator(AbstractIdGenerator $generator): void
  1970.     {
  1971.         $this->idGenerator $generator;
  1972.     }
  1973.     /**
  1974.      * Sets definition.
  1975.      *
  1976.      * @psalm-param array<string, string|null> $definition
  1977.      */
  1978.     public function setCustomGeneratorDefinition(array $definition): void
  1979.     {
  1980.         $this->customGeneratorDefinition $definition;
  1981.     }
  1982.     /**
  1983.      * Sets the definition of the sequence ID generator for this class.
  1984.      *
  1985.      * The definition must have the following structure:
  1986.      * <code>
  1987.      * array(
  1988.      *     'sequenceName'   => 'name',
  1989.      *     'allocationSize' => 20,
  1990.      *     'initialValue'   => 1
  1991.      *     'quoted'         => 1
  1992.      * )
  1993.      * </code>
  1994.      *
  1995.      * @psalm-param array{sequenceName?: string, allocationSize?: int|string, initialValue?: int|string, quoted?: mixed} $definition
  1996.      *
  1997.      * @throws MappingException
  1998.      */
  1999.     public function setSequenceGeneratorDefinition(array $definition): void
  2000.     {
  2001.         if (! isset($definition['sequenceName']) || trim($definition['sequenceName']) === '') {
  2002.             throw MappingException::missingSequenceName($this->name);
  2003.         }
  2004.         if ($definition['sequenceName'][0] === '`') {
  2005.             $definition['sequenceName'] = trim($definition['sequenceName'], '`');
  2006.             $definition['quoted']       = true;
  2007.         }
  2008.         if (! isset($definition['allocationSize']) || trim((string) $definition['allocationSize']) === '') {
  2009.             $definition['allocationSize'] = '1';
  2010.         }
  2011.         if (! isset($definition['initialValue']) || trim((string) $definition['initialValue']) === '') {
  2012.             $definition['initialValue'] = '1';
  2013.         }
  2014.         $definition['allocationSize'] = (string) $definition['allocationSize'];
  2015.         $definition['initialValue']   = (string) $definition['initialValue'];
  2016.         $this->sequenceGeneratorDefinition $definition;
  2017.     }
  2018.     /**
  2019.      * Sets the version field mapping used for versioning. Sets the default
  2020.      * value to use depending on the column type.
  2021.      *
  2022.      * @psalm-param array<string, mixed> $mapping The version field mapping array.
  2023.      *
  2024.      * @throws MappingException
  2025.      */
  2026.     public function setVersionMapping(array &$mapping): void
  2027.     {
  2028.         $this->isVersioned              true;
  2029.         $this->versionField             $mapping['fieldName'];
  2030.         $this->requiresFetchAfterChange true;
  2031.         if (! isset($mapping['default'])) {
  2032.             if (in_array($mapping['type'], ['integer''bigint''smallint'], true)) {
  2033.                 $mapping['default'] = 1;
  2034.             } elseif ($mapping['type'] === 'datetime') {
  2035.                 $mapping['default'] = 'CURRENT_TIMESTAMP';
  2036.             } else {
  2037.                 throw MappingException::unsupportedOptimisticLockingType($this->name$mapping['fieldName'], $mapping['type']);
  2038.             }
  2039.         }
  2040.     }
  2041.     /**
  2042.      * Sets whether this class is to be versioned for optimistic locking.
  2043.      */
  2044.     public function setVersioned(bool $bool): void
  2045.     {
  2046.         $this->isVersioned $bool;
  2047.         if ($bool) {
  2048.             $this->requiresFetchAfterChange true;
  2049.         }
  2050.     }
  2051.     /**
  2052.      * Sets the name of the field that is to be used for versioning if this class is
  2053.      * versioned for optimistic locking.
  2054.      */
  2055.     public function setVersionField(string|null $versionField): void
  2056.     {
  2057.         $this->versionField $versionField;
  2058.     }
  2059.     /**
  2060.      * Marks this class as read only, no change tracking is applied to it.
  2061.      */
  2062.     public function markReadOnly(): void
  2063.     {
  2064.         $this->isReadOnly true;
  2065.     }
  2066.     /**
  2067.      * {@inheritDoc}
  2068.      */
  2069.     public function getFieldNames(): array
  2070.     {
  2071.         return array_keys($this->fieldMappings);
  2072.     }
  2073.     /**
  2074.      * {@inheritDoc}
  2075.      */
  2076.     public function getAssociationNames(): array
  2077.     {
  2078.         return array_keys($this->associationMappings);
  2079.     }
  2080.     /**
  2081.      * {@inheritDoc}
  2082.      *
  2083.      * @psalm-return class-string
  2084.      *
  2085.      * @throws InvalidArgumentException
  2086.      */
  2087.     public function getAssociationTargetClass(string $assocName): string
  2088.     {
  2089.         return $this->associationMappings[$assocName]->targetEntity
  2090.             ?? throw new InvalidArgumentException("Association name expected, '" $assocName "' is not an association.");
  2091.     }
  2092.     public function getName(): string
  2093.     {
  2094.         return $this->name;
  2095.     }
  2096.     public function isAssociationInverseSide(string $assocName): bool
  2097.     {
  2098.         return isset($this->associationMappings[$assocName])
  2099.             && ! $this->associationMappings[$assocName]->isOwningSide();
  2100.     }
  2101.     public function getAssociationMappedByTargetField(string $assocName): string
  2102.     {
  2103.         $assoc $this->associationMappings[$assocName];
  2104.         assert($assoc instanceof InverseSideMapping);
  2105.         return $assoc->mappedBy;
  2106.     }
  2107.     /**
  2108.      * @return string|null null if the input value is null
  2109.      * @psalm-return class-string|null
  2110.      */
  2111.     public function fullyQualifiedClassName(string|null $className): string|null
  2112.     {
  2113.         if (empty($className)) {
  2114.             return $className;
  2115.         }
  2116.         if (! str_contains($className'\\') && $this->namespace) {
  2117.             return $this->namespace '\\' $className;
  2118.         }
  2119.         return $className;
  2120.     }
  2121.     public function getMetadataValue(string $name): mixed
  2122.     {
  2123.         return $this->$name ?? null;
  2124.     }
  2125.     /**
  2126.      * Map Embedded Class
  2127.      *
  2128.      * @psalm-param array{
  2129.      *     fieldName: string,
  2130.      *     class?: class-string,
  2131.      *     declaredField?: string,
  2132.      *     columnPrefix?: string|false|null,
  2133.      *     originalField?: string
  2134.      * } $mapping
  2135.      *
  2136.      * @throws MappingException
  2137.      */
  2138.     public function mapEmbedded(array $mapping): void
  2139.     {
  2140.         $this->assertFieldNotMapped($mapping['fieldName']);
  2141.         if (! isset($mapping['class']) && $this->isTypedProperty($mapping['fieldName'])) {
  2142.             $type $this->reflClass->getProperty($mapping['fieldName'])->getType();
  2143.             if ($type instanceof ReflectionNamedType) {
  2144.                 $mapping['class'] = $type->getName();
  2145.             }
  2146.         }
  2147.         if (! (isset($mapping['class']) && $mapping['class'])) {
  2148.             throw MappingException::missingEmbeddedClass($mapping['fieldName']);
  2149.         }
  2150.         $fqcn $this->fullyQualifiedClassName($mapping['class']);
  2151.         assert($fqcn !== null);
  2152.         $this->embeddedClasses[$mapping['fieldName']] = EmbeddedClassMapping::fromMappingArray([
  2153.             'class' => $fqcn,
  2154.             'columnPrefix' => $mapping['columnPrefix'] ?? null,
  2155.             'declaredField' => $mapping['declaredField'] ?? null,
  2156.             'originalField' => $mapping['originalField'] ?? null,
  2157.         ]);
  2158.     }
  2159.     /**
  2160.      * Inline the embeddable class
  2161.      */
  2162.     public function inlineEmbeddable(string $propertyClassMetadata $embeddable): void
  2163.     {
  2164.         foreach ($embeddable->fieldMappings as $originalFieldMapping) {
  2165.             $fieldMapping                    = (array) $originalFieldMapping;
  2166.             $fieldMapping['originalClass'] ??= $embeddable->name;
  2167.             $fieldMapping['declaredField']   = isset($fieldMapping['declaredField'])
  2168.                 ? $property '.' $fieldMapping['declaredField']
  2169.                 : $property;
  2170.             $fieldMapping['originalField'] ??= $fieldMapping['fieldName'];
  2171.             $fieldMapping['fieldName']       = $property '.' $fieldMapping['fieldName'];
  2172.             if (! empty($this->embeddedClasses[$property]->columnPrefix)) {
  2173.                 $fieldMapping['columnName'] = $this->embeddedClasses[$property]->columnPrefix $fieldMapping['columnName'];
  2174.             } elseif ($this->embeddedClasses[$property]->columnPrefix !== false) {
  2175.                 assert($this->reflClass !== null);
  2176.                 assert($embeddable->reflClass !== null);
  2177.                 $fieldMapping['columnName'] = $this->namingStrategy
  2178.                     ->embeddedFieldToColumnName(
  2179.                         $property,
  2180.                         $fieldMapping['columnName'],
  2181.                         $this->reflClass->name,
  2182.                         $embeddable->reflClass->name,
  2183.                     );
  2184.             }
  2185.             $this->mapField($fieldMapping);
  2186.         }
  2187.     }
  2188.     /** @throws MappingException */
  2189.     private function assertFieldNotMapped(string $fieldName): void
  2190.     {
  2191.         if (
  2192.             isset($this->fieldMappings[$fieldName]) ||
  2193.             isset($this->associationMappings[$fieldName]) ||
  2194.             isset($this->embeddedClasses[$fieldName])
  2195.         ) {
  2196.             throw MappingException::duplicateFieldMapping($this->name$fieldName);
  2197.         }
  2198.     }
  2199.     /**
  2200.      * Gets the sequence name based on class metadata.
  2201.      *
  2202.      * @todo Sequence names should be computed in DBAL depending on the platform
  2203.      */
  2204.     public function getSequenceName(AbstractPlatform $platform): string
  2205.     {
  2206.         $sequencePrefix $this->getSequencePrefix($platform);
  2207.         $columnName     $this->getSingleIdentifierColumnName();
  2208.         return $sequencePrefix '_' $columnName '_seq';
  2209.     }
  2210.     /**
  2211.      * Gets the sequence name prefix based on class metadata.
  2212.      *
  2213.      * @todo Sequence names should be computed in DBAL depending on the platform
  2214.      */
  2215.     public function getSequencePrefix(AbstractPlatform $platform): string
  2216.     {
  2217.         $tableName      $this->getTableName();
  2218.         $sequencePrefix $tableName;
  2219.         // Prepend the schema name to the table name if there is one
  2220.         $schemaName $this->getSchemaName();
  2221.         if ($schemaName) {
  2222.             $sequencePrefix $schemaName '.' $tableName;
  2223.         }
  2224.         return $sequencePrefix;
  2225.     }
  2226.     /** @psalm-param class-string $class */
  2227.     private function getAccessibleProperty(ReflectionService $reflServicestring $classstring $field): ReflectionProperty|null
  2228.     {
  2229.         $reflectionProperty $reflService->getAccessibleProperty($class$field);
  2230.         if ($reflectionProperty?->isReadOnly()) {
  2231.             $declaringClass $reflectionProperty->class;
  2232.             if ($declaringClass !== $class) {
  2233.                 $reflectionProperty $reflService->getAccessibleProperty($declaringClass$field);
  2234.             }
  2235.             if ($reflectionProperty !== null) {
  2236.                 $reflectionProperty = new ReflectionReadonlyProperty($reflectionProperty);
  2237.             }
  2238.         }
  2239.         return $reflectionProperty;
  2240.     }
  2241. }