Table.php 55 KB

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