Table.php 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\ORM;
  17. use ArrayObject;
  18. use BadMethodCallException;
  19. use Cake\Core\App;
  20. use Cake\Database\Connection;
  21. use Cake\Database\Schema\TableSchema;
  22. use Cake\Database\TypeFactory;
  23. use Cake\Datasource\ConnectionInterface;
  24. use Cake\Datasource\ConnectionManager;
  25. use Cake\Datasource\EntityInterface;
  26. use Cake\Datasource\Exception\InvalidPrimaryKeyException;
  27. use Cake\Datasource\RepositoryInterface;
  28. use Cake\Datasource\RulesAwareTrait;
  29. use Cake\Event\EventDispatcherInterface;
  30. use Cake\Event\EventDispatcherTrait;
  31. use Cake\Event\EventListenerInterface;
  32. use Cake\Event\EventManager;
  33. use Cake\ORM\Association\BelongsTo;
  34. use Cake\ORM\Association\BelongsToMany;
  35. use Cake\ORM\Association\HasMany;
  36. use Cake\ORM\Association\HasOne;
  37. use Cake\ORM\Exception\MissingEntityException;
  38. use Cake\ORM\Exception\PersistenceFailedException;
  39. use Cake\ORM\Exception\RolledbackTransactionException;
  40. use Cake\ORM\Rule\IsUnique;
  41. use Cake\Utility\Inflector;
  42. use Cake\Validation\ValidatorAwareInterface;
  43. use Cake\Validation\ValidatorAwareTrait;
  44. use Exception;
  45. use InvalidArgumentException;
  46. use RuntimeException;
  47. /**
  48. * Represents a single database table.
  49. *
  50. * Exposes methods for retrieving data out of it, and manages the associations
  51. * this table has to other tables. Multiple instances of this class can be created
  52. * for the same database table with different aliases, this allows you to address
  53. * your database structure in a richer and more expressive way.
  54. *
  55. * ### Retrieving data
  56. *
  57. * The primary way to retrieve data is using Table::find(). See that method
  58. * for more information.
  59. *
  60. * ### Dynamic finders
  61. *
  62. * In addition to the standard find($type) finder methods, CakePHP provides dynamic
  63. * finder methods. These methods allow you to easily set basic conditions up. For example
  64. * to filter users by username you would call
  65. *
  66. * ```
  67. * $query = $users->findByUsername('mark');
  68. * ```
  69. *
  70. * You can also combine conditions on multiple fields using either `Or` or `And`:
  71. *
  72. * ```
  73. * $query = $users->findByUsernameOrEmail('mark', 'mark@example.org');
  74. * ```
  75. *
  76. * ### Bulk updates/deletes
  77. *
  78. * You can use Table::updateAll() and Table::deleteAll() to do bulk updates/deletes.
  79. * You should be aware that events will *not* be fired for bulk updates/deletes.
  80. *
  81. * ### Callbacks/events
  82. *
  83. * Table objects provide a few callbacks/events you can hook into to augment/replace
  84. * find operations. Each event uses the standard event subsystem in CakePHP
  85. *
  86. * - `beforeFind(EventInterface $event, Query $query, ArrayObject $options, boolean $primary)`
  87. * Fired before each find operation. By stopping the event and supplying a
  88. * return value you can bypass the find operation entirely. Any changes done
  89. * to the $query instance will be retained for the rest of the find. The
  90. * $primary parameter indicates whether or not this is the root query,
  91. * or an associated query.
  92. *
  93. * - `buildValidator(EventInterface $event, Validator $validator, string $name)`
  94. * Allows listeners to modify validation rules for the provided named validator.
  95. *
  96. * - `buildRules(EventInterface $event, RulesChecker $rules)`
  97. * Allows listeners to modify the rules checker by adding more rules.
  98. *
  99. * - `beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, string $operation)`
  100. * Fired before an entity is validated using the rules checker. By stopping this event,
  101. * you can return the final value of the rules checking operation.
  102. *
  103. * - `afterRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation)`
  104. * Fired after the rules have been checked on the entity. By stopping this event,
  105. * you can return the final value of the rules checking operation.
  106. *
  107. * - `beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
  108. * Fired before each entity is saved. Stopping this event will abort the save
  109. * operation. When the event is stopped the result of the event will be returned.
  110. *
  111. * - `afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
  112. * Fired after an entity is saved.
  113. *
  114. * - `afterSaveCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
  115. * Fired after the transaction in which the save operation is wrapped has been committed.
  116. * It’s also triggered for non atomic saves where database operations are implicitly committed.
  117. * The event is triggered only for the primary table on which save() is directly called.
  118. * The event is not triggered if a transaction is started before calling save.
  119. *
  120. * - `beforeDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
  121. * Fired before an entity is deleted. By stopping this event you will abort
  122. * the delete operation.
  123. *
  124. * - `afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)`
  125. * Fired after an entity has been deleted.
  126. *
  127. * @see \Cake\Event\EventManager for reference on the events system.
  128. */
  129. class Table implements RepositoryInterface, EventListenerInterface, EventDispatcherInterface, ValidatorAwareInterface
  130. {
  131. use EventDispatcherTrait;
  132. use RulesAwareTrait;
  133. use ValidatorAwareTrait;
  134. /**
  135. * The alias this object is assigned to validators as.
  136. *
  137. * @var string
  138. */
  139. public const VALIDATOR_PROVIDER_NAME = 'table';
  140. /**
  141. * The name of the event dispatched when a validator has been built.
  142. *
  143. * @var string
  144. */
  145. public const BUILD_VALIDATOR_EVENT = 'Model.buildValidator';
  146. /**
  147. * The rules class name that is used.
  148. *
  149. * @var string
  150. */
  151. public const RULES_CLASS = RulesChecker::class;
  152. /**
  153. * The IsUnique class name that is used.
  154. *
  155. * @var string
  156. */
  157. public const IS_UNIQUE_CLASS = IsUnique::class;
  158. /**
  159. * Name of the table as it can be found in the database
  160. *
  161. * @var string
  162. */
  163. protected $_table;
  164. /**
  165. * Human name giving to this particular instance. Multiple objects representing
  166. * the same database table can exist by using different aliases.
  167. *
  168. * @var string
  169. */
  170. protected $_alias;
  171. /**
  172. * Connection instance
  173. *
  174. * @var \Cake\Database\Connection|null
  175. */
  176. protected $_connection;
  177. /**
  178. * The schema object containing a description of this table fields
  179. *
  180. * @var \Cake\Database\Schema\TableSchema
  181. */
  182. protected $_schema;
  183. /**
  184. * The name of the field that represents the primary key in the table
  185. *
  186. * @var string|array
  187. */
  188. protected $_primaryKey;
  189. /**
  190. * The name of the field that represents a human readable representation of a row
  191. *
  192. * @var string|array
  193. */
  194. protected $_displayField;
  195. /**
  196. * The associations container for this Table.
  197. *
  198. * @var \Cake\ORM\AssociationCollection
  199. */
  200. protected $_associations;
  201. /**
  202. * BehaviorRegistry for this table
  203. *
  204. * @var \Cake\ORM\BehaviorRegistry
  205. */
  206. protected $_behaviors;
  207. /**
  208. * The name of the class that represent a single row for this table
  209. *
  210. * @var string
  211. */
  212. protected $_entityClass;
  213. /**
  214. * Registry key used to create this table object
  215. *
  216. * @var string
  217. */
  218. protected $_registryAlias;
  219. /**
  220. * Initializes a new instance
  221. *
  222. * The $config array understands the following keys:
  223. *
  224. * - table: Name of the database table to represent
  225. * - alias: Alias to be assigned to this table (default to table name)
  226. * - connection: The connection instance to use
  227. * - entityClass: The fully namespaced class name of the entity class that will
  228. * represent rows in this table.
  229. * - schema: A \Cake\Database\Schema\TableSchema object or an array that can be
  230. * passed to it.
  231. * - eventManager: An instance of an event manager to use for internal events
  232. * - behaviors: A BehaviorRegistry. Generally not used outside of tests.
  233. * - associations: An AssociationCollection instance.
  234. * - validator: A Validator instance which is assigned as the "default"
  235. * validation set, or an associative array, where key is the name of the
  236. * validation set and value the Validator instance.
  237. *
  238. * @param array $config List of options for this table
  239. */
  240. public function __construct(array $config = [])
  241. {
  242. if (!empty($config['registryAlias'])) {
  243. $this->setRegistryAlias($config['registryAlias']);
  244. }
  245. if (!empty($config['table'])) {
  246. $this->setTable($config['table']);
  247. }
  248. if (!empty($config['alias'])) {
  249. $this->setAlias($config['alias']);
  250. }
  251. if (!empty($config['connection'])) {
  252. $this->setConnection($config['connection']);
  253. }
  254. if (!empty($config['schema'])) {
  255. $this->setSchema($config['schema']);
  256. }
  257. if (!empty($config['entityClass'])) {
  258. $this->setEntityClass($config['entityClass']);
  259. }
  260. $eventManager = $behaviors = $associations = null;
  261. if (!empty($config['eventManager'])) {
  262. $eventManager = $config['eventManager'];
  263. }
  264. if (!empty($config['behaviors'])) {
  265. $behaviors = $config['behaviors'];
  266. }
  267. if (!empty($config['associations'])) {
  268. $associations = $config['associations'];
  269. }
  270. if (!empty($config['validator'])) {
  271. if (!is_array($config['validator'])) {
  272. $this->setValidator(static::DEFAULT_VALIDATOR, $config['validator']);
  273. } else {
  274. foreach ($config['validator'] as $name => $validator) {
  275. $this->setValidator($name, $validator);
  276. }
  277. }
  278. }
  279. $this->_eventManager = $eventManager ?: new EventManager();
  280. $this->_behaviors = $behaviors ?: new BehaviorRegistry();
  281. $this->_behaviors->setTable($this);
  282. $this->_associations = $associations ?: new AssociationCollection();
  283. $this->initialize($config);
  284. $this->_eventManager->on($this);
  285. $this->dispatchEvent('Model.initialize');
  286. }
  287. /**
  288. * Get the default connection name.
  289. *
  290. * This method is used to get the fallback connection name if an
  291. * instance is created through the TableLocator without a connection.
  292. *
  293. * @return string
  294. * @see \Cake\ORM\Locator\TableLocator::get()
  295. */
  296. public static function defaultConnectionName(): string
  297. {
  298. return 'default';
  299. }
  300. /**
  301. * Initialize a table instance. Called after the constructor.
  302. *
  303. * You can use this method to define associations, attach behaviors
  304. * define validation and do any other initialization logic you need.
  305. *
  306. * ```
  307. * public function initialize(array $config)
  308. * {
  309. * $this->belongsTo('Users');
  310. * $this->belongsToMany('Tagging.Tags');
  311. * $this->setPrimaryKey('something_else');
  312. * }
  313. * ```
  314. *
  315. * @param array $config Configuration options passed to the constructor
  316. * @return void
  317. */
  318. public function initialize(array $config): void
  319. {
  320. }
  321. /**
  322. * Sets the database table name.
  323. *
  324. * This can include the database schema name in the form 'schema.table'.
  325. * If the name must be quoted, enable automatic identifier quoting.
  326. *
  327. * @param string $table Table name.
  328. * @return $this
  329. */
  330. public function setTable(string $table)
  331. {
  332. $this->_table = $table;
  333. return $this;
  334. }
  335. /**
  336. * Returns the database table name.
  337. *
  338. * This can include the database schema name if set using `setTable()`.
  339. *
  340. * @return string
  341. */
  342. public function getTable(): string
  343. {
  344. if ($this->_table === null) {
  345. $table = namespaceSplit(static::class);
  346. $table = substr(end($table), 0, -5);
  347. if (!$table) {
  348. $table = $this->getAlias();
  349. }
  350. $this->_table = Inflector::underscore($table);
  351. }
  352. return $this->_table;
  353. }
  354. /**
  355. * Sets the table alias.
  356. *
  357. * @param string $alias Table alias
  358. * @return $this
  359. */
  360. public function setAlias(string $alias)
  361. {
  362. $this->_alias = $alias;
  363. return $this;
  364. }
  365. /**
  366. * Returns the table alias.
  367. *
  368. * @return string
  369. */
  370. public function getAlias(): string
  371. {
  372. if ($this->_alias === null) {
  373. $alias = namespaceSplit(static::class);
  374. $alias = substr(end($alias), 0, -5) ?: $this->_table;
  375. $this->_alias = $alias;
  376. }
  377. return $this->_alias;
  378. }
  379. /**
  380. * Alias a field with the table's current alias.
  381. *
  382. * If field is already aliased it will result in no-op.
  383. *
  384. * @param string $field The field to alias.
  385. * @return string The field prefixed with the table alias.
  386. */
  387. public function aliasField(string $field): string
  388. {
  389. if (strpos($field, '.') !== false) {
  390. return $field;
  391. }
  392. return $this->getAlias() . '.' . $field;
  393. }
  394. /**
  395. * Sets the table registry key used to create this table instance.
  396. *
  397. * @param string $registryAlias The key used to access this object.
  398. * @return $this
  399. */
  400. public function setRegistryAlias(string $registryAlias)
  401. {
  402. $this->_registryAlias = $registryAlias;
  403. return $this;
  404. }
  405. /**
  406. * Returns the table registry key used to create this table instance.
  407. *
  408. * @return string
  409. */
  410. public function getRegistryAlias(): string
  411. {
  412. if ($this->_registryAlias === null) {
  413. $this->_registryAlias = $this->getAlias();
  414. }
  415. return $this->_registryAlias;
  416. }
  417. /**
  418. * Sets the connection instance.
  419. *
  420. * @param \Cake\Database\Connection $connection The connection instance
  421. * @return $this
  422. */
  423. public function setConnection(ConnectionInterface $connection)
  424. {
  425. $this->_connection = $connection;
  426. return $this;
  427. }
  428. /**
  429. * Returns the connection instance.
  430. *
  431. * @return \Cake\Database\Connection
  432. */
  433. public function getConnection(): Connection
  434. {
  435. if (!$this->_connection) {
  436. /** @var \Cake\Database\Connection $connection */
  437. $connection = ConnectionManager::get(static::defaultConnectionName());
  438. $this->_connection = $connection;
  439. }
  440. return $this->_connection;
  441. }
  442. /**
  443. * Returns the schema table object describing this table's properties.
  444. *
  445. * @return \Cake\Database\Schema\TableSchema
  446. */
  447. public function getSchema(): TableSchema
  448. {
  449. if ($this->_schema === null) {
  450. $this->_schema = $this->_initializeSchema(
  451. $this->getConnection()
  452. ->getSchemaCollection()
  453. ->describe($this->getTable())
  454. );
  455. }
  456. return $this->_schema;
  457. }
  458. /**
  459. * Sets the schema table object describing this table's properties.
  460. *
  461. * If an array is passed, a new TableSchema will be constructed
  462. * out of it and used as the schema for this table.
  463. *
  464. * @param array|\Cake\Database\Schema\TableSchema $schema Schema to be used for this table
  465. * @return $this
  466. */
  467. public function setSchema($schema)
  468. {
  469. if (is_array($schema)) {
  470. $constraints = [];
  471. if (isset($schema['_constraints'])) {
  472. $constraints = $schema['_constraints'];
  473. unset($schema['_constraints']);
  474. }
  475. $schema = new TableSchema($this->getTable(), $schema);
  476. foreach ($constraints as $name => $value) {
  477. $schema->addConstraint($name, $value);
  478. }
  479. }
  480. $this->_schema = $schema;
  481. return $this;
  482. }
  483. /**
  484. * Override this function in order to alter the schema used by this table.
  485. * This function is only called after fetching the schema out of the database.
  486. * If you wish to provide your own schema to this table without touching the
  487. * database, you can override schema() or inject the definitions though that
  488. * method.
  489. *
  490. * ### Example:
  491. *
  492. * ```
  493. * protected function _initializeSchema(\Cake\Database\Schema\TableSchema $schema) {
  494. * $schema->setColumnType('preferences', 'json');
  495. * return $schema;
  496. * }
  497. * ```
  498. *
  499. * @param \Cake\Database\Schema\TableSchema $schema The table definition fetched from database.
  500. * @return \Cake\Database\Schema\TableSchema the altered schema
  501. */
  502. protected function _initializeSchema(TableSchema $schema): TableSchema
  503. {
  504. return $schema;
  505. }
  506. /**
  507. * Test to see if a Table has a specific field/column.
  508. *
  509. * Delegates to the schema object and checks for column presence
  510. * using the Schema\Table instance.
  511. *
  512. * @param string $field The field to check for.
  513. * @return bool True if the field exists, false if it does not.
  514. */
  515. public function hasField(string $field): bool
  516. {
  517. $schema = $this->getSchema();
  518. return $schema->getColumn($field) !== null;
  519. }
  520. /**
  521. * Sets the primary key field name.
  522. *
  523. * @param string|array $key Sets a new name to be used as primary key
  524. * @return $this
  525. */
  526. public function setPrimaryKey($key)
  527. {
  528. $this->_primaryKey = $key;
  529. return $this;
  530. }
  531. /**
  532. * Returns the primary key field name.
  533. *
  534. * @return string|array
  535. */
  536. public function getPrimaryKey()
  537. {
  538. if ($this->_primaryKey === null) {
  539. $key = (array)$this->getSchema()->primaryKey();
  540. if (count($key) === 1) {
  541. $key = $key[0];
  542. }
  543. $this->_primaryKey = $key;
  544. }
  545. return $this->_primaryKey;
  546. }
  547. /**
  548. * Sets the display field.
  549. *
  550. * @param string|array $field Name to be used as display field.
  551. * @return $this
  552. */
  553. public function setDisplayField($field)
  554. {
  555. $this->_displayField = $field;
  556. return $this;
  557. }
  558. /**
  559. * Returns the display field.
  560. *
  561. * @return string|array
  562. */
  563. public function getDisplayField()
  564. {
  565. if ($this->_displayField === null) {
  566. $schema = $this->getSchema();
  567. $primary = (array)$this->getPrimaryKey();
  568. $this->_displayField = array_shift($primary);
  569. if ($schema->getColumn('title')) {
  570. $this->_displayField = 'title';
  571. }
  572. if ($schema->getColumn('name')) {
  573. $this->_displayField = 'name';
  574. }
  575. }
  576. return $this->_displayField;
  577. }
  578. /**
  579. * Returns the class used to hydrate rows for this table.
  580. *
  581. * @return string
  582. */
  583. public function getEntityClass(): string
  584. {
  585. if (!$this->_entityClass) {
  586. $default = Entity::class;
  587. $self = static::class;
  588. $parts = explode('\\', $self);
  589. if ($self === self::class || count($parts) < 3) {
  590. return $this->_entityClass = $default;
  591. }
  592. $alias = Inflector::classify(Inflector::underscore(substr(array_pop($parts), 0, -5)));
  593. $name = implode('\\', array_slice($parts, 0, -1)) . '\\Entity\\' . $alias;
  594. if (!class_exists($name)) {
  595. return $this->_entityClass = $default;
  596. }
  597. $class = App::className($name, 'Model/Entity');
  598. if (!$class) {
  599. throw new MissingEntityException([$name]);
  600. }
  601. $this->_entityClass = $class;
  602. }
  603. return $this->_entityClass;
  604. }
  605. /**
  606. * Sets the class used to hydrate rows for this table.
  607. *
  608. * @param string $name The name of the class to use
  609. * @throws \Cake\ORM\Exception\MissingEntityException when the entity class cannot be found
  610. * @return $this
  611. */
  612. public function setEntityClass(string $name)
  613. {
  614. $class = App::className($name, 'Model/Entity');
  615. if (!$class) {
  616. throw new MissingEntityException([$name]);
  617. }
  618. $this->_entityClass = $class;
  619. return $this;
  620. }
  621. /**
  622. * Add a behavior.
  623. *
  624. * Adds a behavior to this table's behavior collection. Behaviors
  625. * provide an easy way to create horizontally re-usable features
  626. * that can provide trait like functionality, and allow for events
  627. * to be listened to.
  628. *
  629. * Example:
  630. *
  631. * Load a behavior, with some settings.
  632. *
  633. * ```
  634. * $this->addBehavior('Tree', ['parent' => 'parentId']);
  635. * ```
  636. *
  637. * Behaviors are generally loaded during Table::initialize().
  638. *
  639. * @param string $name The name of the behavior. Can be a short class reference.
  640. * @param array $options The options for the behavior to use.
  641. * @return $this
  642. * @throws \RuntimeException If a behavior is being reloaded.
  643. * @see \Cake\ORM\Behavior
  644. */
  645. public function addBehavior(string $name, array $options = [])
  646. {
  647. $this->_behaviors->load($name, $options);
  648. return $this;
  649. }
  650. /**
  651. * Adds an array of behaviors to the table's behavior collection.
  652. *
  653. * Example:
  654. *
  655. * ```
  656. * $this->addBehaviors([
  657. * 'Timestamp',
  658. * 'Tree' => ['level' => 'level'],
  659. * ]);
  660. * ```
  661. *
  662. * @param array $behaviors All of the behaviors to load.
  663. * @return $this
  664. * @throws \RuntimeException If a behavior is being reloaded.
  665. */
  666. public function addBehaviors(array $behaviors)
  667. {
  668. foreach ($behaviors as $name => $options) {
  669. if (is_int($name)) {
  670. $name = $options;
  671. $options = [];
  672. }
  673. $this->addBehavior($name, $options);
  674. }
  675. return $this;
  676. }
  677. /**
  678. * Removes a behavior from this table's behavior registry.
  679. *
  680. * Example:
  681. *
  682. * Remove a behavior from this table.
  683. *
  684. * ```
  685. * $this->removeBehavior('Tree');
  686. * ```
  687. *
  688. * @param string $name The alias that the behavior was added with.
  689. * @return $this
  690. * @see \Cake\ORM\Behavior
  691. */
  692. public function removeBehavior(string $name)
  693. {
  694. $this->_behaviors->unload($name);
  695. return $this;
  696. }
  697. /**
  698. * Returns the behavior registry for this table.
  699. *
  700. * @return \Cake\ORM\BehaviorRegistry The BehaviorRegistry instance.
  701. */
  702. public function behaviors(): BehaviorRegistry
  703. {
  704. return $this->_behaviors;
  705. }
  706. /**
  707. * Get a behavior from the registry.
  708. *
  709. * @param string $name The behavior alias to get from the registry.
  710. * @return \Cake\ORM\Behavior
  711. * @throws \InvalidArgumentException If the behavior does not exist.
  712. */
  713. public function getBehavior(string $name): Behavior
  714. {
  715. /** @var \Cake\ORM\Behavior|null $behavior */
  716. $behavior = $this->_behaviors->get($name);
  717. if ($behavior === null) {
  718. throw new InvalidArgumentException(sprintf(
  719. 'The %s behavior is not defined on %s.',
  720. $name,
  721. static::class
  722. ));
  723. }
  724. return $behavior;
  725. }
  726. /**
  727. * Check if a behavior with the given alias has been loaded.
  728. *
  729. * @param string $name The behavior alias to check.
  730. * @return bool Whether or not the behavior exists.
  731. */
  732. public function hasBehavior(string $name): bool
  733. {
  734. return $this->_behaviors->has($name);
  735. }
  736. /**
  737. * Returns an association object configured for the specified alias.
  738. *
  739. * The name argument also supports dot syntax to access deeper associations.
  740. *
  741. * ```
  742. * $users = $this->getAssociation('Articles.Comments.Users');
  743. * ```
  744. *
  745. * Note that this method requires the association to be present or otherwise
  746. * throws an exception.
  747. * If you are not sure, use hasAssociation() before calling this method.
  748. *
  749. * @param string $name The alias used for the association.
  750. * @return \Cake\ORM\Association The association.
  751. * @throws \InvalidArgumentException
  752. */
  753. public function getAssociation(string $name): Association
  754. {
  755. $association = $this->findAssociation($name);
  756. if (!$association) {
  757. throw new InvalidArgumentException("The {$name} association is not defined on {$this->getAlias()}.");
  758. }
  759. return $association;
  760. }
  761. /**
  762. * Checks whether a specific association exists on this Table instance.
  763. *
  764. * The name argument also supports dot syntax to access deeper associations.
  765. *
  766. * ```
  767. * $hasUsers = $this->hasAssociation('Articles.Comments.Users');
  768. * ```
  769. *
  770. * @param string $name The alias used for the association.
  771. * @return bool
  772. */
  773. public function hasAssociation(string $name): bool
  774. {
  775. return $this->findAssociation($name) !== null;
  776. }
  777. /**
  778. * Returns an association object configured for the specified alias if any.
  779. *
  780. * The name argument also supports dot syntax to access deeper associations.
  781. *
  782. * ```
  783. * $users = $this->getAssociation('Articles.Comments.Users');
  784. * ```
  785. *
  786. * @param string $name The alias used for the association.
  787. * @return \Cake\ORM\Association|null Either the association or null.
  788. */
  789. protected function findAssociation(string $name): ?Association
  790. {
  791. if (strpos($name, '.') === false) {
  792. return $this->_associations->get($name);
  793. }
  794. [$name, $next] = array_pad(explode('.', $name, 2), 2, null);
  795. $result = $this->_associations->get($name);
  796. if ($result !== null && $next !== null) {
  797. $result = $result->getTarget()->getAssociation($next);
  798. }
  799. return $result;
  800. }
  801. /**
  802. * Get the associations collection for this table.
  803. *
  804. * @return \Cake\ORM\AssociationCollection|\Cake\ORM\Association[] The collection of association objects.
  805. */
  806. public function associations(): iterable
  807. {
  808. return $this->_associations;
  809. }
  810. /**
  811. * Setup multiple associations.
  812. *
  813. * It takes an array containing set of table names indexed by association type
  814. * as argument:
  815. *
  816. * ```
  817. * $this->Posts->addAssociations([
  818. * 'belongsTo' => [
  819. * 'Users' => ['className' => 'App\Model\Table\UsersTable']
  820. * ],
  821. * 'hasMany' => ['Comments'],
  822. * 'belongsToMany' => ['Tags']
  823. * ]);
  824. * ```
  825. *
  826. * Each association type accepts multiple associations where the keys
  827. * are the aliases, and the values are association config data. If numeric
  828. * keys are used the values will be treated as association aliases.
  829. *
  830. * @param array $params Set of associations to bind (indexed by association type)
  831. * @return $this
  832. * @see \Cake\ORM\Table::belongsTo()
  833. * @see \Cake\ORM\Table::hasOne()
  834. * @see \Cake\ORM\Table::hasMany()
  835. * @see \Cake\ORM\Table::belongsToMany()
  836. */
  837. public function addAssociations(array $params)
  838. {
  839. foreach ($params as $assocType => $tables) {
  840. foreach ($tables as $associated => $options) {
  841. if (is_numeric($associated)) {
  842. $associated = $options;
  843. $options = [];
  844. }
  845. $this->{$assocType}($associated, $options);
  846. }
  847. }
  848. return $this;
  849. }
  850. /**
  851. * Creates a new BelongsTo association between this table and a target
  852. * table. A "belongs to" association is a N-1 relationship where this table
  853. * is the N side, and where there is a single associated record in the target
  854. * table for each one in this table.
  855. *
  856. * Target table can be inferred by its name, which is provided in the
  857. * first argument, or you can either pass the to be instantiated or
  858. * an instance of it directly.
  859. *
  860. * The options array accept the following keys:
  861. *
  862. * - className: The class name of the target table object
  863. * - targetTable: An instance of a table object to be used as the target table
  864. * - foreignKey: The name of the field to use as foreign key, if false none
  865. * will be used
  866. * - conditions: array with a list of conditions to filter the join with
  867. * - joinType: The type of join to be used (e.g. INNER)
  868. * - strategy: The loading strategy to use. 'join' and 'select' are supported.
  869. * - finder: The finder method to use when loading records from this association.
  870. * Defaults to 'all'. When the strategy is 'join', only the fields, containments,
  871. * and where conditions will be used from the finder.
  872. *
  873. * This method will return the association object that was built.
  874. *
  875. * @param string $associated the alias for the target table. This is used to
  876. * uniquely identify the association
  877. * @param array $options list of options to configure the association definition
  878. * @return \Cake\ORM\Association\BelongsTo
  879. */
  880. public function belongsTo(string $associated, array $options = []): BelongsTo
  881. {
  882. $options += ['sourceTable' => $this];
  883. /** @var \Cake\ORM\Association\BelongsTo $association */
  884. $association = $this->_associations->load(BelongsTo::class, $associated, $options);
  885. return $association;
  886. }
  887. /**
  888. * Creates a new HasOne association between this table and a target
  889. * table. A "has one" association is a 1-1 relationship.
  890. *
  891. * Target table can be inferred by its name, which is provided in the
  892. * first argument, or you can either pass the class name to be instantiated or
  893. * an instance of it directly.
  894. *
  895. * The options array accept the following keys:
  896. *
  897. * - className: The class name of the target table object
  898. * - targetTable: An instance of a table object to be used as the target table
  899. * - foreignKey: The name of the field to use as foreign key, if false none
  900. * will be used
  901. * - dependent: Set to true if you want CakePHP to cascade deletes to the
  902. * associated table when an entity is removed on this table. The delete operation
  903. * on the associated table will not cascade further. To get recursive cascades enable
  904. * `cascadeCallbacks` as well. Set to false if you don't want CakePHP to remove
  905. * associated data, or when you are using database constraints.
  906. * - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on
  907. * cascaded deletes. If false the ORM will use deleteAll() to remove data.
  908. * When true records will be loaded and then deleted.
  909. * - conditions: array with a list of conditions to filter the join with
  910. * - joinType: The type of join to be used (e.g. LEFT)
  911. * - strategy: The loading strategy to use. 'join' and 'select' are supported.
  912. * - finder: The finder method to use when loading records from this association.
  913. * Defaults to 'all'. When the strategy is 'join', only the fields, containments,
  914. * and where conditions will be used from the finder.
  915. *
  916. * This method will return the association object that was built.
  917. *
  918. * @param string $associated the alias for the target table. This is used to
  919. * uniquely identify the association
  920. * @param array $options list of options to configure the association definition
  921. * @return \Cake\ORM\Association\HasOne
  922. */
  923. public function hasOne(string $associated, array $options = []): HasOne
  924. {
  925. $options += ['sourceTable' => $this];
  926. /** @var \Cake\ORM\Association\HasOne $association */
  927. $association = $this->_associations->load(HasOne::class, $associated, $options);
  928. return $association;
  929. }
  930. /**
  931. * Creates a new HasMany association between this table and a target
  932. * table. A "has many" association is a 1-N relationship.
  933. *
  934. * Target table can be inferred by its name, which is provided in the
  935. * first argument, or you can either pass the class name to be instantiated or
  936. * an instance of it directly.
  937. *
  938. * The options array accept the following keys:
  939. *
  940. * - className: The class name of the target table object
  941. * - targetTable: An instance of a table object to be used as the target table
  942. * - foreignKey: The name of the field to use as foreign key, if false none
  943. * will be used
  944. * - dependent: Set to true if you want CakePHP to cascade deletes to the
  945. * associated table when an entity is removed on this table. The delete operation
  946. * on the associated table will not cascade further. To get recursive cascades enable
  947. * `cascadeCallbacks` as well. Set to false if you don't want CakePHP to remove
  948. * associated data, or when you are using database constraints.
  949. * - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on
  950. * cascaded deletes. If false the ORM will use deleteAll() to remove data.
  951. * When true records will be loaded and then deleted.
  952. * - conditions: array with a list of conditions to filter the join with
  953. * - sort: The order in which results for this association should be returned
  954. * - saveStrategy: Either 'append' or 'replace'. When 'append' the current records
  955. * are appended to any records in the database. When 'replace' associated records
  956. * not in the current set will be removed. If the foreign key is a null able column
  957. * or if `dependent` is true records will be orphaned.
  958. * - strategy: The strategy to be used for selecting results Either 'select'
  959. * or 'subquery'. If subquery is selected the query used to return results
  960. * in the source table will be used as conditions for getting rows in the
  961. * target table.
  962. * - finder: The finder method to use when loading records from this association.
  963. * Defaults to 'all'.
  964. *
  965. * This method will return the association object that was built.
  966. *
  967. * @param string $associated the alias for the target table. This is used to
  968. * uniquely identify the association
  969. * @param array $options list of options to configure the association definition
  970. * @return \Cake\ORM\Association\HasMany
  971. */
  972. public function hasMany(string $associated, array $options = []): HasMany
  973. {
  974. $options += ['sourceTable' => $this];
  975. /** @var \Cake\ORM\Association\HasMany $association */
  976. $association = $this->_associations->load(HasMany::class, $associated, $options);
  977. return $association;
  978. }
  979. /**
  980. * Creates a new BelongsToMany association between this table and a target
  981. * table. A "belongs to many" association is a M-N relationship.
  982. *
  983. * Target table can be inferred by its name, which is provided in the
  984. * first argument, or you can either pass the class name to be instantiated or
  985. * an instance of it directly.
  986. *
  987. * The options array accept the following keys:
  988. *
  989. * - className: The class name of the target table object.
  990. * - targetTable: An instance of a table object to be used as the target table.
  991. * - foreignKey: The name of the field to use as foreign key.
  992. * - targetForeignKey: The name of the field to use as the target foreign key.
  993. * - joinTable: The name of the table representing the link between the two
  994. * - through: If you choose to use an already instantiated link table, set this
  995. * key to a configured Table instance containing associations to both the source
  996. * and target tables in this association.
  997. * - dependent: Set to false, if you do not want junction table records removed
  998. * when an owning record is removed.
  999. * - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on
  1000. * cascaded deletes. If false the ORM will use deleteAll() to remove data.
  1001. * When true join/junction table records will be loaded and then deleted.
  1002. * - conditions: array with a list of conditions to filter the join with.
  1003. * - sort: The order in which results for this association should be returned.
  1004. * - strategy: The strategy to be used for selecting results Either 'select'
  1005. * or 'subquery'. If subquery is selected the query used to return results
  1006. * in the source table will be used as conditions for getting rows in the
  1007. * target table.
  1008. * - saveStrategy: Either 'append' or 'replace'. Indicates the mode to be used
  1009. * for saving associated entities. The former will only create new links
  1010. * between both side of the relation and the latter will do a wipe and
  1011. * replace to create the links between the passed entities when saving.
  1012. * - strategy: The loading strategy to use. 'select' and 'subquery' are supported.
  1013. * - finder: The finder method to use when loading records from this association.
  1014. * Defaults to 'all'.
  1015. *
  1016. * This method will return the association object that was built.
  1017. *
  1018. * @param string $associated the alias for the target table. This is used to
  1019. * uniquely identify the association
  1020. * @param array $options list of options to configure the association definition
  1021. * @return \Cake\ORM\Association\BelongsToMany
  1022. */
  1023. public function belongsToMany(string $associated, array $options = []): BelongsToMany
  1024. {
  1025. $options += ['sourceTable' => $this];
  1026. /** @var \Cake\ORM\Association\BelongsToMany $association */
  1027. $association = $this->_associations->load(BelongsToMany::class, $associated, $options);
  1028. return $association;
  1029. }
  1030. /**
  1031. * Creates a new Query for this repository and applies some defaults based on the
  1032. * type of search that was selected.
  1033. *
  1034. * ### Model.beforeFind event
  1035. *
  1036. * Each find() will trigger a `Model.beforeFind` event for all attached
  1037. * listeners. Any listener can set a valid result set using $query
  1038. *
  1039. * By default, `$options` will recognize the following keys:
  1040. *
  1041. * - fields
  1042. * - conditions
  1043. * - order
  1044. * - limit
  1045. * - offset
  1046. * - page
  1047. * - group
  1048. * - having
  1049. * - contain
  1050. * - join
  1051. *
  1052. * ### Usage
  1053. *
  1054. * Using the options array:
  1055. *
  1056. * ```
  1057. * $query = $articles->find('all', [
  1058. * 'conditions' => ['published' => 1],
  1059. * 'limit' => 10,
  1060. * 'contain' => ['Users', 'Comments']
  1061. * ]);
  1062. * ```
  1063. *
  1064. * Using the builder interface:
  1065. *
  1066. * ```
  1067. * $query = $articles->find()
  1068. * ->where(['published' => 1])
  1069. * ->limit(10)
  1070. * ->contain(['Users', 'Comments']);
  1071. * ```
  1072. *
  1073. * ### Calling finders
  1074. *
  1075. * The find() method is the entry point for custom finder methods.
  1076. * You can invoke a finder by specifying the type:
  1077. *
  1078. * ```
  1079. * $query = $articles->find('published');
  1080. * ```
  1081. *
  1082. * Would invoke the `findPublished` method.
  1083. *
  1084. * @param string $type the type of query to perform
  1085. * @param array|\ArrayAccess $options An array that will be passed to Query::applyOptions()
  1086. * @return \Cake\ORM\Query The query builder
  1087. */
  1088. public function find(string $type = 'all', $options = []): Query
  1089. {
  1090. $query = $this->query();
  1091. $query->select();
  1092. return $this->callFinder($type, $query, $options);
  1093. }
  1094. /**
  1095. * Returns the query as passed.
  1096. *
  1097. * By default findAll() applies no conditions, you
  1098. * can override this method in subclasses to modify how `find('all')` works.
  1099. *
  1100. * @param \Cake\ORM\Query $query The query to find with
  1101. * @param array $options The options to use for the find
  1102. * @return \Cake\ORM\Query The query builder
  1103. */
  1104. public function findAll(Query $query, array $options): Query
  1105. {
  1106. return $query;
  1107. }
  1108. /**
  1109. * Sets up a query object so results appear as an indexed array, useful for any
  1110. * place where you would want a list such as for populating input select boxes.
  1111. *
  1112. * When calling this finder, the fields passed are used to determine what should
  1113. * be used as the array key, value and optionally what to group the results by.
  1114. * By default the primary key for the model is used for the key, and the display
  1115. * field as value.
  1116. *
  1117. * The results of this finder will be in the following form:
  1118. *
  1119. * ```
  1120. * [
  1121. * 1 => 'value for id 1',
  1122. * 2 => 'value for id 2',
  1123. * 4 => 'value for id 4'
  1124. * ]
  1125. * ```
  1126. *
  1127. * You can specify which property will be used as the key and which as value
  1128. * by using the `$options` array, when not specified, it will use the results
  1129. * of calling `primaryKey` and `displayField` respectively in this table:
  1130. *
  1131. * ```
  1132. * $table->find('list', [
  1133. * 'keyField' => 'name',
  1134. * 'valueField' => 'age'
  1135. * ]);
  1136. * ```
  1137. *
  1138. * Results can be put together in bigger groups when they share a property, you
  1139. * can customize the property to use for grouping by setting `groupField`:
  1140. *
  1141. * ```
  1142. * $table->find('list', [
  1143. * 'groupField' => 'category_id',
  1144. * ]);
  1145. * ```
  1146. *
  1147. * When using a `groupField` results will be returned in this format:
  1148. *
  1149. * ```
  1150. * [
  1151. * 'group_1' => [
  1152. * 1 => 'value for id 1',
  1153. * 2 => 'value for id 2',
  1154. * ]
  1155. * 'group_2' => [
  1156. * 4 => 'value for id 4'
  1157. * ]
  1158. * ]
  1159. * ```
  1160. *
  1161. * @param \Cake\ORM\Query $query The query to find with
  1162. * @param array $options The options for the find
  1163. * @return \Cake\ORM\Query The query builder
  1164. */
  1165. public function findList(Query $query, array $options): Query
  1166. {
  1167. $options += [
  1168. 'keyField' => $this->getPrimaryKey(),
  1169. 'valueField' => $this->getDisplayField(),
  1170. 'groupField' => null,
  1171. ];
  1172. if (!$query->clause('select') &&
  1173. !is_object($options['keyField']) &&
  1174. !is_object($options['valueField']) &&
  1175. !is_object($options['groupField'])
  1176. ) {
  1177. $fields = array_merge(
  1178. (array)$options['keyField'],
  1179. (array)$options['valueField'],
  1180. (array)$options['groupField']
  1181. );
  1182. $columns = $this->getSchema()->columns();
  1183. if (count($fields) === count(array_intersect($fields, $columns))) {
  1184. $query->select($fields);
  1185. }
  1186. }
  1187. $options = $this->_setFieldMatchers(
  1188. $options,
  1189. ['keyField', 'valueField', 'groupField']
  1190. );
  1191. return $query->formatResults(function ($results) use ($options) {
  1192. /** @var \Cake\Collection\CollectionInterface $results */
  1193. return $results->combine(
  1194. $options['keyField'],
  1195. $options['valueField'],
  1196. $options['groupField']
  1197. );
  1198. });
  1199. }
  1200. /**
  1201. * Results for this finder will be a nested array, and is appropriate if you want
  1202. * to use the parent_id field of your model data to build nested results.
  1203. *
  1204. * Values belonging to a parent row based on their parent_id value will be
  1205. * recursively nested inside the parent row values using the `children` property
  1206. *
  1207. * You can customize what fields are used for nesting results, by default the
  1208. * primary key and the `parent_id` fields are used. If you wish to change
  1209. * these defaults you need to provide the keys `keyField`, `parentField` or `nestingKey` in
  1210. * `$options`:
  1211. *
  1212. * ```
  1213. * $table->find('threaded', [
  1214. * 'keyField' => 'id',
  1215. * 'parentField' => 'ancestor_id'
  1216. * 'nestingKey' => 'children'
  1217. * ]);
  1218. * ```
  1219. *
  1220. * @param \Cake\ORM\Query $query The query to find with
  1221. * @param array $options The options to find with
  1222. * @return \Cake\ORM\Query The query builder
  1223. */
  1224. public function findThreaded(Query $query, array $options): Query
  1225. {
  1226. $options += [
  1227. 'keyField' => $this->getPrimaryKey(),
  1228. 'parentField' => 'parent_id',
  1229. 'nestingKey' => 'children',
  1230. ];
  1231. $options = $this->_setFieldMatchers($options, ['keyField', 'parentField']);
  1232. return $query->formatResults(function ($results) use ($options) {
  1233. /** @var \Cake\Collection\CollectionInterface $results */
  1234. return $results->nest($options['keyField'], $options['parentField'], $options['nestingKey']);
  1235. });
  1236. }
  1237. /**
  1238. * Out of an options array, check if the keys described in `$keys` are arrays
  1239. * and change the values for closures that will concatenate the each of the
  1240. * properties in the value array when passed a row.
  1241. *
  1242. * This is an auxiliary function used for result formatters that can accept
  1243. * composite keys when comparing values.
  1244. *
  1245. * @param array $options the original options passed to a finder
  1246. * @param string[] $keys the keys to check in $options to build matchers from
  1247. * the associated value
  1248. * @return array
  1249. */
  1250. protected function _setFieldMatchers(array $options, array $keys): array
  1251. {
  1252. foreach ($keys as $field) {
  1253. if (!is_array($options[$field])) {
  1254. continue;
  1255. }
  1256. if (count($options[$field]) === 1) {
  1257. $options[$field] = current($options[$field]);
  1258. continue;
  1259. }
  1260. $fields = $options[$field];
  1261. $options[$field] = function ($row) use ($fields) {
  1262. $matches = [];
  1263. foreach ($fields as $field) {
  1264. $matches[] = $row[$field];
  1265. }
  1266. return implode(';', $matches);
  1267. };
  1268. }
  1269. return $options;
  1270. }
  1271. /**
  1272. * {@inheritDoc}
  1273. *
  1274. * ### Usage
  1275. *
  1276. * Get an article and some relationships:
  1277. *
  1278. * ```
  1279. * $article = $articles->get(1, ['contain' => ['Users', 'Comments']]);
  1280. * ```
  1281. *
  1282. * @throws \Cake\Datasource\Exception\InvalidPrimaryKeyException When $primaryKey has an
  1283. * incorrect number of elements.
  1284. * @psalm-suppress InvalidReturnType
  1285. */
  1286. public function get($primaryKey, $options = []): EntityInterface
  1287. {
  1288. $key = (array)$this->getPrimaryKey();
  1289. $alias = $this->getAlias();
  1290. foreach ($key as $index => $keyname) {
  1291. $key[$index] = $alias . '.' . $keyname;
  1292. }
  1293. $primaryKey = (array)$primaryKey;
  1294. if (count($key) !== count($primaryKey)) {
  1295. $primaryKey = $primaryKey ?: [null];
  1296. $primaryKey = array_map(function ($key) {
  1297. return var_export($key, true);
  1298. }, $primaryKey);
  1299. throw new InvalidPrimaryKeyException(sprintf(
  1300. 'Record not found in table "%s" with primary key [%s]',
  1301. $this->getTable(),
  1302. implode(', ', $primaryKey)
  1303. ));
  1304. }
  1305. $conditions = array_combine($key, $primaryKey);
  1306. $cacheConfig = $options['cache'] ?? false;
  1307. $cacheKey = $options['key'] ?? false;
  1308. $finder = $options['finder'] ?? 'all';
  1309. unset($options['key'], $options['cache'], $options['finder']);
  1310. $query = $this->find($finder, $options)->where($conditions);
  1311. if ($cacheConfig) {
  1312. if (!$cacheKey) {
  1313. $cacheKey = sprintf(
  1314. 'get:%s.%s%s',
  1315. $this->getConnection()->configName(),
  1316. $this->getTable(),
  1317. json_encode($primaryKey)
  1318. );
  1319. }
  1320. $query->cache($cacheKey, $cacheConfig);
  1321. }
  1322. /** @psalm-suppress InvalidReturnStatement */
  1323. return $query->firstOrFail();
  1324. }
  1325. /**
  1326. * Handles the logic executing of a worker inside a transaction.
  1327. *
  1328. * @param callable $worker The worker that will run inside the transaction.
  1329. * @param bool $atomic Whether to execute the worker inside a database transaction.
  1330. * @return mixed
  1331. */
  1332. protected function _executeTransaction(callable $worker, bool $atomic = true)
  1333. {
  1334. if ($atomic) {
  1335. return $this->getConnection()->transactional(function () use ($worker) {
  1336. return $worker();
  1337. });
  1338. }
  1339. return $worker();
  1340. }
  1341. /**
  1342. * Checks if the caller would have executed a commit on a transaction.
  1343. *
  1344. * @param bool $atomic True if an atomic transaction was used.
  1345. * @param bool $primary True if a primary was used.
  1346. * @return bool Returns true if a transaction was committed.
  1347. */
  1348. protected function _transactionCommitted(bool $atomic, bool $primary): bool
  1349. {
  1350. return !$this->getConnection()->inTransaction() && ($atomic || ($primary && !$atomic));
  1351. }
  1352. /**
  1353. * Finds an existing record or creates a new one.
  1354. *
  1355. * A find() will be done to locate an existing record using the attributes
  1356. * defined in $search. If records matches the conditions, the first record
  1357. * will be returned.
  1358. *
  1359. * If no record can be found, a new entity will be created
  1360. * with the $search properties. If a callback is provided, it will be
  1361. * called allowing you to define additional default values. The new
  1362. * entity will be saved and returned.
  1363. *
  1364. * If your find conditions require custom order, associations or conditions, then the $search
  1365. * parameter can be a callable that takes the Query as the argument, or a \Cake\ORM\Query object passed
  1366. * as the $search parameter. Allowing you to customize the find results.
  1367. *
  1368. * ### Options
  1369. *
  1370. * The options array is passed to the save method with exception to the following keys:
  1371. *
  1372. * - atomic: Whether to execute the methods for find, save and callbacks inside a database
  1373. * transaction (default: true)
  1374. * - defaults: Whether to use the search criteria as default values for the new entity (default: true)
  1375. *
  1376. * @param array|callable|\Cake\ORM\Query $search The criteria to find existing
  1377. * records by. Note that when you pass a query object you'll have to use
  1378. * the 2nd arg of the method to modify the entity data before saving.
  1379. * @param callable|null $callback A callback that will be invoked for newly
  1380. * created entities. This callback will be called *before* the entity
  1381. * is persisted.
  1382. * @param array $options The options to use when saving.
  1383. * @return \Cake\Datasource\EntityInterface An entity.
  1384. */
  1385. public function findOrCreate($search, ?callable $callback = null, $options = []): EntityInterface
  1386. {
  1387. $options = new ArrayObject($options + [
  1388. 'atomic' => true,
  1389. 'defaults' => true,
  1390. ]);
  1391. $entity = $this->_executeTransaction(function () use ($search, $callback, $options) {
  1392. return $this->_processFindOrCreate($search, $callback, $options->getArrayCopy());
  1393. }, $options['atomic']);
  1394. if ($entity && $this->_transactionCommitted($options['atomic'], true)) {
  1395. $this->dispatchEvent('Model.afterSaveCommit', compact('entity', 'options'));
  1396. }
  1397. return $entity;
  1398. }
  1399. /**
  1400. * Performs the actual find and/or create of an entity based on the passed options.
  1401. *
  1402. * @param array|callable|\Cake\ORM\Query $search The criteria to find an existing record by, or a callable tha will
  1403. * customize the find query.
  1404. * @param callable|null $callback A callback that will be invoked for newly
  1405. * created entities. This callback will be called *before* the entity
  1406. * is persisted.
  1407. * @param array $options The options to use when saving.
  1408. * @return \Cake\Datasource\EntityInterface|array An entity.
  1409. * @throws \Cake\ORM\Exception\PersistenceFailedException
  1410. * @throws \InvalidArgumentException
  1411. */
  1412. protected function _processFindOrCreate($search, ?callable $callback = null, $options = [])
  1413. {
  1414. $query = $this->_getFindOrCreateQuery($search);
  1415. $row = $query->first();
  1416. if ($row !== null) {
  1417. return $row;
  1418. }
  1419. $entity = $this->newEmptyEntity();
  1420. if ($options['defaults'] && is_array($search)) {
  1421. $accessibleFields = array_combine(array_keys($search), array_fill(0, count($search), true));
  1422. $entity = $this->patchEntity($entity, $search, ['accessibleFields' => $accessibleFields]);
  1423. }
  1424. if ($callback !== null) {
  1425. $entity = $callback($entity) ?: $entity;
  1426. }
  1427. unset($options['defaults']);
  1428. $result = $this->save($entity, $options);
  1429. if ($result === false) {
  1430. throw new PersistenceFailedException($entity, ['findOrCreate']);
  1431. }
  1432. return $entity;
  1433. }
  1434. /**
  1435. * Gets the query object for findOrCreate().
  1436. *
  1437. * @param array|callable|\Cake\ORM\Query $search The criteria to find existing records by.
  1438. * @return \Cake\ORM\Query
  1439. */
  1440. protected function _getFindOrCreateQuery($search): Query
  1441. {
  1442. if (is_callable($search)) {
  1443. $query = $this->find();
  1444. $search($query);
  1445. } elseif (is_array($search)) {
  1446. $query = $this->find()->where($search);
  1447. } elseif ($search instanceof Query) {
  1448. $query = $search;
  1449. } else {
  1450. throw new InvalidArgumentException(sprintf(
  1451. 'Search criteria must be an array, callable or Query. Got "%s"',
  1452. getTypeName($search)
  1453. ));
  1454. }
  1455. return $query;
  1456. }
  1457. /**
  1458. * Creates a new Query instance for a table.
  1459. *
  1460. * @return \Cake\ORM\Query
  1461. */
  1462. public function query(): Query
  1463. {
  1464. return new Query($this->getConnection(), $this);
  1465. }
  1466. /**
  1467. * @inheritDoc
  1468. */
  1469. public function updateAll($fields, $conditions): int
  1470. {
  1471. $query = $this->query();
  1472. $query->update()
  1473. ->set($fields)
  1474. ->where($conditions);
  1475. $statement = $query->execute();
  1476. $statement->closeCursor();
  1477. return $statement->rowCount();
  1478. }
  1479. /**
  1480. * @inheritDoc
  1481. */
  1482. public function deleteAll($conditions): int
  1483. {
  1484. $query = $this->query()
  1485. ->delete()
  1486. ->where($conditions);
  1487. $statement = $query->execute();
  1488. $statement->closeCursor();
  1489. return $statement->rowCount();
  1490. }
  1491. /**
  1492. * @inheritDoc
  1493. */
  1494. public function exists($conditions): bool
  1495. {
  1496. return (bool)count(
  1497. $this->find('all')
  1498. ->select(['existing' => 1])
  1499. ->where($conditions)
  1500. ->limit(1)
  1501. ->disableHydration()
  1502. ->toArray()
  1503. );
  1504. }
  1505. /**
  1506. * {@inheritDoc}
  1507. *
  1508. * ### Options
  1509. *
  1510. * The options array accepts the following keys:
  1511. *
  1512. * - atomic: Whether to execute the save and callbacks inside a database
  1513. * transaction (default: true)
  1514. * - checkRules: Whether or not to check the rules on entity before saving, if the checking
  1515. * fails, it will abort the save operation. (default:true)
  1516. * - associated: If `true` it will save 1st level associated entities as they are found
  1517. * in the passed `$entity` whenever the property defined for the association
  1518. * is marked as dirty. If an array, it will be interpreted as the list of associations
  1519. * to be saved. It is possible to provide different options for saving on associated
  1520. * table objects using this key by making the custom options the array value.
  1521. * If `false` no associated records will be saved. (default: `true`)
  1522. * - checkExisting: Whether or not to check if the entity already exists, assuming that the
  1523. * entity is marked as not new, and the primary key has been set.
  1524. *
  1525. * ### Events
  1526. *
  1527. * When saving, this method will trigger four events:
  1528. *
  1529. * - Model.beforeRules: Will be triggered right before any rule checking is done
  1530. * for the passed entity if the `checkRules` key in $options is not set to false.
  1531. * Listeners will receive as arguments the entity, options array and the operation type.
  1532. * If the event is stopped the rules check result will be set to the result of the event itself.
  1533. * - Model.afterRules: Will be triggered right after the `checkRules()` method is
  1534. * called for the entity. Listeners will receive as arguments the entity,
  1535. * options array, the result of checking the rules and the operation type.
  1536. * If the event is stopped the checking result will be set to the result of
  1537. * the event itself.
  1538. * - Model.beforeSave: Will be triggered just before the list of fields to be
  1539. * persisted is calculated. It receives both the entity and the options as
  1540. * arguments. The options array is passed as an ArrayObject, so any changes in
  1541. * it will be reflected in every listener and remembered at the end of the event
  1542. * so it can be used for the rest of the save operation. Returning false in any
  1543. * of the listeners will abort the saving process. If the event is stopped
  1544. * using the event API, the event object's `result` property will be returned.
  1545. * This can be useful when having your own saving strategy implemented inside a
  1546. * listener.
  1547. * - Model.afterSave: Will be triggered after a successful insert or save,
  1548. * listeners will receive the entity and the options array as arguments. The type
  1549. * of operation performed (insert or update) can be determined by checking the
  1550. * entity's method `isNew`, true meaning an insert and false an update.
  1551. * - Model.afterSaveCommit: Will be triggered after the transaction is committed
  1552. * for atomic save, listeners will receive the entity and the options array
  1553. * as arguments.
  1554. *
  1555. * This method will determine whether the passed entity needs to be
  1556. * inserted or updated in the database. It does that by checking the `isNew`
  1557. * method on the entity. If the entity to be saved returns a non-empty value from
  1558. * its `errors()` method, it will not be saved.
  1559. *
  1560. * ### Saving on associated tables
  1561. *
  1562. * This method will by default persist entities belonging to associated tables,
  1563. * whenever a dirty property matching the name of the property name set for an
  1564. * association in this table. It is possible to control what associations will
  1565. * be saved and to pass additional option for saving them.
  1566. *
  1567. * ```
  1568. * // Only save the comments association
  1569. * $articles->save($entity, ['associated' => ['Comments']]);
  1570. *
  1571. * // Save the company, the employees and related addresses for each of them.
  1572. * // For employees do not check the entity rules
  1573. * $companies->save($entity, [
  1574. * 'associated' => [
  1575. * 'Employees' => [
  1576. * 'associated' => ['Addresses'],
  1577. * 'checkRules' => false
  1578. * ]
  1579. * ]
  1580. * ]);
  1581. *
  1582. * // Save no associations
  1583. * $articles->save($entity, ['associated' => false]);
  1584. * ```
  1585. *
  1586. * @param \Cake\Datasource\EntityInterface $entity
  1587. * @param array $options
  1588. * @return \Cake\Datasource\EntityInterface|false
  1589. * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction is aborted in the afterSave event.
  1590. */
  1591. public function save(EntityInterface $entity, $options = [])
  1592. {
  1593. if ($options instanceof SaveOptionsBuilder) {
  1594. $options = $options->toArray();
  1595. }
  1596. $options = new ArrayObject((array)$options + [
  1597. 'atomic' => true,
  1598. 'associated' => true,
  1599. 'checkRules' => true,
  1600. 'checkExisting' => true,
  1601. '_primary' => true,
  1602. ]);
  1603. if ($entity->hasErrors((bool)$options['associated'])) {
  1604. return false;
  1605. }
  1606. if ($entity->isNew() === false && !$entity->isDirty()) {
  1607. return $entity;
  1608. }
  1609. $success = $this->_executeTransaction(function () use ($entity, $options) {
  1610. return $this->_processSave($entity, $options);
  1611. }, $options['atomic']);
  1612. if ($success) {
  1613. if ($this->_transactionCommitted($options['atomic'], $options['_primary'])) {
  1614. $this->dispatchEvent('Model.afterSaveCommit', compact('entity', 'options'));
  1615. }
  1616. if ($options['atomic'] || $options['_primary']) {
  1617. $entity->clean();
  1618. $entity->isNew(false);
  1619. $entity->setSource($this->getRegistryAlias());
  1620. }
  1621. }
  1622. return $success;
  1623. }
  1624. /**
  1625. * Try to save an entity or throw a PersistenceFailedException if the application rules checks failed,
  1626. * the entity contains errors or the save was aborted by a callback.
  1627. *
  1628. * @param \Cake\Datasource\EntityInterface $entity the entity to be saved
  1629. * @param array|\ArrayAccess $options The options to use when saving.
  1630. * @return \Cake\Datasource\EntityInterface
  1631. * @throws \Cake\ORM\Exception\PersistenceFailedException When the entity couldn't be saved
  1632. * @see \Cake\ORM\Table::save()
  1633. */
  1634. public function saveOrFail(EntityInterface $entity, $options = []): EntityInterface
  1635. {
  1636. $saved = $this->save($entity, $options);
  1637. if ($saved === false) {
  1638. throw new PersistenceFailedException($entity, ['save']);
  1639. }
  1640. return $saved;
  1641. }
  1642. /**
  1643. * Performs the actual saving of an entity based on the passed options.
  1644. *
  1645. * @param \Cake\Datasource\EntityInterface $entity the entity to be saved
  1646. * @param \ArrayObject $options the options to use for the save operation
  1647. * @return \Cake\Datasource\EntityInterface|bool
  1648. * @throws \RuntimeException When an entity is missing some of the primary keys.
  1649. * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction
  1650. * is aborted in the afterSave event.
  1651. */
  1652. protected function _processSave(EntityInterface $entity, ArrayObject $options)
  1653. {
  1654. $primaryColumns = (array)$this->getPrimaryKey();
  1655. if ($options['checkExisting'] && $primaryColumns && $entity->isNew() && $entity->has($primaryColumns)) {
  1656. $alias = $this->getAlias();
  1657. $conditions = [];
  1658. foreach ($entity->extract($primaryColumns) as $k => $v) {
  1659. $conditions["$alias.$k"] = $v;
  1660. }
  1661. $entity->isNew(!$this->exists($conditions));
  1662. }
  1663. $mode = $entity->isNew() ? RulesChecker::CREATE : RulesChecker::UPDATE;
  1664. if ($options['checkRules'] && !$this->checkRules($entity, $mode, $options)) {
  1665. return false;
  1666. }
  1667. $options['associated'] = $this->_associations->normalizeKeys($options['associated']);
  1668. $event = $this->dispatchEvent('Model.beforeSave', compact('entity', 'options'));
  1669. if ($event->isStopped()) {
  1670. return $event->getResult();
  1671. }
  1672. $saved = $this->_associations->saveParents(
  1673. $this,
  1674. $entity,
  1675. $options['associated'],
  1676. ['_primary' => false] + $options->getArrayCopy()
  1677. );
  1678. if (!$saved && $options['atomic']) {
  1679. return false;
  1680. }
  1681. $data = $entity->extract($this->getSchema()->columns(), true);
  1682. $isNew = $entity->isNew();
  1683. if ($isNew) {
  1684. $success = $this->_insert($entity, $data);
  1685. } else {
  1686. $success = $this->_update($entity, $data);
  1687. }
  1688. if ($success) {
  1689. $success = $this->_onSaveSuccess($entity, $options);
  1690. }
  1691. if (!$success && $isNew) {
  1692. $entity->unset($this->getPrimaryKey());
  1693. $entity->isNew(true);
  1694. }
  1695. return $success ? $entity : false;
  1696. }
  1697. /**
  1698. * Handles the saving of children associations and executing the afterSave logic
  1699. * once the entity for this table has been saved successfully.
  1700. *
  1701. * @param \Cake\Datasource\EntityInterface $entity the entity to be saved
  1702. * @param \ArrayObject $options the options to use for the save operation
  1703. * @return bool True on success
  1704. * @throws \Cake\ORM\Exception\RolledbackTransactionException If the transaction
  1705. * is aborted in the afterSave event.
  1706. */
  1707. protected function _onSaveSuccess(EntityInterface $entity, ArrayObject $options): bool
  1708. {
  1709. $success = $this->_associations->saveChildren(
  1710. $this,
  1711. $entity,
  1712. $options['associated'],
  1713. ['_primary' => false] + $options->getArrayCopy()
  1714. );
  1715. if (!$success && $options['atomic']) {
  1716. return false;
  1717. }
  1718. $this->dispatchEvent('Model.afterSave', compact('entity', 'options'));
  1719. if ($options['atomic'] && !$this->getConnection()->inTransaction()) {
  1720. throw new RolledbackTransactionException(['table' => static::class]);
  1721. }
  1722. if (!$options['atomic'] && !$options['_primary']) {
  1723. $entity->clean();
  1724. $entity->isNew(false);
  1725. $entity->setSource($this->getRegistryAlias());
  1726. }
  1727. return true;
  1728. }
  1729. /**
  1730. * Auxiliary function to handle the insert of an entity's data in the table
  1731. *
  1732. * @param \Cake\Datasource\EntityInterface $entity the subject entity from were $data was extracted
  1733. * @param array $data The actual data that needs to be saved
  1734. * @return \Cake\Datasource\EntityInterface|bool
  1735. * @throws \RuntimeException if not all the primary keys where supplied or could
  1736. * be generated when the table has composite primary keys. Or when the table has no primary key.
  1737. */
  1738. protected function _insert(EntityInterface $entity, array $data)
  1739. {
  1740. $primary = (array)$this->getPrimaryKey();
  1741. if (empty($primary)) {
  1742. $msg = sprintf(
  1743. 'Cannot insert row in "%s" table, it has no primary key.',
  1744. $this->getTable()
  1745. );
  1746. throw new RuntimeException($msg);
  1747. }
  1748. $keys = array_fill(0, count($primary), null);
  1749. $id = (array)$this->_newId($primary) + $keys;
  1750. // Generate primary keys preferring values in $data.
  1751. $primary = array_combine($primary, $id);
  1752. $primary = array_intersect_key($data, $primary) + $primary;
  1753. $filteredKeys = array_filter($primary, function ($v) {
  1754. return $v !== null;
  1755. });
  1756. $data += $filteredKeys;
  1757. if (count($primary) > 1) {
  1758. $schema = $this->getSchema();
  1759. foreach ($primary as $k => $v) {
  1760. if (!isset($data[$k]) && empty($schema->getColumn($k)['autoIncrement'])) {
  1761. $msg = 'Cannot insert row, some of the primary key values are missing. ';
  1762. $msg .= sprintf(
  1763. 'Got (%s), expecting (%s)',
  1764. implode(', ', $filteredKeys + $entity->extract(array_keys($primary))),
  1765. implode(', ', array_keys($primary))
  1766. );
  1767. throw new RuntimeException($msg);
  1768. }
  1769. }
  1770. }
  1771. $success = false;
  1772. if (empty($data)) {
  1773. return $success;
  1774. }
  1775. $statement = $this->query()->insert(array_keys($data))
  1776. ->values($data)
  1777. ->execute();
  1778. if ($statement->rowCount() !== 0) {
  1779. $success = $entity;
  1780. $entity->set($filteredKeys, ['guard' => false]);
  1781. $schema = $this->getSchema();
  1782. $driver = $this->getConnection()->getDriver();
  1783. foreach ($primary as $key => $v) {
  1784. if (!isset($data[$key])) {
  1785. $id = $statement->lastInsertId($this->getTable(), $key);
  1786. $type = $schema->getColumnType($key);
  1787. $entity->set($key, TypeFactory::build($type)->toPHP($id, $driver));
  1788. break;
  1789. }
  1790. }
  1791. }
  1792. $statement->closeCursor();
  1793. return $success;
  1794. }
  1795. /**
  1796. * Generate a primary key value for a new record.
  1797. *
  1798. * By default, this uses the type system to generate a new primary key
  1799. * value if possible. You can override this method if you have specific requirements
  1800. * for id generation.
  1801. *
  1802. * Note: The ORM will not generate primary key values for composite primary keys.
  1803. * You can overwrite _newId() in your table class.
  1804. *
  1805. * @param array $primary The primary key columns to get a new ID for.
  1806. * @return null|string|array Either null or the primary key value or a list of primary key values.
  1807. */
  1808. protected function _newId(array $primary)
  1809. {
  1810. if (!$primary || count((array)$primary) > 1) {
  1811. return null;
  1812. }
  1813. $typeName = $this->getSchema()->getColumnType($primary[0]);
  1814. $type = TypeFactory::build($typeName);
  1815. return $type->newId();
  1816. }
  1817. /**
  1818. * Auxiliary function to handle the update of an entity's data in the table
  1819. *
  1820. * @param \Cake\Datasource\EntityInterface $entity the subject entity from were $data was extracted
  1821. * @param array $data The actual data that needs to be saved
  1822. * @return \Cake\Datasource\EntityInterface|bool
  1823. * @throws \InvalidArgumentException When primary key data is missing.
  1824. */
  1825. protected function _update(EntityInterface $entity, array $data)
  1826. {
  1827. $primaryColumns = (array)$this->getPrimaryKey();
  1828. $primaryKey = $entity->extract($primaryColumns);
  1829. $data = array_diff_key($data, $primaryKey);
  1830. if (empty($data)) {
  1831. return $entity;
  1832. }
  1833. if (count($primaryColumns) === 0) {
  1834. $entityClass = get_class($entity);
  1835. $table = $this->getTable();
  1836. $message = "Cannot update `$entityClass`. The `$table` has no primary key.";
  1837. throw new InvalidArgumentException($message);
  1838. }
  1839. if (!$entity->has($primaryColumns)) {
  1840. $message = 'All primary key value(s) are needed for updating, ';
  1841. $message .= get_class($entity) . ' is missing ' . implode(', ', $primaryColumns);
  1842. throw new InvalidArgumentException($message);
  1843. }
  1844. $query = $this->query();
  1845. $statement = $query->update()
  1846. ->set($data)
  1847. ->where($primaryKey)
  1848. ->execute();
  1849. $success = false;
  1850. if ($statement->errorCode() === '00000') {
  1851. $success = $entity;
  1852. }
  1853. $statement->closeCursor();
  1854. return $success;
  1855. }
  1856. /**
  1857. * Persists multiple entities of a table.
  1858. *
  1859. * The records will be saved in a transaction which will be rolled back if
  1860. * any one of the records fails to save due to failed validation or database
  1861. * error.
  1862. *
  1863. * @param \Cake\Datasource\EntityInterface[]|\Cake\Datasource\ResultSetInterface $entities Entities to save.
  1864. * @param array|\ArrayAccess $options Options used when calling Table::save() for each entity.
  1865. * @return bool|\Cake\Datasource\EntityInterface[]|\Cake\Datasource\ResultSetInterface False on failure, entities list on success.
  1866. * @throws \Exception
  1867. */
  1868. public function saveMany(iterable $entities, $options = [])
  1869. {
  1870. /** @var bool[] $isNew */
  1871. $isNew = [];
  1872. $cleanup = function ($entities) use (&$isNew): void {
  1873. /** @var \Cake\Datasource\EntityInterface[] $entities */
  1874. foreach ($entities as $key => $entity) {
  1875. if (isset($isNew[$key]) && $isNew[$key]) {
  1876. $entity->unset($this->getPrimaryKey());
  1877. $entity->isNew(true);
  1878. }
  1879. }
  1880. };
  1881. try {
  1882. $return = $this->getConnection()
  1883. ->transactional(function () use ($entities, $options, &$isNew) {
  1884. foreach ($entities as $key => $entity) {
  1885. $isNew[$key] = $entity->isNew();
  1886. if ($this->save($entity, $options) === false) {
  1887. return false;
  1888. }
  1889. }
  1890. });
  1891. } catch (Exception $e) {
  1892. $cleanup($entities);
  1893. throw $e;
  1894. }
  1895. if ($return === false) {
  1896. $cleanup($entities);
  1897. return false;
  1898. }
  1899. return $entities;
  1900. }
  1901. /**
  1902. * {@inheritDoc}
  1903. *
  1904. * For HasMany and HasOne associations records will be removed based on
  1905. * the dependent option. Join table records in BelongsToMany associations
  1906. * will always be removed. You can use the `cascadeCallbacks` option
  1907. * when defining associations to change how associated data is deleted.
  1908. *
  1909. * ### Options
  1910. *
  1911. * - `atomic` Defaults to true. When true the deletion happens within a transaction.
  1912. * - `checkRules` Defaults to true. Check deletion rules before deleting the record.
  1913. *
  1914. * ### Events
  1915. *
  1916. * - `Model.beforeDelete` Fired before the delete occurs. If stopped the delete
  1917. * will be aborted. Receives the event, entity, and options.
  1918. * - `Model.afterDelete` Fired after the delete has been successful. Receives
  1919. * the event, entity, and options.
  1920. * - `Model.afterDeleteCommit` Fired after the transaction is committed for
  1921. * an atomic delete. Receives the event, entity, and options.
  1922. *
  1923. * The options argument will be converted into an \ArrayObject instance
  1924. * for the duration of the callbacks, this allows listeners to modify
  1925. * the options used in the delete operation.
  1926. *
  1927. */
  1928. public function delete(EntityInterface $entity, $options = []): bool
  1929. {
  1930. $options = new ArrayObject((array)$options + [
  1931. 'atomic' => true,
  1932. 'checkRules' => true,
  1933. '_primary' => true,
  1934. ]);
  1935. $success = $this->_executeTransaction(function () use ($entity, $options) {
  1936. return $this->_processDelete($entity, $options);
  1937. }, $options['atomic']);
  1938. if ($success && $this->_transactionCommitted($options['atomic'], $options['_primary'])) {
  1939. $this->dispatchEvent('Model.afterDeleteCommit', [
  1940. 'entity' => $entity,
  1941. 'options' => $options,
  1942. ]);
  1943. }
  1944. return $success;
  1945. }
  1946. /**
  1947. * Try to delete an entity or throw a PersistenceFailedException if the entity is new,
  1948. * has no primary key value, application rules checks failed or the delete was aborted by a callback.
  1949. *
  1950. * @param \Cake\Datasource\EntityInterface $entity The entity to remove.
  1951. * @param array|\ArrayAccess $options The options for the delete.
  1952. * @return bool success
  1953. * @throws \Cake\ORM\Exception\PersistenceFailedException
  1954. * @see \Cake\ORM\Table::delete()
  1955. */
  1956. public function deleteOrFail(EntityInterface $entity, $options = []): bool
  1957. {
  1958. $deleted = $this->delete($entity, $options);
  1959. if ($deleted === false) {
  1960. throw new PersistenceFailedException($entity, ['delete']);
  1961. }
  1962. return $deleted;
  1963. }
  1964. /**
  1965. * Perform the delete operation.
  1966. *
  1967. * Will delete the entity provided. Will remove rows from any
  1968. * dependent associations, and clear out join tables for BelongsToMany associations.
  1969. *
  1970. * @param \Cake\Datasource\EntityInterface $entity The entity to delete.
  1971. * @param \ArrayObject $options The options for the delete.
  1972. * @throws \InvalidArgumentException if there are no primary key values of the
  1973. * passed entity
  1974. * @return bool success
  1975. */
  1976. protected function _processDelete(EntityInterface $entity, ArrayObject $options): bool
  1977. {
  1978. if ($entity->isNew()) {
  1979. return false;
  1980. }
  1981. $primaryKey = (array)$this->getPrimaryKey();
  1982. if (!$entity->has($primaryKey)) {
  1983. $msg = 'Deleting requires all primary key values.';
  1984. throw new InvalidArgumentException($msg);
  1985. }
  1986. if ($options['checkRules'] && !$this->checkRules($entity, RulesChecker::DELETE, $options)) {
  1987. return false;
  1988. }
  1989. $event = $this->dispatchEvent('Model.beforeDelete', [
  1990. 'entity' => $entity,
  1991. 'options' => $options,
  1992. ]);
  1993. if ($event->isStopped()) {
  1994. return (bool)$event->getResult();
  1995. }
  1996. $this->_associations->cascadeDelete(
  1997. $entity,
  1998. ['_primary' => false] + $options->getArrayCopy()
  1999. );
  2000. $query = $this->query();
  2001. $conditions = (array)$entity->extract($primaryKey);
  2002. $statement = $query->delete()
  2003. ->where($conditions)
  2004. ->execute();
  2005. $success = $statement->rowCount() > 0;
  2006. if (!$success) {
  2007. return $success;
  2008. }
  2009. $this->dispatchEvent('Model.afterDelete', [
  2010. 'entity' => $entity,
  2011. 'options' => $options,
  2012. ]);
  2013. return $success;
  2014. }
  2015. /**
  2016. * Returns true if the finder exists for the table
  2017. *
  2018. * @param string $type name of finder to check
  2019. *
  2020. * @return bool
  2021. */
  2022. public function hasFinder(string $type): bool
  2023. {
  2024. $finder = 'find' . $type;
  2025. return method_exists($this, $finder) || $this->_behaviors->hasFinder($type);
  2026. }
  2027. /**
  2028. * Calls a finder method directly and applies it to the passed query,
  2029. * if no query is passed a new one will be created and returned
  2030. *
  2031. * @param string $type name of the finder to be called
  2032. * @param \Cake\ORM\Query $query The query object to apply the finder options to
  2033. * @param array $options List of options to pass to the finder
  2034. * @return \Cake\ORM\Query
  2035. * @throws \BadMethodCallException
  2036. */
  2037. public function callFinder(string $type, Query $query, array $options = []): Query
  2038. {
  2039. $query->applyOptions($options);
  2040. $options = $query->getOptions();
  2041. $finder = 'find' . $type;
  2042. if (method_exists($this, $finder)) {
  2043. return $this->{$finder}($query, $options);
  2044. }
  2045. if ($this->_behaviors->hasFinder($type)) {
  2046. return $this->_behaviors->callFinder($type, [$query, $options]);
  2047. }
  2048. throw new BadMethodCallException(sprintf(
  2049. 'Unknown finder method "%s" on %s.',
  2050. $type,
  2051. static::class
  2052. ));
  2053. }
  2054. /**
  2055. * Provides the dynamic findBy and findByAll methods.
  2056. *
  2057. * @param string $method The method name that was fired.
  2058. * @param array $args List of arguments passed to the function.
  2059. * @return \Cake\ORM\Query
  2060. * @throws \BadMethodCallException when there are missing arguments, or when
  2061. * and & or are combined.
  2062. */
  2063. protected function _dynamicFinder(string $method, array $args)
  2064. {
  2065. $method = Inflector::underscore($method);
  2066. preg_match('/^find_([\w]+)_by_/', $method, $matches);
  2067. if (empty($matches)) {
  2068. // find_by_ is 8 characters.
  2069. $fields = substr($method, 8);
  2070. $findType = 'all';
  2071. } else {
  2072. $fields = substr($method, strlen($matches[0]));
  2073. $findType = Inflector::variable($matches[1]);
  2074. }
  2075. $hasOr = strpos($fields, '_or_');
  2076. $hasAnd = strpos($fields, '_and_');
  2077. $makeConditions = function ($fields, $args) {
  2078. $conditions = [];
  2079. if (count($args) < count($fields)) {
  2080. throw new BadMethodCallException(sprintf(
  2081. 'Not enough arguments for magic finder. Got %s required %s',
  2082. count($args),
  2083. count($fields)
  2084. ));
  2085. }
  2086. foreach ($fields as $field) {
  2087. $conditions[$this->aliasField($field)] = array_shift($args);
  2088. }
  2089. return $conditions;
  2090. };
  2091. if ($hasOr !== false && $hasAnd !== false) {
  2092. throw new BadMethodCallException(
  2093. 'Cannot mix "and" & "or" in a magic finder. Use find() instead.'
  2094. );
  2095. }
  2096. $conditions = [];
  2097. if ($hasOr === false && $hasAnd === false) {
  2098. $conditions = $makeConditions([$fields], $args);
  2099. } elseif ($hasOr !== false) {
  2100. $fields = explode('_or_', $fields);
  2101. $conditions = [
  2102. 'OR' => $makeConditions($fields, $args),
  2103. ];
  2104. } elseif ($hasAnd !== false) {
  2105. $fields = explode('_and_', $fields);
  2106. $conditions = $makeConditions($fields, $args);
  2107. }
  2108. return $this->find($findType, [
  2109. 'conditions' => $conditions,
  2110. ]);
  2111. }
  2112. /**
  2113. * Handles behavior delegation + dynamic finders.
  2114. *
  2115. * If your Table uses any behaviors you can call them as if
  2116. * they were on the table object.
  2117. *
  2118. * @param string $method name of the method to be invoked
  2119. * @param array $args List of arguments passed to the function
  2120. * @return mixed
  2121. * @throws \BadMethodCallException
  2122. */
  2123. public function __call($method, $args)
  2124. {
  2125. if ($this->_behaviors->hasMethod($method)) {
  2126. return $this->_behaviors->call($method, $args);
  2127. }
  2128. if (preg_match('/^find(?:\w+)?By/', $method) > 0) {
  2129. return $this->_dynamicFinder($method, $args);
  2130. }
  2131. throw new BadMethodCallException(
  2132. sprintf('Unknown method "%s" called on %s', $method, static::class)
  2133. );
  2134. }
  2135. /**
  2136. * Returns the association named after the passed value if exists, otherwise
  2137. * throws an exception.
  2138. *
  2139. * @param string $property the association name
  2140. * @return \Cake\ORM\Association
  2141. * @throws \RuntimeException if no association with such name exists
  2142. */
  2143. public function __get($property)
  2144. {
  2145. $association = $this->_associations->get($property);
  2146. if (!$association) {
  2147. throw new RuntimeException(sprintf(
  2148. 'Table "%s" is not associated with "%s"',
  2149. static::class,
  2150. $property
  2151. ));
  2152. }
  2153. return $association;
  2154. }
  2155. /**
  2156. * Returns whether an association named after the passed value
  2157. * exists for this table.
  2158. *
  2159. * @param string $property the association name
  2160. * @return bool
  2161. */
  2162. public function __isset($property)
  2163. {
  2164. return $this->_associations->has($property);
  2165. }
  2166. /**
  2167. * Get the object used to marshal/convert array data into objects.
  2168. *
  2169. * Override this method if you want a table object to use custom
  2170. * marshalling logic.
  2171. *
  2172. * @return \Cake\ORM\Marshaller
  2173. * @see \Cake\ORM\Marshaller
  2174. */
  2175. public function marshaller(): Marshaller
  2176. {
  2177. return new Marshaller($this);
  2178. }
  2179. /**
  2180. * {@inheritDoc}
  2181. *
  2182. * @return \Cake\Datasource\EntityInterface
  2183. */
  2184. public function newEmptyEntity(): EntityInterface
  2185. {
  2186. $class = $this->getEntityClass();
  2187. return new $class([], ['source' => $this->getRegistryAlias()]);
  2188. }
  2189. /**
  2190. * {@inheritDoc}
  2191. *
  2192. * By default all the associations on this table will be hydrated. You can
  2193. * limit which associations are built, or include deeper associations
  2194. * using the options parameter:
  2195. *
  2196. * ```
  2197. * $article = $this->Articles->newEntity(
  2198. * $this->request->getData(),
  2199. * ['associated' => ['Tags', 'Comments.Users']]
  2200. * );
  2201. * ```
  2202. *
  2203. * You can limit fields that will be present in the constructed entity by
  2204. * passing the `fields` option, which is also accepted for associations:
  2205. *
  2206. * ```
  2207. * $article = $this->Articles->newEntity($this->request->getData(), [
  2208. * 'fields' => ['title', 'body', 'tags', 'comments'],
  2209. * 'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
  2210. * ]
  2211. * );
  2212. * ```
  2213. *
  2214. * The `fields` option lets remove or restrict input data from ending up in
  2215. * the entity. If you'd like to relax the entity's default accessible fields,
  2216. * you can use the `accessibleFields` option:
  2217. *
  2218. * ```
  2219. * $article = $this->Articles->newEntity(
  2220. * $this->request->getData(),
  2221. * ['accessibleFields' => ['protected_field' => true]]
  2222. * );
  2223. * ```
  2224. *
  2225. * By default, the data is validated before being passed to the new entity. In
  2226. * the case of invalid fields, those will not be present in the resulting object.
  2227. * The `validate` option can be used to disable validation on the passed data:
  2228. *
  2229. * ```
  2230. * $article = $this->Articles->newEntity(
  2231. * $this->request->getData(),
  2232. * ['validate' => false]
  2233. * );
  2234. * ```
  2235. *
  2236. * You can also pass the name of the validator to use in the `validate` option.
  2237. * If `null` is passed to the first param of this function, no validation will
  2238. * be performed.
  2239. *
  2240. * You can use the `Model.beforeMarshal` event to modify request data
  2241. * before it is converted into entities.
  2242. */
  2243. public function newEntity(array $data, array $options = []): EntityInterface
  2244. {
  2245. if (!isset($options['associated'])) {
  2246. $options['associated'] = $this->_associations->keys();
  2247. }
  2248. $marshaller = $this->marshaller();
  2249. return $marshaller->one($data, $options);
  2250. }
  2251. /**
  2252. * {@inheritDoc}
  2253. *
  2254. * By default all the associations on this table will be hydrated. You can
  2255. * limit which associations are built, or include deeper associations
  2256. * using the options parameter:
  2257. *
  2258. * ```
  2259. * $articles = $this->Articles->newEntities(
  2260. * $this->request->getData(),
  2261. * ['associated' => ['Tags', 'Comments.Users']]
  2262. * );
  2263. * ```
  2264. *
  2265. * You can limit fields that will be present in the constructed entities by
  2266. * passing the `fields` option, which is also accepted for associations:
  2267. *
  2268. * ```
  2269. * $articles = $this->Articles->newEntities($this->request->getData(), [
  2270. * 'fields' => ['title', 'body', 'tags', 'comments'],
  2271. * 'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
  2272. * ]
  2273. * );
  2274. * ```
  2275. *
  2276. * You can use the `Model.beforeMarshal` event to modify request data
  2277. * before it is converted into entities.
  2278. */
  2279. public function newEntities(array $data, array $options = []): array
  2280. {
  2281. if (!isset($options['associated'])) {
  2282. $options['associated'] = $this->_associations->keys();
  2283. }
  2284. $marshaller = $this->marshaller();
  2285. return $marshaller->many($data, $options);
  2286. }
  2287. /**
  2288. * {@inheritDoc}
  2289. *
  2290. * When merging HasMany or BelongsToMany associations, all the entities in the
  2291. * `$data` array will appear, those that can be matched by primary key will get
  2292. * the data merged, but those that cannot, will be discarded.
  2293. *
  2294. * You can limit fields that will be present in the merged entity by
  2295. * passing the `fields` option, which is also accepted for associations:
  2296. *
  2297. * ```
  2298. * $article = $this->Articles->patchEntity($article, $this->request->getData(), [
  2299. * 'fields' => ['title', 'body', 'tags', 'comments'],
  2300. * 'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
  2301. * ]
  2302. * );
  2303. * ```
  2304. *
  2305. * By default, the data is validated before being passed to the entity. In
  2306. * the case of invalid fields, those will not be assigned to the entity.
  2307. * The `validate` option can be used to disable validation on the passed data:
  2308. *
  2309. * ```
  2310. * $article = $this->patchEntity($article, $this->request->getData(),[
  2311. * 'validate' => false
  2312. * ]);
  2313. * ```
  2314. *
  2315. * You can use the `Model.beforeMarshal` event to modify request data
  2316. * before it is converted into entities.
  2317. *
  2318. * When patching scalar values (null/booleans/string/integer/float), if the property
  2319. * presently has an identical value, the setter will not be called, and the
  2320. * property will not be marked as dirty. This is an optimization to prevent unnecessary field
  2321. * updates when persisting entities.
  2322. */
  2323. public function patchEntity(EntityInterface $entity, array $data, array $options = []): EntityInterface
  2324. {
  2325. if (!isset($options['associated'])) {
  2326. $options['associated'] = $this->_associations->keys();
  2327. }
  2328. $marshaller = $this->marshaller();
  2329. return $marshaller->merge($entity, $data, $options);
  2330. }
  2331. /**
  2332. * {@inheritDoc}
  2333. *
  2334. * Those entries in `$entities` that cannot be matched to any record in
  2335. * `$data` will be discarded. Records in `$data` that could not be matched will
  2336. * be marshalled as a new entity.
  2337. *
  2338. * When merging HasMany or BelongsToMany associations, all the entities in the
  2339. * `$data` array will appear, those that can be matched by primary key will get
  2340. * the data merged, but those that cannot, will be discarded.
  2341. *
  2342. * You can limit fields that will be present in the merged entities by
  2343. * passing the `fields` option, which is also accepted for associations:
  2344. *
  2345. * ```
  2346. * $articles = $this->Articles->patchEntities($articles, $this->request->getData(), [
  2347. * 'fields' => ['title', 'body', 'tags', 'comments'],
  2348. * 'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
  2349. * ]
  2350. * );
  2351. * ```
  2352. *
  2353. * You can use the `Model.beforeMarshal` event to modify request data
  2354. * before it is converted into entities.
  2355. */
  2356. public function patchEntities(iterable $entities, array $data, array $options = []): array
  2357. {
  2358. if (!isset($options['associated'])) {
  2359. $options['associated'] = $this->_associations->keys();
  2360. }
  2361. $marshaller = $this->marshaller();
  2362. return $marshaller->mergeMany($entities, $data, $options);
  2363. }
  2364. /**
  2365. * Validator method used to check the uniqueness of a value for a column.
  2366. * This is meant to be used with the validation API and not to be called
  2367. * directly.
  2368. *
  2369. * ### Example:
  2370. *
  2371. * ```
  2372. * $validator->add('email', [
  2373. * 'unique' => ['rule' => 'validateUnique', 'provider' => 'table']
  2374. * ])
  2375. * ```
  2376. *
  2377. * Unique validation can be scoped to the value of another column:
  2378. *
  2379. * ```
  2380. * $validator->add('email', [
  2381. * 'unique' => [
  2382. * 'rule' => ['validateUnique', ['scope' => 'site_id']],
  2383. * 'provider' => 'table'
  2384. * ]
  2385. * ]);
  2386. * ```
  2387. *
  2388. * In the above example, the email uniqueness will be scoped to only rows having
  2389. * the same site_id. Scoping will only be used if the scoping field is present in
  2390. * the data to be validated.
  2391. *
  2392. * @param mixed $value The value of column to be checked for uniqueness.
  2393. * @param array $options The options array, optionally containing the 'scope' key.
  2394. * May also be the validation context, if there are no options.
  2395. * @param array|null $context Either the validation context or null.
  2396. * @return bool True if the value is unique, or false if a non-scalar, non-unique value was given.
  2397. */
  2398. public function validateUnique($value, array $options, ?array $context = null): bool
  2399. {
  2400. if ($context === null) {
  2401. $context = $options;
  2402. }
  2403. $entity = new Entity(
  2404. $context['data'],
  2405. [
  2406. 'useSetters' => false,
  2407. 'markNew' => $context['newRecord'],
  2408. 'source' => $this->getRegistryAlias(),
  2409. ]
  2410. );
  2411. $fields = array_merge(
  2412. [$context['field']],
  2413. isset($options['scope']) ? (array)$options['scope'] : []
  2414. );
  2415. $values = $entity->extract($fields);
  2416. foreach ($values as $field) {
  2417. if ($field !== null && !is_scalar($field)) {
  2418. return false;
  2419. }
  2420. }
  2421. $class = static::IS_UNIQUE_CLASS;
  2422. /** @var \Cake\ORM\Rule\IsUnique $rule */
  2423. $rule = new $class($fields, $options);
  2424. return $rule($entity, ['repository' => $this]);
  2425. }
  2426. /**
  2427. * Get the Model callbacks this table is interested in.
  2428. *
  2429. * By implementing the conventional methods a table class is assumed
  2430. * to be interested in the related event.
  2431. *
  2432. * Override this method if you need to add non-conventional event listeners.
  2433. * Or if you want you table to listen to non-standard events.
  2434. *
  2435. * The conventional method map is:
  2436. *
  2437. * - Model.beforeMarshal => beforeMarshal
  2438. * - Model.buildValidator => buildValidator
  2439. * - Model.beforeFind => beforeFind
  2440. * - Model.beforeSave => beforeSave
  2441. * - Model.afterSave => afterSave
  2442. * - Model.afterSaveCommit => afterSaveCommit
  2443. * - Model.beforeDelete => beforeDelete
  2444. * - Model.afterDelete => afterDelete
  2445. * - Model.afterDeleteCommit => afterDeleteCommit
  2446. * - Model.beforeRules => beforeRules
  2447. * - Model.afterRules => afterRules
  2448. *
  2449. * @return array
  2450. */
  2451. public function implementedEvents(): array
  2452. {
  2453. $eventMap = [
  2454. 'Model.beforeMarshal' => 'beforeMarshal',
  2455. 'Model.buildValidator' => 'buildValidator',
  2456. 'Model.beforeFind' => 'beforeFind',
  2457. 'Model.beforeSave' => 'beforeSave',
  2458. 'Model.afterSave' => 'afterSave',
  2459. 'Model.afterSaveCommit' => 'afterSaveCommit',
  2460. 'Model.beforeDelete' => 'beforeDelete',
  2461. 'Model.afterDelete' => 'afterDelete',
  2462. 'Model.afterDeleteCommit' => 'afterDeleteCommit',
  2463. 'Model.beforeRules' => 'beforeRules',
  2464. 'Model.afterRules' => 'afterRules',
  2465. ];
  2466. $events = [];
  2467. foreach ($eventMap as $event => $method) {
  2468. if (!method_exists($this, $method)) {
  2469. continue;
  2470. }
  2471. $events[$event] = $method;
  2472. }
  2473. return $events;
  2474. }
  2475. /**
  2476. * {@inheritDoc}
  2477. *
  2478. * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
  2479. * @return \Cake\ORM\RulesChecker
  2480. */
  2481. public function buildRules(RulesChecker $rules): RulesChecker
  2482. {
  2483. return $rules;
  2484. }
  2485. /**
  2486. * Gets a SaveOptionsBuilder instance.
  2487. *
  2488. * @param array $options Options to parse by the builder.
  2489. * @return \Cake\ORM\SaveOptionsBuilder
  2490. */
  2491. public function getSaveOptionsBuilder(array $options = []): SaveOptionsBuilder
  2492. {
  2493. return new SaveOptionsBuilder($this, $options);
  2494. }
  2495. /**
  2496. * Loads the specified associations in the passed entity or list of entities
  2497. * by executing extra queries in the database and merging the results in the
  2498. * appropriate properties.
  2499. *
  2500. * ### Example:
  2501. *
  2502. * ```
  2503. * $user = $usersTable->get(1);
  2504. * $user = $usersTable->loadInto($user, ['Articles.Tags', 'Articles.Comments']);
  2505. * echo $user->articles[0]->title;
  2506. * ```
  2507. *
  2508. * You can also load associations for multiple entities at once
  2509. *
  2510. * ### Example:
  2511. *
  2512. * ```
  2513. * $users = $usersTable->find()->where([...])->toList();
  2514. * $users = $usersTable->loadInto($users, ['Articles.Tags', 'Articles.Comments']);
  2515. * echo $user[1]->articles[0]->title;
  2516. * ```
  2517. *
  2518. * The properties for the associations to be loaded will be overwritten on each entity.
  2519. *
  2520. * @param \Cake\Datasource\EntityInterface|array $entities a single entity or list of entities
  2521. * @param array $contain A `contain()` compatible array.
  2522. * @see \Cake\ORM\Query::contain()
  2523. * @return \Cake\Datasource\EntityInterface|array
  2524. */
  2525. public function loadInto($entities, array $contain)
  2526. {
  2527. return (new LazyEagerLoader())->loadInto($entities, $contain, $this);
  2528. }
  2529. /**
  2530. * @inheritDoc
  2531. */
  2532. protected function validationMethodExists(string $method): bool
  2533. {
  2534. return method_exists($this, $method) || $this->behaviors()->hasMethod($method);
  2535. }
  2536. /**
  2537. * Returns an array that can be used to describe the internal state of this
  2538. * object.
  2539. *
  2540. * @return array
  2541. */
  2542. public function __debugInfo()
  2543. {
  2544. $conn = $this->getConnection();
  2545. return [
  2546. 'registryAlias' => $this->getRegistryAlias(),
  2547. 'table' => $this->getTable(),
  2548. 'alias' => $this->getAlias(),
  2549. 'entityClass' => $this->getEntityClass(),
  2550. 'associations' => $this->_associations->keys(),
  2551. 'behaviors' => $this->_behaviors->loaded(),
  2552. 'defaultConnection' => static::defaultConnectionName(),
  2553. 'connectionName' => $conn->configName(),
  2554. ];
  2555. }
  2556. }