/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php
PHP | 3745 lines | 2131 code | 314 blank | 1300 comment | 137 complexity | f316fbe6d97995a1e1bf8318d79db696 MD5 | raw file
Possible License(s): Unlicense
Large files files are truncated, but you can click here to view the full file
- <?php
- declare(strict_types=1);
- namespace Doctrine\ORM\Mapping;
- use BadMethodCallException;
- use DateInterval;
- use DateTime;
- use DateTimeImmutable;
- use Doctrine\DBAL\Platforms\AbstractPlatform;
- use Doctrine\DBAL\Types\Type;
- use Doctrine\DBAL\Types\Types;
- use Doctrine\Deprecations\Deprecation;
- use Doctrine\Instantiator\Instantiator;
- use Doctrine\Instantiator\InstantiatorInterface;
- use Doctrine\ORM\Cache\Exception\CacheException;
- use Doctrine\ORM\Cache\Exception\NonCacheableEntityAssociation;
- use Doctrine\ORM\Id\AbstractIdGenerator;
- use Doctrine\Persistence\Mapping\ClassMetadata;
- use Doctrine\Persistence\Mapping\ReflectionService;
- use InvalidArgumentException;
- use ReflectionClass;
- use ReflectionNamedType;
- use ReflectionProperty;
- use RuntimeException;
- use function array_diff;
- use function array_flip;
- use function array_intersect;
- use function array_keys;
- use function array_map;
- use function array_merge;
- use function array_pop;
- use function array_values;
- use function assert;
- use function class_exists;
- use function count;
- use function explode;
- use function gettype;
- use function in_array;
- use function interface_exists;
- use function is_array;
- use function is_subclass_of;
- use function ltrim;
- use function method_exists;
- use function spl_object_id;
- use function str_replace;
- use function strpos;
- use function strtolower;
- use function trait_exists;
- use function trim;
- use const PHP_VERSION_ID;
- /**
- * A <tt>ClassMetadata</tt> instance holds all the object-relational mapping metadata
- * of an entity and its associations.
- *
- * Once populated, ClassMetadata instances are usually cached in a serialized form.
- *
- * <b>IMPORTANT NOTE:</b>
- *
- * The fields of this class are only public for 2 reasons:
- * 1) To allow fast READ access.
- * 2) To drastically reduce the size of a serialized instance (private/protected members
- * get the whole class name, namespace inclusive, prepended to every property in
- * the serialized representation).
- *
- * @template-covariant T of object
- * @template-implements ClassMetadata<T>
- */
- class ClassMetadataInfo implements ClassMetadata
- {
- /* The inheritance mapping types */
- /**
- * NONE means the class does not participate in an inheritance hierarchy
- * and therefore does not need an inheritance mapping type.
- */
- public const INHERITANCE_TYPE_NONE = 1;
- /**
- * JOINED means the class will be persisted according to the rules of
- * <tt>Class Table Inheritance</tt>.
- */
- public const INHERITANCE_TYPE_JOINED = 2;
- /**
- * SINGLE_TABLE means the class will be persisted according to the rules of
- * <tt>Single Table Inheritance</tt>.
- */
- public const INHERITANCE_TYPE_SINGLE_TABLE = 3;
- /**
- * TABLE_PER_CLASS means the class will be persisted according to the rules
- * of <tt>Concrete Table Inheritance</tt>.
- */
- public const INHERITANCE_TYPE_TABLE_PER_CLASS = 4;
- /* The Id generator types. */
- /**
- * AUTO means the generator type will depend on what the used platform prefers.
- * Offers full portability.
- */
- public const GENERATOR_TYPE_AUTO = 1;
- /**
- * SEQUENCE means a separate sequence object will be used. Platforms that do
- * not have native sequence support may emulate it. Full portability is currently
- * not guaranteed.
- */
- public const GENERATOR_TYPE_SEQUENCE = 2;
- /**
- * TABLE means a separate table is used for id generation.
- * Offers full portability (in that it results in an exception being thrown
- * no matter the platform).
- *
- * @deprecated no replacement planned
- */
- public const GENERATOR_TYPE_TABLE = 3;
- /**
- * IDENTITY means an identity column is used for id generation. The database
- * will fill in the id column on insertion. Platforms that do not support
- * native identity columns may emulate them. Full portability is currently
- * not guaranteed.
- */
- public const GENERATOR_TYPE_IDENTITY = 4;
- /**
- * NONE means the class does not have a generated id. That means the class
- * must have a natural, manually assigned id.
- */
- public const GENERATOR_TYPE_NONE = 5;
- /**
- * UUID means that a UUID/GUID expression is used for id generation. Full
- * portability is currently not guaranteed.
- *
- * @deprecated use an application-side generator instead
- */
- public const GENERATOR_TYPE_UUID = 6;
- /**
- * CUSTOM means that customer will use own ID generator that supposedly work
- */
- public const GENERATOR_TYPE_CUSTOM = 7;
- /**
- * DEFERRED_IMPLICIT means that changes of entities are calculated at commit-time
- * by doing a property-by-property comparison with the original data. This will
- * be done for all entities that are in MANAGED state at commit-time.
- *
- * This is the default change tracking policy.
- */
- public const CHANGETRACKING_DEFERRED_IMPLICIT = 1;
- /**
- * DEFERRED_EXPLICIT means that changes of entities are calculated at commit-time
- * by doing a property-by-property comparison with the original data. This will
- * be done only for entities that were explicitly saved (through persist() or a cascade).
- */
- public const CHANGETRACKING_DEFERRED_EXPLICIT = 2;
- /**
- * NOTIFY means that Doctrine relies on the entities sending out notifications
- * when their properties change. Such entity classes must implement
- * the <tt>NotifyPropertyChanged</tt> interface.
- */
- public const CHANGETRACKING_NOTIFY = 3;
- /**
- * Specifies that an association is to be fetched when it is first accessed.
- */
- public const FETCH_LAZY = 2;
- /**
- * Specifies that an association is to be fetched when the owner of the
- * association is fetched.
- */
- public const FETCH_EAGER = 3;
- /**
- * Specifies that an association is to be fetched lazy (on first access) and that
- * commands such as Collection#count, Collection#slice are issued directly against
- * the database if the collection is not yet initialized.
- */
- public const FETCH_EXTRA_LAZY = 4;
- /**
- * Identifies a one-to-one association.
- */
- public const ONE_TO_ONE = 1;
- /**
- * Identifies a many-to-one association.
- */
- public const MANY_TO_ONE = 2;
- /**
- * Identifies a one-to-many association.
- */
- public const ONE_TO_MANY = 4;
- /**
- * Identifies a many-to-many association.
- */
- public const MANY_TO_MANY = 8;
- /**
- * Combined bitmask for to-one (single-valued) associations.
- */
- public const TO_ONE = 3;
- /**
- * Combined bitmask for to-many (collection-valued) associations.
- */
- public const TO_MANY = 12;
- /**
- * ReadOnly cache can do reads, inserts and deletes, cannot perform updates or employ any locks,
- */
- public const CACHE_USAGE_READ_ONLY = 1;
- /**
- * Nonstrict Read Write Cache doesn’t employ any locks but can do inserts, update and deletes.
- */
- public const CACHE_USAGE_NONSTRICT_READ_WRITE = 2;
- /**
- * Read Write Attempts to lock the entity before update/delete.
- */
- public const CACHE_USAGE_READ_WRITE = 3;
- /**
- * READ-ONLY: The name of the entity class.
- *
- * @var string
- * @psalm-var class-string<T>
- */
- public $name;
- /**
- * READ-ONLY: The namespace the entity class is contained in.
- *
- * @var string
- * @todo Not really needed. Usage could be localized.
- */
- public $namespace;
- /**
- * READ-ONLY: The name of the entity class that is at the root of the mapped entity inheritance
- * hierarchy. If the entity is not part of a mapped inheritance hierarchy this is the same
- * as {@link $name}.
- *
- * @var string
- * @psalm-var class-string
- */
- public $rootEntityName;
- /**
- * READ-ONLY: The definition of custom generator. Only used for CUSTOM
- * generator type
- *
- * The definition has the following structure:
- * <code>
- * array(
- * 'class' => 'ClassName',
- * )
- * </code>
- *
- * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
- * @var array<string, string>|null
- */
- public $customGeneratorDefinition;
- /**
- * The name of the custom repository class used for the entity class.
- * (Optional).
- *
- * @var string|null
- * @psalm-var ?class-string
- */
- public $customRepositoryClassName;
- /**
- * READ-ONLY: Whether this class describes the mapping of a mapped superclass.
- *
- * @var bool
- */
- public $isMappedSuperclass = false;
- /**
- * READ-ONLY: Whether this class describes the mapping of an embeddable class.
- *
- * @var bool
- */
- public $isEmbeddedClass = false;
- /**
- * READ-ONLY: The names of the parent classes (ancestors).
- *
- * @psalm-var list<class-string>
- */
- public $parentClasses = [];
- /**
- * READ-ONLY: The names of all subclasses (descendants).
- *
- * @psalm-var list<class-string>
- */
- public $subClasses = [];
- /**
- * READ-ONLY: The names of all embedded classes based on properties.
- *
- * @psalm-var array<string, mixed[]>
- */
- public $embeddedClasses = [];
- /**
- * READ-ONLY: The named queries allowed to be called directly from Repository.
- *
- * @psalm-var array<string, array<string, mixed>>
- */
- public $namedQueries = [];
- /**
- * READ-ONLY: The named native queries allowed to be called directly from Repository.
- *
- * A native SQL named query definition has the following structure:
- * <pre>
- * array(
- * 'name' => <query name>,
- * 'query' => <sql query>,
- * 'resultClass' => <class of the result>,
- * 'resultSetMapping' => <name of a SqlResultSetMapping>
- * )
- * </pre>
- *
- * @psalm-var array<string, array<string, mixed>>
- */
- public $namedNativeQueries = [];
- /**
- * READ-ONLY: The mappings of the results of native SQL queries.
- *
- * A native result mapping definition has the following structure:
- * <pre>
- * array(
- * 'name' => <result name>,
- * 'entities' => array(<entity result mapping>),
- * 'columns' => array(<column result mapping>)
- * )
- * </pre>
- *
- * @psalm-var array<string, array{
- * name: string,
- * entities: mixed[],
- * columns: mixed[]
- * }>
- */
- public $sqlResultSetMappings = [];
- /**
- * READ-ONLY: The field names of all fields that are part of the identifier/primary key
- * of the mapped entity class.
- *
- * @psalm-var list<string>
- */
- public $identifier = [];
- /**
- * READ-ONLY: The inheritance mapping type used by the class.
- *
- * @var int
- * @psalm-var self::$INHERITANCE_TYPE_*
- */
- public $inheritanceType = self::INHERITANCE_TYPE_NONE;
- /**
- * READ-ONLY: The Id generator type used by the class.
- *
- * @var int
- */
- public $generatorType = self::GENERATOR_TYPE_NONE;
- /**
- * READ-ONLY: The field mappings of the class.
- * Keys are field names and values are mapping definitions.
- *
- * The mapping definition array has the following values:
- *
- * - <b>fieldName</b> (string)
- * The name of the field in the Entity.
- *
- * - <b>type</b> (string)
- * The type name of the mapped field. Can be one of Doctrine's mapping types
- * or a custom mapping type.
- *
- * - <b>columnName</b> (string, optional)
- * The column name. Optional. Defaults to the field name.
- *
- * - <b>length</b> (integer, optional)
- * The database length of the column. Optional. Default value taken from
- * the type.
- *
- * - <b>id</b> (boolean, optional)
- * Marks the field as the primary key of the entity. Multiple fields of an
- * entity can have the id attribute, forming a composite key.
- *
- * - <b>nullable</b> (boolean, optional)
- * Whether the column is nullable. Defaults to FALSE.
- *
- * - <b>columnDefinition</b> (string, optional, schema-only)
- * The SQL fragment that is used when generating the DDL for the column.
- *
- * - <b>precision</b> (integer, optional, schema-only)
- * The precision of a decimal column. Only valid if the column type is decimal.
- *
- * - <b>scale</b> (integer, optional, schema-only)
- * The scale of a decimal column. Only valid if the column type is decimal.
- *
- * - <b>'unique'</b> (string, optional, schema-only)
- * Whether a unique constraint should be generated for the column.
- *
- * @var mixed[]
- * @psalm-var array<string, array{
- * type: string,
- * fieldName: string,
- * columnName?: string,
- * length?: int,
- * id?: bool,
- * nullable?: bool,
- * columnDefinition?: string,
- * precision?: int,
- * scale?: int,
- * unique?: string,
- * inherited?: class-string,
- * originalClass?: class-string,
- * originalField?: string,
- * quoted?: bool,
- * requireSQLConversion?: bool,
- * declared?: class-string,
- * declaredField?: string,
- * options: array<mixed>
- * }>
- */
- public $fieldMappings = [];
- /**
- * READ-ONLY: An array of field names. Used to look up field names from column names.
- * Keys are column names and values are field names.
- *
- * @psalm-var array<string, string>
- */
- public $fieldNames = [];
- /**
- * READ-ONLY: A map of field names to column names. Keys are field names and values column names.
- * Used to look up column names from field names.
- * This is the reverse lookup map of $_fieldNames.
- *
- * @deprecated 3.0 Remove this.
- *
- * @var mixed[]
- */
- public $columnNames = [];
- /**
- * READ-ONLY: The discriminator value of this class.
- *
- * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
- * where a discriminator column is used.</b>
- *
- * @see discriminatorColumn
- *
- * @var mixed
- */
- public $discriminatorValue;
- /**
- * READ-ONLY: The discriminator map of all mapped classes in the hierarchy.
- *
- * <b>This does only apply to the JOINED and SINGLE_TABLE inheritance mapping strategies
- * where a discriminator column is used.</b>
- *
- * @see discriminatorColumn
- *
- * @var mixed
- */
- public $discriminatorMap = [];
- /**
- * READ-ONLY: The definition of the discriminator column used in JOINED and SINGLE_TABLE
- * inheritance mappings.
- *
- * @psalm-var array<string, mixed>
- */
- public $discriminatorColumn;
- /**
- * READ-ONLY: The primary table definition. The definition is an array with the
- * following entries:
- *
- * name => <tableName>
- * schema => <schemaName>
- * indexes => array
- * uniqueConstraints => array
- *
- * @var mixed[]
- * @psalm-var array{
- * name: string,
- * schema: string,
- * indexes: array,
- * uniqueConstraints: array,
- * options: array<string, mixed>,
- * quoted?: bool
- * }
- */
- public $table;
- /**
- * READ-ONLY: The registered lifecycle callbacks for entities of this class.
- *
- * @psalm-var array<string, list<string>>
- */
- public $lifecycleCallbacks = [];
- /**
- * READ-ONLY: The registered entity listeners.
- *
- * @psalm-var array<string, list<array{class: class-string, method: string}>>
- */
- public $entityListeners = [];
- /**
- * READ-ONLY: The association mappings of this class.
- *
- * The mapping definition array supports the following keys:
- *
- * - <b>fieldName</b> (string)
- * The name of the field in the entity the association is mapped to.
- *
- * - <b>targetEntity</b> (string)
- * The class name of the target entity. If it is fully-qualified it is used as is.
- * If it is a simple, unqualified class name the namespace is assumed to be the same
- * as the namespace of the source entity.
- *
- * - <b>mappedBy</b> (string, required for bidirectional associations)
- * The name of the field that completes the bidirectional association on the owning side.
- * This key must be specified on the inverse side of a bidirectional association.
- *
- * - <b>inversedBy</b> (string, required for bidirectional associations)
- * The name of the field that completes the bidirectional association on the inverse side.
- * This key must be specified on the owning side of a bidirectional association.
- *
- * - <b>cascade</b> (array, optional)
- * The names of persistence operations to cascade on the association. The set of possible
- * values are: "persist", "remove", "detach", "merge", "refresh", "all" (implies all others).
- *
- * - <b>orderBy</b> (array, one-to-many/many-to-many only)
- * A map of field names (of the target entity) to sorting directions (ASC/DESC).
- * Example: array('priority' => 'desc')
- *
- * - <b>fetch</b> (integer, optional)
- * The fetching strategy to use for the association, usually defaults to FETCH_LAZY.
- * Possible values are: ClassMetadata::FETCH_EAGER, ClassMetadata::FETCH_LAZY.
- *
- * - <b>joinTable</b> (array, optional, many-to-many only)
- * Specification of the join table and its join columns (foreign keys).
- * Only valid for many-to-many mappings. Note that one-to-many associations can be mapped
- * through a join table by simply mapping the association as many-to-many with a unique
- * constraint on the join table.
- *
- * - <b>indexBy</b> (string, optional, to-many only)
- * Specification of a field on target-entity that is used to index the collection by.
- * This field HAS to be either the primary key or a unique column. Otherwise the collection
- * does not contain all the entities that are actually related.
- *
- * A join table definition has the following structure:
- * <pre>
- * array(
- * 'name' => <join table name>,
- * 'joinColumns' => array(<join column mapping from join table to source table>),
- * 'inverseJoinColumns' => array(<join column mapping from join table to target table>)
- * )
- * </pre>
- *
- * @psalm-var array<string, array<string, mixed>>
- */
- public $associationMappings = [];
- /**
- * READ-ONLY: Flag indicating whether the identifier/primary key of the class is composite.
- *
- * @var bool
- */
- public $isIdentifierComposite = false;
- /**
- * READ-ONLY: Flag indicating whether the identifier/primary key contains at least one foreign key association.
- *
- * This flag is necessary because some code blocks require special treatment of this cases.
- *
- * @var bool
- */
- public $containsForeignIdentifier = false;
- /**
- * READ-ONLY: The ID generator used for generating IDs for this class.
- *
- * @var AbstractIdGenerator
- * @todo Remove!
- */
- public $idGenerator;
- /**
- * READ-ONLY: The definition of the sequence generator of this class. Only used for the
- * SEQUENCE generation strategy.
- *
- * The definition has the following structure:
- * <code>
- * array(
- * 'sequenceName' => 'name',
- * 'allocationSize' => '20',
- * 'initialValue' => '1'
- * )
- * </code>
- *
- * @var array<string, mixed>
- * @psalm-var array{sequenceName: string, allocationSize: string, initialValue: string, quoted?: mixed}
- * @todo Merge with tableGeneratorDefinition into generic generatorDefinition
- */
- public $sequenceGeneratorDefinition;
- /**
- * READ-ONLY: The definition of the table generator of this class. Only used for the
- * TABLE generation strategy.
- *
- * @deprecated
- *
- * @var array<string, mixed>
- */
- public $tableGeneratorDefinition;
- /**
- * READ-ONLY: The policy used for change-tracking on entities of this class.
- *
- * @var int
- */
- public $changeTrackingPolicy = self::CHANGETRACKING_DEFERRED_IMPLICIT;
- /**
- * READ-ONLY: A flag for whether or not instances of this class are to be versioned
- * with optimistic locking.
- *
- * @var bool
- */
- public $isVersioned;
- /**
- * READ-ONLY: The name of the field which is used for versioning in optimistic locking (if any).
- *
- * @var mixed
- */
- public $versionField;
- /** @var mixed[] */
- public $cache = null;
- /**
- * The ReflectionClass instance of the mapped class.
- *
- * @var ReflectionClass|null
- */
- public $reflClass;
- /**
- * Is this entity marked as "read-only"?
- *
- * That means it is never considered for change-tracking in the UnitOfWork. It is a very helpful performance
- * optimization for entities that are immutable, either in your domain or through the relation database
- * (coming from a view, or a history table for example).
- *
- * @var bool
- */
- public $isReadOnly = false;
- /**
- * NamingStrategy determining the default column and table names.
- *
- * @var NamingStrategy
- */
- protected $namingStrategy;
- /**
- * The ReflectionProperty instances of the mapped class.
- *
- * @var ReflectionProperty[]|null[]
- */
- public $reflFields = [];
- /** @var InstantiatorInterface|null */
- private $instantiator;
- /**
- * Initializes a new ClassMetadata instance that will hold the object-relational mapping
- * metadata of the class with the given name.
- *
- * @param string $entityName The name of the entity class the new instance is used for.
- * @psalm-param class-string<T> $entityName
- */
- public function __construct($entityName, ?NamingStrategy $namingStrategy = null)
- {
- $this->name = $entityName;
- $this->rootEntityName = $entityName;
- $this->namingStrategy = $namingStrategy ?: new DefaultNamingStrategy();
- $this->instantiator = new Instantiator();
- }
- /**
- * Gets the ReflectionProperties of the mapped class.
- *
- * @return ReflectionProperty[]|null[] An array of ReflectionProperty instances.
- * @psalm-return array<ReflectionProperty|null>
- */
- public function getReflectionProperties()
- {
- return $this->reflFields;
- }
- /**
- * Gets a ReflectionProperty for a specific field of the mapped class.
- *
- * @param string $name
- *
- * @return ReflectionProperty
- */
- public function getReflectionProperty($name)
- {
- return $this->reflFields[$name];
- }
- /**
- * Gets the ReflectionProperty for the single identifier field.
- *
- * @return ReflectionProperty
- *
- * @throws BadMethodCallException If the class has a composite identifier.
- */
- public function getSingleIdReflectionProperty()
- {
- if ($this->isIdentifierComposite) {
- throw new BadMethodCallException('Class ' . $this->name . ' has a composite identifier.');
- }
- return $this->reflFields[$this->identifier[0]];
- }
- /**
- * Extracts the identifier values of an entity of this class.
- *
- * For composite identifiers, the identifier values are returned as an array
- * with the same order as the field order in {@link identifier}.
- *
- * @param object $entity
- *
- * @return array<string, mixed>
- */
- public function getIdentifierValues($entity)
- {
- if ($this->isIdentifierComposite) {
- $id = [];
- foreach ($this->identifier as $idField) {
- $value = $this->reflFields[$idField]->getValue($entity);
- if ($value !== null) {
- $id[$idField] = $value;
- }
- }
- return $id;
- }
- $id = $this->identifier[0];
- $value = $this->reflFields[$id]->getValue($entity);
- if ($value === null) {
- return [];
- }
- return [$id => $value];
- }
- /**
- * Populates the entity identifier of an entity.
- *
- * @param object $entity
- * @psalm-param array<string, mixed> $id
- *
- * @return void
- *
- * @todo Rename to assignIdentifier()
- */
- public function setIdentifierValues($entity, array $id)
- {
- foreach ($id as $idField => $idValue) {
- $this->reflFields[$idField]->setValue($entity, $idValue);
- }
- }
- /**
- * Sets the specified field to the specified value on the given entity.
- *
- * @param object $entity
- * @param string $field
- * @param mixed $value
- *
- * @return void
- */
- public function setFieldValue($entity, $field, $value)
- {
- $this->reflFields[$field]->setValue($entity, $value);
- }
- /**
- * Gets the specified field's value off the given entity.
- *
- * @param object $entity
- * @param string $field
- *
- * @return mixed
- */
- public function getFieldValue($entity, $field)
- {
- return $this->reflFields[$field]->getValue($entity);
- }
- /**
- * Creates a string representation of this instance.
- *
- * @return string The string representation of this instance.
- *
- * @todo Construct meaningful string representation.
- */
- public function __toString()
- {
- return self::class . '@' . spl_object_id($this);
- }
- /**
- * Determines which fields get serialized.
- *
- * It is only serialized what is necessary for best unserialization performance.
- * That means any metadata properties that are not set or empty or simply have
- * their default value are NOT serialized.
- *
- * Parts that are also NOT serialized because they can not be properly unserialized:
- * - reflClass (ReflectionClass)
- * - reflFields (ReflectionProperty array)
- *
- * @return string[] The names of all the fields that should be serialized.
- */
- public function __sleep()
- {
- // This metadata is always serialized/cached.
- $serialized = [
- 'associationMappings',
- 'columnNames', //TODO: 3.0 Remove this. Can use fieldMappings[$fieldName]['columnName']
- 'fieldMappings',
- 'fieldNames',
- 'embeddedClasses',
- 'identifier',
- 'isIdentifierComposite', // TODO: REMOVE
- 'name',
- 'namespace', // TODO: REMOVE
- 'table',
- 'rootEntityName',
- 'idGenerator', //TODO: Does not really need to be serialized. Could be moved to runtime.
- ];
- // The rest of the metadata is only serialized if necessary.
- if ($this->changeTrackingPolicy !== self::CHANGETRACKING_DEFERRED_IMPLICIT) {
- $serialized[] = 'changeTrackingPolicy';
- }
- if ($this->customRepositoryClassName) {
- $serialized[] = 'customRepositoryClassName';
- }
- if ($this->inheritanceType !== self::INHERITANCE_TYPE_NONE) {
- $serialized[] = 'inheritanceType';
- $serialized[] = 'discriminatorColumn';
- $serialized[] = 'discriminatorValue';
- $serialized[] = 'discriminatorMap';
- $serialized[] = 'parentClasses';
- $serialized[] = 'subClasses';
- }
- if ($this->generatorType !== self::GENERATOR_TYPE_NONE) {
- $serialized[] = 'generatorType';
- if ($this->generatorType === self::GENERATOR_TYPE_SEQUENCE) {
- $serialized[] = 'sequenceGeneratorDefinition';
- }
- }
- if ($this->isMappedSuperclass) {
- $serialized[] = 'isMappedSuperclass';
- }
- if ($this->isEmbeddedClass) {
- $serialized[] = 'isEmbeddedClass';
- }
- if ($this->containsForeignIdentifier) {
- $serialized[] = 'containsForeignIdentifier';
- }
- if ($this->isVersioned) {
- $serialized[] = 'isVersioned';
- $serialized[] = 'versionField';
- }
- if ($this->lifecycleCallbacks) {
- $serialized[] = 'lifecycleCallbacks';
- }
- if ($this->entityListeners) {
- $serialized[] = 'entityListeners';
- }
- if ($this->namedQueries) {
- $serialized[] = 'namedQueries';
- }
- if ($this->namedNativeQueries) {
- $serialized[] = 'namedNativeQueries';
- }
- if ($this->sqlResultSetMappings) {
- $serialized[] = 'sqlResultSetMappings';
- }
- if ($this->isReadOnly) {
- $serialized[] = 'isReadOnly';
- }
- if ($this->customGeneratorDefinition) {
- $serialized[] = 'customGeneratorDefinition';
- }
- if ($this->cache) {
- $serialized[] = 'cache';
- }
- return $serialized;
- }
- /**
- * Creates a new instance of the mapped class, without invoking the constructor.
- *
- * @return object
- */
- public function newInstance()
- {
- return $this->instantiator->instantiate($this->name);
- }
- /**
- * Restores some state that can not be serialized/unserialized.
- *
- * @param ReflectionService $reflService
- *
- * @return void
- */
- public function wakeupReflection($reflService)
- {
- // Restore ReflectionClass and properties
- $this->reflClass = $reflService->getClass($this->name);
- $this->instantiator = $this->instantiator ?: new Instantiator();
- $parentReflFields = [];
- foreach ($this->embeddedClasses as $property => $embeddedClass) {
- if (isset($embeddedClass['declaredField'])) {
- $childProperty = $reflService->getAccessibleProperty(
- $this->embeddedClasses[$embeddedClass['declaredField']]['class'],
- $embeddedClass['originalField']
- );
- assert($childProperty !== null);
- $parentReflFields[$property] = new ReflectionEmbeddedProperty(
- $parentReflFields[$embeddedClass['declaredField']],
- $childProperty,
- $this->embeddedClasses[$embeddedClass['declaredField']]['class']
- );
- continue;
- }
- $fieldRefl = $reflService->getAccessibleProperty(
- $embeddedClass['declared'] ?? $this->name,
- $property
- );
- $parentReflFields[$property] = $fieldRefl;
- $this->reflFields[$property] = $fieldRefl;
- }
- foreach ($this->fieldMappings as $field => $mapping) {
- if (isset($mapping['declaredField']) && isset($parentReflFields[$mapping['declaredField']])) {
- $this->reflFields[$field] = new ReflectionEmbeddedProperty(
- $parentReflFields[$mapping['declaredField']],
- $reflService->getAccessibleProperty($mapping['originalClass'], $mapping['originalField']),
- $mapping['originalClass']
- );
- continue;
- }
- $this->reflFields[$field] = isset($mapping['declared'])
- ? $reflService->getAccessibleProperty($mapping['declared'], $field)
- : $reflService->getAccessibleProperty($this->name, $field);
- }
- foreach ($this->associationMappings as $field => $mapping) {
- $this->reflFields[$field] = isset($mapping['declared'])
- ? $reflService->getAccessibleProperty($mapping['declared'], $field)
- : $reflService->getAccessibleProperty($this->name, $field);
- }
- }
- /**
- * Initializes a new ClassMetadata instance that will hold the object-relational mapping
- * metadata of the class with the given name.
- *
- * @param ReflectionService $reflService The reflection service.
- *
- * @return void
- */
- public function initializeReflection($reflService)
- {
- $this->reflClass = $reflService->getClass($this->name);
- $this->namespace = $reflService->getClassNamespace($this->name);
- if ($this->reflClass) {
- $this->name = $this->rootEntityName = $this->reflClass->getName();
- }
- $this->table['name'] = $this->namingStrategy->classToTableName($this->name);
- }
- /**
- * Validates Identifier.
- *
- * @return void
- *
- * @throws MappingException
- */
- public function validateIdentifier()
- {
- if ($this->isMappedSuperclass || $this->isEmbeddedClass) {
- return;
- }
- // Verify & complete identifier mapping
- if (! $this->identifier) {
- throw MappingException::identifierRequired($this->name);
- }
- if ($this->usesIdGenerator() && $this->isIdentifierComposite) {
- throw MappingException::compositeKeyAssignedIdGeneratorRequired($this->name);
- }
- }
- /**
- * Validates association targets actually exist.
- *
- * @return void
- *
- * @throws MappingException
- */
- public function validateAssociations()
- {
- foreach ($this->associationMappings as $mapping) {
- if (
- ! class_exists($mapping['targetEntity'])
- && ! interface_exists($mapping['targetEntity'])
- && ! trait_exists($mapping['targetEntity'])
- ) {
- throw MappingException::invalidTargetEntityClass($mapping['targetEntity'], $this->name, $mapping['fieldName']);
- }
- }
- }
- /**
- * Validates lifecycle callbacks.
- *
- * @param ReflectionService $reflService
- *
- * @return void
- *
- * @throws MappingException
- */
- public function validateLifecycleCallbacks($reflService)
- {
- foreach ($this->lifecycleCallbacks as $callbacks) {
- foreach ($callbacks as $callbackFuncName) {
- if (! $reflService->hasPublicMethod($this->name, $callbackFuncName)) {
- throw MappingException::lifecycleCallbackMethodNotFound($this->name, $callbackFuncName);
- }
- }
- }
- }
- /**
- * {@inheritDoc}
- */
- public function getReflectionClass()
- {
- return $this->reflClass;
- }
- /**
- * @psalm-param array{usage?: mixed, region?: mixed} $cache
- *
- * @return void
- */
- public function enableCache(array $cache)
- {
- if (! isset($cache['usage'])) {
- $cache['usage'] = self::CACHE_USAGE_READ_ONLY;
- }
- if (! isset($cache['region'])) {
- $cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName));
- }
- $this->cache = $cache;
- }
- /**
- * @param string $fieldName
- * @psalm-param array{usage?: int, region?: string} $cache
- *
- * @return void
- */
- public function enableAssociationCache($fieldName, array $cache)
- {
- $this->associationMappings[$fieldName]['cache'] = $this->getAssociationCacheDefaults($fieldName, $cache);
- }
- /**
- * @param string $fieldName
- * @param array $cache
- * @psalm-param array{usage?: int, region?: string|null} $cache
- *
- * @return int[]|string[]
- * @psalm-return array{usage: int, region: string|null}
- */
- public function getAssociationCacheDefaults($fieldName, array $cache)
- {
- if (! isset($cache['usage'])) {
- $cache['usage'] = $this->cache['usage'] ?? self::CACHE_USAGE_READ_ONLY;
- }
- if (! isset($cache['region'])) {
- $cache['region'] = strtolower(str_replace('\\', '_', $this->rootEntityName)) . '__' . $fieldName;
- }
- return $cache;
- }
- /**
- * Sets the change tracking policy used by this class.
- *
- * @param int $policy
- *
- * @return void
- */
- public function setChangeTrackingPolicy($policy)
- {
- $this->changeTrackingPolicy = $policy;
- }
- /**
- * Whether the change tracking policy of this class is "deferred explicit".
- *
- * @return bool
- */
- public function isChangeTrackingDeferredExplicit()
- {
- return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_EXPLICIT;
- }
- /**
- * Whether the change tracking policy of this class is "deferred implicit".
- *
- * @return bool
- */
- public function isChangeTrackingDeferredImplicit()
- {
- return $this->changeTrackingPolicy === self::CHANGETRACKING_DEFERRED_IMPLICIT;
- }
- /**
- * Whether the change tracking policy of this class is "notify".
- *
- * @return bool
- */
- public function isChangeTrackingNotify()
- {
- return $this->changeTrackingPolicy === self::CHANGETRACKING_NOTIFY;
- }
- /**
- * Checks whether a field is part of the identifier/primary key field(s).
- *
- * @param string $fieldName The field name.
- *
- * @return bool TRUE if the field is part of the table identifier/primary key field(s),
- * FALSE otherwise.
- */
- public function isIdentifier($fieldName)
- {
- if (! $this->identifier) {
- return false;
- }
- if (! $this->isIdentifierComposite) {
- return $fieldName === $this->identifier[0];
- }
- return in_array($fieldName, $this->identifier, true);
- }
- /**
- * Checks if the field is unique.
- *
- * @param string $fieldName The field name.
- *
- * @return bool TRUE if the field is unique, FALSE otherwise.
- */
- public function isUniqueField($fieldName)
- {
- $mapping = $this->getFieldMapping($fieldName);
- return $mapping !== false && isset($mapping['unique']) && $mapping['unique'];
- }
- /**
- * Checks if the field is not null.
- *
- * @param string $fieldName The field name.
- *
- * @return bool TRUE if the field is not null, FALSE otherwise.
- */
- public function isNullable($fieldName)
- {
- $mapping = $this->getFieldMapping($fieldName);
- return $mapping !== false && isset($mapping['nullable']) && $mapping['nullable'];
- }
- /**
- * Gets a column name for a field name.
- * If the column name for the field cannot be found, the given field name
- * is returned.
- *
- * @param string $fieldName The field name.
- *
- * @return string The column name.
- */
- public function getColumnName($fieldName)
- {
- return $this->columnNames[$fieldName] ?? $fieldName;
- }
- /**
- * Gets the mapping of a (regular) field that holds some data but not a
- * reference to another object.
- *
- * @param string $fieldName The field name.
- *
- * @return mixed[] The field mapping.
- * @psalm-return array{
- * type: string,
- * fieldName: string,
- * columnName?: string,
- * inherited?: class-string,
- * nullable?: bool,
- * originalClass?: class-string,
- * originalField?: string,
- * scale?: int,
- * precision?: int,
- * length?: int
- * }
- *
- * @throws MappingException
- */
- public function getFieldMapping($fieldName)
- {
- if (! isset($this->fieldMappings[$fieldName])) {
- throw MappingException::mappingNotFound($this->name, $fieldName);
- }
- return $this->fieldMappings[$fieldName];
- }
- /**
- * Gets the mapping of an association.
- *
- * @see ClassMetadataInfo::$associationMappings
- *
- * @param string $fieldName The field name that represents the association in
- * the object model.
- *
- * @return mixed[] The mapping.
- * @psalm-return array<string, mixed>
- *
- * @throws MappingException
- */
- public function getAssociationMapping($fieldName)
- {
- if (! isset($this->associationMappings[$fieldName])) {
- throw MappingException::mappingNotFound($this->name, $fieldName);
- }
- return $this->associationMappings[$fieldName];
- }
- /**
- * Gets all association mappings of the class.
- *
- * @psalm-return array<string, array<string, mixed>>
- */
- public function getAssociationMappings()
- {
- return $this->associationMappings;
- }
- /**
- * Gets the field name for a column name.
- * If no field name can be found the column name is returned.
- *
- * @param string $columnName The column name.
- *
- * @return string The column alias.
- */
- public function getFieldName($columnName)
- {
- return $this->fieldNames[$columnName] ?? $columnName;
- }
- /**
- * Gets the named query.
- *
- * @see ClassMetadataInfo::$namedQueries
- *
- * @param string $queryName The query name.
- *
- * @return string
- *
- * @throws MappingException
- */
- public function getNamedQuery($queryName)
- {
- if (! isset($this->namedQueries[$queryName])) {
- throw MappingException::queryNotFound($this->name, $queryName);
- }
- return $this->namedQueries[$queryName]['dql'];
- }
- /**
- * Gets all named queries of the class.
- *
- * @return mixed[][]
- * @psalm-return array<string, array<string, mixed>>
- */
- public function getNamedQueries()
- {
- return $this->namedQueries;
- }
- /**
- * Gets the named native query.
- *
- * @see ClassMetadataInfo::$namedNativeQueries
- *
- * @param string $queryName The query name.
- *
- * @return mixed[]
- * @psalm-return array<string, mixed>
- *
- * @throws MappingException
- */
- public function getNamedNativeQuery($queryName)
- {
- if (! isset($this->namedNativeQueries[$queryName])) {
- throw MappingException::queryNotFound($this->name, $queryName);
- }
- return $this->namedNativeQueries[$queryName];
- }
- /**
- * Gets all named native queries of the class.
- *
- * @psalm-return array<string, array<string, mixed>>
- */
- public function getNamedNativeQueries()
- {
- return $this->namedNativeQueries;
- }
- /**
- * Gets the result set mapping.
- *
- * @see ClassMetadataInfo::$sqlResultSetMappings
- *
- * @param string $name The result set mapping name.
- *
- * @return mixed[]
- * @psalm-return array{name: string, entities: array, columns: array}
- *
- * @throws MappingException
- */
- public function getSqlResultSetMapping($name)
- {
- if (! isset($this->sqlResultSetMappings[$name])) {
- throw MappingException::resultMappingNotFound($this->name, $name);
- }
- return $this->sqlResultSetMappings[$name];
- }
- /**
- * Gets all sql result set mappings of the class.
- *
- * @return mixed[]
- * @psalm-return array<string, array{name: string, entities: array, columns: array}>
- */
- public function getSqlResultSetMappings()
- {
- return $this->sqlResultSetMappings;
- }
- /**
- * Checks whether given property has type
- *
- * @param string $name Property name
- */
- private function isTypedProperty(string $name): bool
- {
- return PHP_VERSION_ID >= 70400
- && isset($this->reflClass)
- && $this->reflClass->hasProperty($name)
- && $this->reflClass->getProperty($name)->hasType();
- }
- /**
- * Validates & completes the given field mapping based on typed property.
- *
- * @param mixed[] $mapping The field mapping to validate & complete.
- *
- * @return mixed[] The updated mapping.
- */
- private function validateAndCompleteTypedFieldMapping(array $mapping): array
- {
- $type = $this->reflClass->getProperty($mapping['fieldName'])->getType();
- if ($type) {
- if (
- ! isset($mapping['type'])
- && ($type instanceof ReflectionNamedType)
- ) {
- switch ($type->getName()) {
- case DateInterval::class:
- $mapping['type'] = Types::DATEINTERVAL;
- break;
- case DateTime::class:
- $mapping['type'] = Types::DATETIME_MUTABLE;
- break;
- case DateTimeImmutable::class:
- $mapping['type'] = Types::DATETIME_IMMUTABLE;
- break;
- case 'array':
- $mapping['type'] = Types::JSON;
- break;
- case 'bool':
- $mapping['type'] = Types::BOOLEAN;
- break;
- case 'float':
- $mapping['type'] = Types::FLOAT;
- break;
- case 'int':
- $mapping['type'] = Types::INTEGER;
- break;
- case 'string':
- $mapping['type'] = Types::STRING;
- break;
- }
- }
- }
- return $mapping;
- }
- /**
- * Validates & completes the basic mapping information based on typed property.
- *
- * @param mixed[] $mapping The mapping.
- *
- * @return mixed[] The updated mapping.
- */
- private function validateAndCompleteTypedAssociationMapping(array $mapping): array
- {
- $type = $this->reflClass->getProperty($mapping['fieldName'])->getType();
- if ($type === null || ($mapping['type'] & self::TO_ONE) === 0) {
- return $mapping;
- }
- if (! isset($mapping['targetEntity']) && $type instanceof ReflectionNamedType) {
- $mapping['targetEntity'] = $type->getName();
- }
- return $mapping;
- }
- /**
- * Validates & completes the given field mapping.
- *
- * @psalm-param array<string, mixed> $mapping The field mapping to validate & complete.
- *
- * @return mixed[] The updated mapping.
- *
- * @throws MappingException
- */
- protected function validateAndCompleteFieldMapping(array $mapping): array
- {
- // Check mandatory fields
- if (! isset($mapping['fieldName']) || ! $mapping['fieldName']) {
- throw MappingException::missingFieldName($this->name);
- }
- if ($this->isTypedProperty($mapping['fieldName'])) {
- $mapping = $this->validateAndCompleteTypedFieldMapping($mapping);
- }
- if (! isset($mapping['type'])) {
- // Default to string
- $mapping['type'] = 'string';
- }
- // Complete fieldName and columnName mapping
- if (! isset($mapping['columnName'])) {
- $mapping['columnName'] = $this->namingStrategy->propertyToColumnName($mapping['fieldName'], $this->name);
- }
- if ($mapping['columnName'][0] === '`') {
- $mapping['columnName'] = trim($mapping['columnName'], '`');
- $mapping['quoted'] = true;
- }
- $this->columnNames[$mapping['fieldName']] = $mapping['columnName'];
- if (isset($this->fieldNames[$mapping['columnName']]) || ($this->discriminatorColumn && $this->discriminatorColumn['name'] === $mapping['columnName'])) {
- throw MappingException::duplicateColumnName($this->name, $mapping['columnName']);
- }
- $this->fieldNames[$mapping['columnName']] = $mapping['fieldName'];
- // Complete id mapping
- if (isset($mapping['id']) && $mapping['id'] === true) {
- if ($this->versionField === $mapping['fieldName']) {
- throw MappingException::cannotVersionIdField($this->name, $mapping['fieldName']);
- }
- if (! in_array($mapping['fieldName'], $this->identifier, true)) {
- $this->identifier[] = $mapping['fieldName'];
- }
- // Check for composite key
- if (! $this->isIdentifierComposite && count($this->identifier) > 1) {
- $this->isIdentifierComposite = true;
- }
- }
- if (Type::hasType($mapping['type']) && Type::getType($mapping['type'])->canRequireSQLConversion()) {
- if (isset($mapping['id']) && $mapping['id'] === true) {
- throw MappingException::sqlConversionNotAllowedForIdentifiers($this->name, $mapping['fieldName'], $mapping['type']);
- }
- $mapping['requireSQLConversion'] = true;
- }
- return $mapping;
- }
- /**
- * Validates & completes the basic mapping information that is common to all
- * association mappings (one-to-one, many-ot-one, one-to-many, many-to-many).
- *
- * @psalm-param array<string, mixed> $mapping The mapping.
- *
- * @return mixed[] The updated mapping.
- * @psalm-return array{
- * mappedBy: mixed|null,
- * inversedBy: mixed|null,
- * isOwningSide: bool,
- * sourceEntity: class-string,
- * targetEntity: string,
- * fieldName: mixed,
- * fetch: mixed,
- * cascade: array<array-key,string>,
- * isCascadeRemove: bool,
- * isCascadePersist: bool,
- * isCascadeRefresh: bool,
- * isCascadeMerge: bool,
- * isCascadeDetach: bool,
- * type: int,
- * originalField: string,
- * originalClass: class-string,
- * ?orphanRemoval: bool
- * }
- *
- * @throws MappingException If something is wrong with the …
Large files files are truncated, but you can click here to view the full file