Table.php 103 KB

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