Table.php 61 KB

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