Table.php 101 KB

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