ClassMetadataInfo.php 94 KB

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