vendor/doctrine/orm/src/Mapping/ClassMetadataInfo.php line 1213

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