Table.php 82 KB

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