Table.php 72 KB

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