Table.php 77 KB

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