Table.php 58 KB

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