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

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