EntityTrait.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Datasource;
  16. use Cake\Collection\Collection;
  17. use Cake\Utility\Hash;
  18. use Cake\Utility\Inflector;
  19. use InvalidArgumentException;
  20. use Traversable;
  21. /**
  22. * An entity represents a single result row from a repository. It exposes the
  23. * methods for retrieving and storing properties associated in this row.
  24. */
  25. trait EntityTrait
  26. {
  27. /**
  28. * Holds all properties and their values for this entity
  29. *
  30. * @var array
  31. */
  32. protected $_properties = [];
  33. /**
  34. * Holds all properties that have been changed and their original values for this entity
  35. *
  36. * @var array
  37. */
  38. protected $_original = [];
  39. /**
  40. * List of property names that should **not** be included in JSON or Array
  41. * representations of this Entity.
  42. *
  43. * @var array
  44. */
  45. protected $_hidden = [];
  46. /**
  47. * List of computed or virtual fields that **should** be included in JSON or array
  48. * representations of this Entity. If a field is present in both _hidden and _virtual
  49. * the field will **not** be in the array/json versions of the entity.
  50. *
  51. * @var array
  52. */
  53. protected $_virtual = [];
  54. /**
  55. * Holds the name of the class for the instance object
  56. *
  57. * @var string
  58. *
  59. * @deprecated 3.2 This field is no longer being used
  60. */
  61. protected $_className;
  62. /**
  63. * Holds a list of the properties that were modified or added after this object
  64. * was originally created.
  65. *
  66. * @var array
  67. */
  68. protected $_dirty = [];
  69. /**
  70. * Holds a cached list of getters/setters per class
  71. *
  72. * @var array
  73. */
  74. protected static $_accessors = [];
  75. /**
  76. * Indicates whether or not this entity is yet to be persisted.
  77. * Entities default to assuming they are new. You can use Table::persisted()
  78. * to set the new flag on an entity based on records in the database.
  79. *
  80. * @var bool
  81. */
  82. protected $_new = true;
  83. /**
  84. * List of errors per field as stored in this object
  85. *
  86. * @var array
  87. */
  88. protected $_errors = [];
  89. /**
  90. * List of invalid fields and their data for errors upon validation/patching
  91. *
  92. * @var array
  93. */
  94. protected $_invalid = [];
  95. /**
  96. * Map of properties in this entity that can be safely assigned, each
  97. * property name points to a boolean indicating its status. An empty array
  98. * means no properties are accessible
  99. *
  100. * The special property '\*' can also be mapped, meaning that any other property
  101. * not defined in the map will take its value. For example, `'\*' => true`
  102. * means that any property not defined in the map will be accessible by default
  103. *
  104. * @var array
  105. */
  106. protected $_accessible = ['*' => true];
  107. /**
  108. * The alias of the repository this entity came from
  109. *
  110. * @var string
  111. */
  112. protected $_registryAlias;
  113. /**
  114. * Magic getter to access properties that have been set in this entity
  115. *
  116. * @param string $property Name of the property to access
  117. * @return mixed
  118. */
  119. public function &__get($property)
  120. {
  121. return $this->get($property);
  122. }
  123. /**
  124. * Magic setter to add or edit a property in this entity
  125. *
  126. * @param string $property The name of the property to set
  127. * @param mixed $value The value to set to the property
  128. * @return void
  129. */
  130. public function __set($property, $value)
  131. {
  132. $this->set($property, $value);
  133. }
  134. /**
  135. * Returns whether this entity contains a property named $property
  136. * regardless of if it is empty.
  137. *
  138. * @param string $property The property to check.
  139. * @return bool
  140. * @see \Cake\ORM\Entity::has()
  141. */
  142. public function __isset($property)
  143. {
  144. return $this->has($property);
  145. }
  146. /**
  147. * Removes a property from this entity
  148. *
  149. * @param string $property The property to unset
  150. * @return void
  151. */
  152. public function __unset($property)
  153. {
  154. $this->unsetProperty($property);
  155. }
  156. /**
  157. * Sets a single property inside this entity.
  158. *
  159. * ### Example:
  160. *
  161. * ```
  162. * $entity->set('name', 'Andrew');
  163. * ```
  164. *
  165. * It is also possible to mass-assign multiple properties to this entity
  166. * with one call by passing a hashed array as properties in the form of
  167. * property => value pairs
  168. *
  169. * ### Example:
  170. *
  171. * ```
  172. * $entity->set(['name' => 'andrew', 'id' => 1]);
  173. * echo $entity->name // prints andrew
  174. * echo $entity->id // prints 1
  175. * ```
  176. *
  177. * Some times it is handy to bypass setter functions in this entity when assigning
  178. * properties. You can achieve this by disabling the `setter` option using the
  179. * `$options` parameter:
  180. *
  181. * ```
  182. * $entity->set('name', 'Andrew', ['setter' => false]);
  183. * $entity->set(['name' => 'Andrew', 'id' => 1], ['setter' => false]);
  184. * ```
  185. *
  186. * Mass assignment should be treated carefully when accepting user input, by default
  187. * entities will guard all fields when properties are assigned in bulk. You can disable
  188. * the guarding for a single set call with the `guard` option:
  189. *
  190. * ```
  191. * $entity->set(['name' => 'Andrew', 'id' => 1], ['guard' => true]);
  192. * ```
  193. *
  194. * You do not need to use the guard option when assigning properties individually:
  195. *
  196. * ```
  197. * // No need to use the guard option.
  198. * $entity->set('name', 'Andrew');
  199. * ```
  200. *
  201. * @param string|array $property the name of property to set or a list of
  202. * properties with their respective values
  203. * @param mixed $value The value to set to the property or an array if the
  204. * first argument is also an array, in which case will be treated as $options
  205. * @param array $options options to be used for setting the property. Allowed option
  206. * keys are `setter` and `guard`
  207. * @return $this
  208. * @throws \InvalidArgumentException
  209. */
  210. public function set($property, $value = null, array $options = [])
  211. {
  212. if (is_string($property) && $property !== '') {
  213. $guard = false;
  214. $property = [$property => $value];
  215. } else {
  216. $guard = true;
  217. $options = (array)$value;
  218. }
  219. if (!is_array($property)) {
  220. throw new InvalidArgumentException('Cannot set an empty property');
  221. }
  222. $options += ['setter' => true, 'guard' => $guard];
  223. foreach ($property as $p => $value) {
  224. if ($options['guard'] === true && !$this->isAccessible($p)) {
  225. continue;
  226. }
  227. $this->setDirty($p, true);
  228. if (!array_key_exists($p, $this->_original) &&
  229. array_key_exists($p, $this->_properties) &&
  230. $this->_properties[$p] !== $value
  231. ) {
  232. $this->_original[$p] = $this->_properties[$p];
  233. }
  234. if (!$options['setter']) {
  235. $this->_properties[$p] = $value;
  236. continue;
  237. }
  238. $setter = static::_accessor($p, 'set');
  239. if ($setter) {
  240. $value = $this->{$setter}($value);
  241. }
  242. $this->_properties[$p] = $value;
  243. }
  244. return $this;
  245. }
  246. /**
  247. * Returns the value of a property by name
  248. *
  249. * @param string $property the name of the property to retrieve
  250. * @return mixed
  251. * @throws \InvalidArgumentException if an empty property name is passed
  252. */
  253. public function &get($property)
  254. {
  255. if (!strlen((string)$property)) {
  256. throw new InvalidArgumentException('Cannot get an empty property');
  257. }
  258. $value = null;
  259. $method = static::_accessor($property, 'get');
  260. if (isset($this->_properties[$property])) {
  261. $value =& $this->_properties[$property];
  262. }
  263. if ($method) {
  264. $result = $this->{$method}($value);
  265. return $result;
  266. }
  267. return $value;
  268. }
  269. /**
  270. * Returns the value of an original property by name
  271. *
  272. * @param string $property the name of the property for which original value is retrieved.
  273. * @return mixed
  274. * @throws \InvalidArgumentException if an empty property name is passed.
  275. */
  276. public function getOriginal($property)
  277. {
  278. if (!strlen((string)$property)) {
  279. throw new InvalidArgumentException('Cannot get an empty property');
  280. }
  281. if (array_key_exists($property, $this->_original)) {
  282. return $this->_original[$property];
  283. }
  284. return $this->get($property);
  285. }
  286. /**
  287. * Gets all original values of the entity.
  288. *
  289. * @return array
  290. */
  291. public function getOriginalValues()
  292. {
  293. $originals = $this->_original;
  294. $originalKeys = array_keys($originals);
  295. foreach ($this->_properties as $key => $value) {
  296. if (!in_array($key, $originalKeys)) {
  297. $originals[$key] = $value;
  298. }
  299. }
  300. return $originals;
  301. }
  302. /**
  303. * Returns whether this entity contains a property named $property
  304. * that contains a non-null value.
  305. *
  306. * ### Example:
  307. *
  308. * ```
  309. * $entity = new Entity(['id' => 1, 'name' => null]);
  310. * $entity->has('id'); // true
  311. * $entity->has('name'); // false
  312. * $entity->has('last_name'); // false
  313. * ```
  314. *
  315. * You can check multiple properties by passing an array:
  316. *
  317. * ```
  318. * $entity->has(['name', 'last_name']);
  319. * ```
  320. *
  321. * All properties must not be null to get a truthy result.
  322. *
  323. * When checking multiple properties. All properties must not be null
  324. * in order for true to be returned.
  325. *
  326. * @param string|array $property The property or properties to check.
  327. * @return bool
  328. */
  329. public function has($property)
  330. {
  331. foreach ((array)$property as $prop) {
  332. if ($this->get($prop) === null) {
  333. return false;
  334. }
  335. }
  336. return true;
  337. }
  338. /**
  339. * Checks that a property is empty
  340. *
  341. * This is not working like the PHP `empty()` function. The method will
  342. * return true for:
  343. *
  344. * - `''` (empty string)
  345. * - `null`
  346. * - `[]`
  347. *
  348. * and false in all other cases.
  349. *
  350. * @param string $property The property to check.
  351. * @return bool
  352. */
  353. public function isEmpty($property)
  354. {
  355. $value = $this->get($property);
  356. if ($value === null
  357. || (is_array($value) && empty($value)
  358. || (is_string($value) && empty($value)))
  359. ) {
  360. return true;
  361. }
  362. return false;
  363. }
  364. /**
  365. * Checks tha a property has a value.
  366. *
  367. * This method will return true for
  368. *
  369. * - Non-empty strings
  370. * - Non-empty arrays
  371. * - Any object
  372. * - Integer, even `0`
  373. * - Float, even 0.0
  374. *
  375. * and false in all other cases.
  376. *
  377. * @param string $property The property to check.
  378. * @return bool
  379. */
  380. public function hasValue($property)
  381. {
  382. return !$this->isEmpty($property);
  383. }
  384. /**
  385. * Removes a property or list of properties from this entity
  386. *
  387. * ### Examples:
  388. *
  389. * ```
  390. * $entity->unsetProperty('name');
  391. * $entity->unsetProperty(['name', 'last_name']);
  392. * ```
  393. *
  394. * @param string|array $property The property to unset.
  395. * @return $this
  396. */
  397. public function unsetProperty($property)
  398. {
  399. $property = (array)$property;
  400. foreach ($property as $p) {
  401. unset($this->_properties[$p], $this->_dirty[$p]);
  402. }
  403. return $this;
  404. }
  405. /**
  406. * Get/Set the hidden properties on this entity.
  407. *
  408. * If the properties argument is null, the currently hidden properties
  409. * will be returned. Otherwise the hidden properties will be set.
  410. *
  411. * @deprecated 3.4.0 Use EntityTrait::setHidden() and EntityTrait::getHidden()
  412. * @param null|array $properties Either an array of properties to hide or null to get properties
  413. * @return array|$this
  414. */
  415. public function hiddenProperties($properties = null)
  416. {
  417. deprecationWarning(
  418. get_called_class() . '::hiddenProperties() is deprecated. ' .
  419. 'Use setHidden()/getHidden() instead.'
  420. );
  421. if ($properties === null) {
  422. return $this->_hidden;
  423. }
  424. $this->_hidden = $properties;
  425. return $this;
  426. }
  427. /**
  428. * Sets hidden properties.
  429. *
  430. * @param array $properties An array of properties to hide from array exports.
  431. * @param bool $merge Merge the new properties with the existing. By default false.
  432. * @return $this
  433. */
  434. public function setHidden(array $properties, $merge = false)
  435. {
  436. if ($merge === false) {
  437. $this->_hidden = $properties;
  438. return $this;
  439. }
  440. $properties = array_merge($this->_hidden, $properties);
  441. $this->_hidden = array_unique($properties);
  442. return $this;
  443. }
  444. /**
  445. * Gets the hidden properties.
  446. *
  447. * @return array
  448. */
  449. public function getHidden()
  450. {
  451. return $this->_hidden;
  452. }
  453. /**
  454. * Get/Set the virtual properties on this entity.
  455. *
  456. * If the properties argument is null, the currently virtual properties
  457. * will be returned. Otherwise the virtual properties will be set.
  458. *
  459. * @deprecated 3.4.0 Use EntityTrait::getVirtual() and EntityTrait::setVirtual()
  460. * @param null|array $properties Either an array of properties to treat as virtual or null to get properties
  461. * @return array|$this
  462. */
  463. public function virtualProperties($properties = null)
  464. {
  465. deprecationWarning(
  466. get_called_class() . '::virtualProperties() is deprecated. ' .
  467. 'Use setVirtual()/getVirtual() instead.'
  468. );
  469. if ($properties === null) {
  470. return $this->getVirtual();
  471. }
  472. return $this->setVirtual($properties);
  473. }
  474. /**
  475. * Sets the virtual properties on this entity.
  476. *
  477. * @param array $properties An array of properties to treat as virtual.
  478. * @param bool $merge Merge the new properties with the existing. By default false.
  479. * @return $this
  480. */
  481. public function setVirtual(array $properties, $merge = false)
  482. {
  483. if ($merge === false) {
  484. $this->_virtual = $properties;
  485. return $this;
  486. }
  487. $properties = array_merge($this->_virtual, $properties);
  488. $this->_virtual = array_unique($properties);
  489. return $this;
  490. }
  491. /**
  492. * Gets the virtual properties on this entity.
  493. *
  494. * @return array
  495. */
  496. public function getVirtual()
  497. {
  498. return $this->_virtual;
  499. }
  500. /**
  501. * Gets the list of visible properties.
  502. *
  503. * The list of visible properties is all standard properties
  504. * plus virtual properties minus hidden properties.
  505. *
  506. * @return array A list of properties that are 'visible' in all
  507. * representations.
  508. */
  509. public function getVisible()
  510. {
  511. $properties = array_keys($this->_properties);
  512. $properties = array_merge($properties, $this->_virtual);
  513. return array_diff($properties, $this->_hidden);
  514. }
  515. /**
  516. * Gets the list of visible properties.
  517. *
  518. * The list of visible properties is all standard properties
  519. * plus virtual properties minus hidden properties.
  520. *
  521. * @return array A list of properties that are 'visible' in all
  522. * representations.
  523. * @deprecated 3.8.0 Use getVisible() instead.
  524. */
  525. public function visibleProperties()
  526. {
  527. deprecationWarning(
  528. get_called_class() . '::visibleProperties() is deprecated. ' .
  529. 'Use getVisible() instead.'
  530. );
  531. return $this->getVisible();
  532. }
  533. /**
  534. * Returns an array with all the properties that have been set
  535. * to this entity
  536. *
  537. * This method will recursively transform entities assigned to properties
  538. * into arrays as well.
  539. *
  540. * @return array
  541. */
  542. public function toArray()
  543. {
  544. $result = [];
  545. foreach ($this->getVisible() as $property) {
  546. $value = $this->get($property);
  547. if (is_array($value)) {
  548. $result[$property] = [];
  549. foreach ($value as $k => $entity) {
  550. if ($entity instanceof EntityInterface) {
  551. $result[$property][$k] = $entity->toArray();
  552. } else {
  553. $result[$property][$k] = $entity;
  554. }
  555. }
  556. } elseif ($value instanceof EntityInterface) {
  557. $result[$property] = $value->toArray();
  558. } else {
  559. $result[$property] = $value;
  560. }
  561. }
  562. return $result;
  563. }
  564. /**
  565. * Returns the properties that will be serialized as JSON
  566. *
  567. * @return array
  568. */
  569. public function jsonSerialize()
  570. {
  571. return $this->extract($this->getVisible());
  572. }
  573. /**
  574. * Implements isset($entity);
  575. *
  576. * @param mixed $offset The offset to check.
  577. * @return bool Success
  578. */
  579. public function offsetExists($offset)
  580. {
  581. return $this->has($offset);
  582. }
  583. /**
  584. * Implements $entity[$offset];
  585. *
  586. * @param mixed $offset The offset to get.
  587. * @return mixed
  588. */
  589. public function &offsetGet($offset)
  590. {
  591. return $this->get($offset);
  592. }
  593. /**
  594. * Implements $entity[$offset] = $value;
  595. *
  596. * @param mixed $offset The offset to set.
  597. * @param mixed $value The value to set.
  598. * @return void
  599. */
  600. public function offsetSet($offset, $value)
  601. {
  602. $this->set($offset, $value);
  603. }
  604. /**
  605. * Implements unset($result[$offset]);
  606. *
  607. * @param mixed $offset The offset to remove.
  608. * @return void
  609. */
  610. public function offsetUnset($offset)
  611. {
  612. $this->unsetProperty($offset);
  613. }
  614. /**
  615. * Fetch accessor method name
  616. * Accessor methods (available or not) are cached in $_accessors
  617. *
  618. * @param string $property the field name to derive getter name from
  619. * @param string $type the accessor type ('get' or 'set')
  620. * @return string method name or empty string (no method available)
  621. */
  622. protected static function _accessor($property, $type)
  623. {
  624. $class = static::class;
  625. if (isset(static::$_accessors[$class][$type][$property])) {
  626. return static::$_accessors[$class][$type][$property];
  627. }
  628. if (!empty(static::$_accessors[$class])) {
  629. return static::$_accessors[$class][$type][$property] = '';
  630. }
  631. if ($class === 'Cake\ORM\Entity') {
  632. return '';
  633. }
  634. foreach (get_class_methods($class) as $method) {
  635. $prefix = substr($method, 1, 3);
  636. if ($method[0] !== '_' || ($prefix !== 'get' && $prefix !== 'set')) {
  637. continue;
  638. }
  639. $field = lcfirst(substr($method, 4));
  640. $snakeField = Inflector::underscore($field);
  641. $titleField = ucfirst($field);
  642. static::$_accessors[$class][$prefix][$snakeField] = $method;
  643. static::$_accessors[$class][$prefix][$field] = $method;
  644. static::$_accessors[$class][$prefix][$titleField] = $method;
  645. }
  646. if (!isset(static::$_accessors[$class][$type][$property])) {
  647. static::$_accessors[$class][$type][$property] = '';
  648. }
  649. return static::$_accessors[$class][$type][$property];
  650. }
  651. /**
  652. * Returns an array with the requested properties
  653. * stored in this entity, indexed by property name
  654. *
  655. * @param array $properties list of properties to be returned
  656. * @param bool $onlyDirty Return the requested property only if it is dirty
  657. * @return array
  658. */
  659. public function extract(array $properties, $onlyDirty = false)
  660. {
  661. $result = [];
  662. foreach ($properties as $property) {
  663. if (!$onlyDirty || $this->isDirty($property)) {
  664. $result[$property] = $this->get($property);
  665. }
  666. }
  667. return $result;
  668. }
  669. /**
  670. * Returns an array with the requested original properties
  671. * stored in this entity, indexed by property name.
  672. *
  673. * Properties that are unchanged from their original value will be included in the
  674. * return of this method.
  675. *
  676. * @param array $properties List of properties to be returned
  677. * @return array
  678. */
  679. public function extractOriginal(array $properties)
  680. {
  681. $result = [];
  682. foreach ($properties as $property) {
  683. $result[$property] = $this->getOriginal($property);
  684. }
  685. return $result;
  686. }
  687. /**
  688. * Returns an array with only the original properties
  689. * stored in this entity, indexed by property name.
  690. *
  691. * This method will only return properties that have been modified since
  692. * the entity was built. Unchanged properties will be omitted.
  693. *
  694. * @param array $properties List of properties to be returned
  695. * @return array
  696. */
  697. public function extractOriginalChanged(array $properties)
  698. {
  699. $result = [];
  700. foreach ($properties as $property) {
  701. $original = $this->getOriginal($property);
  702. if ($original !== $this->get($property)) {
  703. $result[$property] = $original;
  704. }
  705. }
  706. return $result;
  707. }
  708. /**
  709. * Sets the dirty status of a single property. If called with no second
  710. * argument, it will return whether the property was modified or not
  711. * after the object creation.
  712. *
  713. * When called with no arguments it will return whether or not there are any
  714. * dirty property in the entity
  715. *
  716. * @deprecated 3.4.0 Use EntityTrait::setDirty() and EntityTrait::isDirty()
  717. * @param string|null $property the field to set or check status for
  718. * @param null|bool $isDirty true means the property was changed, false means
  719. * it was not changed and null will make the function return current state
  720. * for that property
  721. * @return bool Whether the property was changed or not
  722. */
  723. public function dirty($property = null, $isDirty = null)
  724. {
  725. deprecationWarning(
  726. get_called_class() . '::dirty() is deprecated. ' .
  727. 'Use setDirty()/isDirty() instead.'
  728. );
  729. if ($property === null) {
  730. return $this->isDirty();
  731. }
  732. if ($isDirty === null) {
  733. return $this->isDirty($property);
  734. }
  735. $this->setDirty($property, $isDirty);
  736. return true;
  737. }
  738. /**
  739. * Sets the dirty status of a single property.
  740. *
  741. * @param string $property the field to set or check status for
  742. * @param bool $isDirty true means the property was changed, false means
  743. * it was not changed. Defaults to true.
  744. * @return $this
  745. */
  746. public function setDirty($property, $isDirty = true)
  747. {
  748. if ($isDirty === false) {
  749. unset($this->_dirty[$property]);
  750. return $this;
  751. }
  752. $this->_dirty[$property] = true;
  753. unset($this->_errors[$property], $this->_invalid[$property]);
  754. return $this;
  755. }
  756. /**
  757. * Checks if the entity is dirty or if a single property of it is dirty.
  758. *
  759. * @param string|null $property The field to check the status for. Null for the whole entity.
  760. * @return bool Whether the property was changed or not
  761. */
  762. public function isDirty($property = null)
  763. {
  764. if ($property === null) {
  765. return !empty($this->_dirty);
  766. }
  767. return isset($this->_dirty[$property]);
  768. }
  769. /**
  770. * Gets the dirty properties.
  771. *
  772. * @return string[]
  773. */
  774. public function getDirty()
  775. {
  776. return array_keys($this->_dirty);
  777. }
  778. /**
  779. * Sets the entire entity as clean, which means that it will appear as
  780. * no properties being modified or added at all. This is an useful call
  781. * for an initial object hydration
  782. *
  783. * @return void
  784. */
  785. public function clean()
  786. {
  787. $this->_dirty = [];
  788. $this->_errors = [];
  789. $this->_invalid = [];
  790. $this->_original = [];
  791. }
  792. /**
  793. * Returns whether or not this entity has already been persisted.
  794. * This method can return null in the case there is no prior information on
  795. * the status of this entity.
  796. *
  797. * If called with a boolean it will set the known status of this instance,
  798. * true means that the instance is not yet persisted in the database, false
  799. * that it already is.
  800. *
  801. * @param bool|null $new true if it is known this instance was not yet persisted
  802. * @return bool Whether or not the entity has been persisted.
  803. */
  804. public function isNew($new = null)
  805. {
  806. if ($new === null) {
  807. return $this->_new;
  808. }
  809. $new = (bool)$new;
  810. if ($new) {
  811. foreach ($this->_properties as $k => $p) {
  812. $this->_dirty[$k] = true;
  813. }
  814. }
  815. return $this->_new = $new;
  816. }
  817. /**
  818. * Returns whether this entity has errors.
  819. *
  820. * @param bool $includeNested true will check nested entities for hasErrors()
  821. * @return bool
  822. */
  823. public function hasErrors($includeNested = true)
  824. {
  825. if (Hash::filter($this->_errors)) {
  826. return true;
  827. }
  828. if ($includeNested === false) {
  829. return false;
  830. }
  831. foreach ($this->_properties as $property) {
  832. if ($this->_readHasErrors($property)) {
  833. return true;
  834. }
  835. }
  836. return false;
  837. }
  838. /**
  839. * Returns all validation errors.
  840. *
  841. * @return array
  842. */
  843. public function getErrors()
  844. {
  845. $diff = array_diff_key($this->_properties, $this->_errors);
  846. return $this->_errors + (new Collection($diff))
  847. ->filter(function ($value) {
  848. return is_array($value) || $value instanceof EntityInterface;
  849. })
  850. ->map(function ($value) {
  851. return $this->_readError($value);
  852. })
  853. ->filter()
  854. ->toArray();
  855. }
  856. /**
  857. * Returns validation errors of a field
  858. *
  859. * @param string $field Field name to get the errors from
  860. * @return array
  861. */
  862. public function getError($field)
  863. {
  864. $errors = isset($this->_errors[$field]) ? $this->_errors[$field] : [];
  865. if ($errors) {
  866. return $errors;
  867. }
  868. return $this->_nestedErrors($field);
  869. }
  870. /**
  871. * Sets error messages to the entity
  872. *
  873. * ## Example
  874. *
  875. * ```
  876. * // Sets the error messages for multiple fields at once
  877. * $entity->setErrors(['salary' => ['message'], 'name' => ['another message']]);
  878. * ```
  879. *
  880. * @param array $fields The array of errors to set.
  881. * @param bool $overwrite Whether or not to overwrite pre-existing errors for $fields
  882. * @return $this
  883. */
  884. public function setErrors(array $fields, $overwrite = false)
  885. {
  886. if ($overwrite) {
  887. foreach ($fields as $f => $error) {
  888. $this->_errors[$f] = (array)$error;
  889. }
  890. return $this;
  891. }
  892. foreach ($fields as $f => $error) {
  893. $this->_errors += [$f => []];
  894. // String messages are appended to the list,
  895. // while more complex error structures need their
  896. // keys preserved for nested validator.
  897. if (is_string($error)) {
  898. $this->_errors[$f][] = $error;
  899. } else {
  900. foreach ($error as $k => $v) {
  901. $this->_errors[$f][$k] = $v;
  902. }
  903. }
  904. }
  905. return $this;
  906. }
  907. /**
  908. * Sets errors for a single field
  909. *
  910. * ### Example
  911. *
  912. * ```
  913. * // Sets the error messages for a single field
  914. * $entity->setError('salary', ['must be numeric', 'must be a positive number']);
  915. * ```
  916. *
  917. * @param string $field The field to get errors for, or the array of errors to set.
  918. * @param string|array $errors The errors to be set for $field
  919. * @param bool $overwrite Whether or not to overwrite pre-existing errors for $field
  920. * @return $this
  921. */
  922. public function setError($field, $errors, $overwrite = false)
  923. {
  924. if (is_string($errors)) {
  925. $errors = [$errors];
  926. }
  927. return $this->setErrors([$field => $errors], $overwrite);
  928. }
  929. /**
  930. * Sets the error messages for a field or a list of fields. When called
  931. * without the second argument it returns the validation
  932. * errors for the specified fields. If called with no arguments it returns
  933. * all the validation error messages stored in this entity and any other nested
  934. * entity.
  935. *
  936. * ### Example
  937. *
  938. * ```
  939. * // Sets the error messages for a single field
  940. * $entity->errors('salary', ['must be numeric', 'must be a positive number']);
  941. *
  942. * // Returns the error messages for a single field
  943. * $entity->getErrors('salary');
  944. *
  945. * // Returns all error messages indexed by field name
  946. * $entity->getErrors();
  947. *
  948. * // Sets the error messages for multiple fields at once
  949. * $entity->getErrors(['salary' => ['message'], 'name' => ['another message']);
  950. * ```
  951. *
  952. * When used as a setter, this method will return this entity instance for method
  953. * chaining.
  954. *
  955. * @deprecated 3.4.0 Use EntityTrait::setError(), EntityTrait::setErrors(), EntityTrait::getError() and EntityTrait::getErrors()
  956. * @param string|array|null $field The field to get errors for, or the array of errors to set.
  957. * @param string|array|null $errors The errors to be set for $field
  958. * @param bool $overwrite Whether or not to overwrite pre-existing errors for $field
  959. * @return array|$this
  960. */
  961. public function errors($field = null, $errors = null, $overwrite = false)
  962. {
  963. deprecationWarning(
  964. get_called_class() . '::errors() is deprecated. ' .
  965. 'Use setError()/getError() or setErrors()/getErrors() instead.'
  966. );
  967. if ($field === null) {
  968. return $this->getErrors();
  969. }
  970. if (is_string($field) && $errors === null) {
  971. return $this->getError($field);
  972. }
  973. if (!is_array($field)) {
  974. $field = [$field => $errors];
  975. }
  976. return $this->setErrors($field, $overwrite);
  977. }
  978. /**
  979. * Auxiliary method for getting errors in nested entities
  980. *
  981. * @param string $field the field in this entity to check for errors
  982. * @return array errors in nested entity if any
  983. */
  984. protected function _nestedErrors($field)
  985. {
  986. // Only one path element, check for nested entity with error.
  987. if (strpos($field, '.') === false) {
  988. return $this->_readError($this->get($field));
  989. }
  990. // Try reading the errors data with field as a simple path
  991. $error = Hash::get($this->_errors, $field);
  992. if ($error !== null) {
  993. return $error;
  994. }
  995. $path = explode('.', $field);
  996. // Traverse down the related entities/arrays for
  997. // the relevant entity.
  998. $entity = $this;
  999. $len = count($path);
  1000. while ($len) {
  1001. $part = array_shift($path);
  1002. $len = count($path);
  1003. $val = null;
  1004. if ($entity instanceof EntityInterface) {
  1005. $val = $entity->get($part);
  1006. } elseif (is_array($entity)) {
  1007. $val = isset($entity[$part]) ? $entity[$part] : false;
  1008. }
  1009. if (is_array($val) ||
  1010. $val instanceof Traversable ||
  1011. $val instanceof EntityInterface
  1012. ) {
  1013. $entity = $val;
  1014. } else {
  1015. $path[] = $part;
  1016. break;
  1017. }
  1018. }
  1019. if (count($path) <= 1) {
  1020. return $this->_readError($entity, array_pop($path));
  1021. }
  1022. return [];
  1023. }
  1024. /**
  1025. * Reads if there are errors for one or many objects.
  1026. *
  1027. * @param mixed $object The object to read errors from.
  1028. * @return bool
  1029. */
  1030. protected function _readHasErrors($object)
  1031. {
  1032. if ($object instanceof EntityInterface && $object->hasErrors()) {
  1033. return true;
  1034. }
  1035. if (is_array($object)) {
  1036. foreach ($object as $value) {
  1037. if ($this->_readHasErrors($value)) {
  1038. return true;
  1039. }
  1040. }
  1041. }
  1042. return false;
  1043. }
  1044. /**
  1045. * Read the error(s) from one or many objects.
  1046. *
  1047. * @param array|\Cake\Datasource\EntityInterface $object The object to read errors from.
  1048. * @param string|null $path The field name for errors.
  1049. * @return array
  1050. */
  1051. protected function _readError($object, $path = null)
  1052. {
  1053. if ($path !== null && $object instanceof EntityInterface) {
  1054. return $object->getError($path);
  1055. }
  1056. if ($object instanceof EntityInterface) {
  1057. return $object->getErrors();
  1058. }
  1059. if (is_array($object)) {
  1060. $array = array_map(function ($val) {
  1061. if ($val instanceof EntityInterface) {
  1062. return $val->getErrors();
  1063. }
  1064. }, $object);
  1065. return array_filter($array);
  1066. }
  1067. return [];
  1068. }
  1069. /**
  1070. * Get a list of invalid fields and their data for errors upon validation/patching
  1071. *
  1072. * @return array
  1073. */
  1074. public function getInvalid()
  1075. {
  1076. return $this->_invalid;
  1077. }
  1078. /**
  1079. * Get a single value of an invalid field. Returns null if not set.
  1080. *
  1081. * @param string $field The name of the field.
  1082. * @return mixed
  1083. */
  1084. public function getInvalidField($field)
  1085. {
  1086. $value = isset($this->_invalid[$field]) ? $this->_invalid[$field] : null;
  1087. return $value;
  1088. }
  1089. /**
  1090. * Set fields as invalid and not patchable into the entity.
  1091. *
  1092. * This is useful for batch operations when one needs to get the original value for an error message after patching.
  1093. * This value could not be patched into the entity and is simply copied into the _invalid property for debugging purposes
  1094. * or to be able to log it away.
  1095. *
  1096. * @param array $fields The values to set.
  1097. * @param bool $overwrite Whether or not to overwrite pre-existing values for $field.
  1098. * @return $this
  1099. */
  1100. public function setInvalid(array $fields, $overwrite = false)
  1101. {
  1102. foreach ($fields as $field => $value) {
  1103. if ($overwrite === true) {
  1104. $this->_invalid[$field] = $value;
  1105. continue;
  1106. }
  1107. $this->_invalid += [$field => $value];
  1108. }
  1109. return $this;
  1110. }
  1111. /**
  1112. * Sets a field as invalid and not patchable into the entity.
  1113. *
  1114. * @param string $field The value to set.
  1115. * @param mixed $value The invalid value to be set for $field.
  1116. * @return $this
  1117. */
  1118. public function setInvalidField($field, $value)
  1119. {
  1120. $this->_invalid[$field] = $value;
  1121. return $this;
  1122. }
  1123. /**
  1124. * Sets a field as invalid and not patchable into the entity.
  1125. *
  1126. * This is useful for batch operations when one needs to get the original value for an error message after patching.
  1127. * This value could not be patched into the entity and is simply copied into the _invalid property for debugging purposes
  1128. * or to be able to log it away.
  1129. *
  1130. * @deprecated 3.5 Use getInvalid()/getInvalidField()/setInvalid() instead.
  1131. * @param string|array|null $field The field to get invalid value for, or the value to set.
  1132. * @param mixed|null $value The invalid value to be set for $field.
  1133. * @param bool $overwrite Whether or not to overwrite pre-existing values for $field.
  1134. * @return $this|mixed
  1135. */
  1136. public function invalid($field = null, $value = null, $overwrite = false)
  1137. {
  1138. deprecationWarning(
  1139. get_called_class() . '::invalid() is deprecated. ' .
  1140. 'Use setInvalid()/getInvalid()/getInvalidField() instead.'
  1141. );
  1142. if ($field === null) {
  1143. return $this->_invalid;
  1144. }
  1145. if (is_string($field) && $value === null) {
  1146. $value = isset($this->_invalid[$field]) ? $this->_invalid[$field] : null;
  1147. return $value;
  1148. }
  1149. if (!is_array($field)) {
  1150. $field = [$field => $value];
  1151. }
  1152. foreach ($field as $f => $value) {
  1153. if ($overwrite) {
  1154. $this->_invalid[$f] = $value;
  1155. continue;
  1156. }
  1157. $this->_invalid += [$f => $value];
  1158. }
  1159. return $this;
  1160. }
  1161. /**
  1162. * Stores whether or not a property value can be changed or set in this entity.
  1163. * The special property `*` can also be marked as accessible or protected, meaning
  1164. * that any other property specified before will take its value. For example
  1165. * `$entity->accessible('*', true)` means that any property not specified already
  1166. * will be accessible by default.
  1167. *
  1168. * You can also call this method with an array of properties, in which case they
  1169. * will each take the accessibility value specified in the second argument.
  1170. *
  1171. * ### Example:
  1172. *
  1173. * ```
  1174. * $entity->accessible('id', true); // Mark id as not protected
  1175. * $entity->accessible('author_id', false); // Mark author_id as protected
  1176. * $entity->accessible(['id', 'user_id'], true); // Mark both properties as accessible
  1177. * $entity->accessible('*', false); // Mark all properties as protected
  1178. * ```
  1179. *
  1180. * When called without the second param it will return whether or not the property
  1181. * can be set.
  1182. *
  1183. * ### Example:
  1184. *
  1185. * ```
  1186. * $entity->accessible('id'); // Returns whether it can be set or not
  1187. * ```
  1188. *
  1189. * @deprecated 3.4.0 Use EntityTrait::setAccess() and EntityTrait::isAccessible()
  1190. * @param string|array $property single or list of properties to change its accessibility
  1191. * @param bool|null $set true marks the property as accessible, false will
  1192. * mark it as protected.
  1193. * @return $this|bool
  1194. */
  1195. public function accessible($property, $set = null)
  1196. {
  1197. deprecationWarning(
  1198. get_called_class() . '::accessible() is deprecated. ' .
  1199. 'Use setAccess()/isAccessible() instead.'
  1200. );
  1201. if ($set === null) {
  1202. return $this->isAccessible($property);
  1203. }
  1204. return $this->setAccess($property, $set);
  1205. }
  1206. /**
  1207. * Stores whether or not a property value can be changed or set in this entity.
  1208. * The special property `*` can also be marked as accessible or protected, meaning
  1209. * that any other property specified before will take its value. For example
  1210. * `$entity->setAccess('*', true)` means that any property not specified already
  1211. * will be accessible by default.
  1212. *
  1213. * You can also call this method with an array of properties, in which case they
  1214. * will each take the accessibility value specified in the second argument.
  1215. *
  1216. * ### Example:
  1217. *
  1218. * ```
  1219. * $entity->setAccess('id', true); // Mark id as not protected
  1220. * $entity->setAccess('author_id', false); // Mark author_id as protected
  1221. * $entity->setAccess(['id', 'user_id'], true); // Mark both properties as accessible
  1222. * $entity->setAccess('*', false); // Mark all properties as protected
  1223. * ```
  1224. *
  1225. * @param string|array $property single or list of properties to change its accessibility
  1226. * @param bool $set true marks the property as accessible, false will
  1227. * mark it as protected.
  1228. * @return $this
  1229. */
  1230. public function setAccess($property, $set)
  1231. {
  1232. if ($property === '*') {
  1233. $this->_accessible = array_map(function ($p) use ($set) {
  1234. return (bool)$set;
  1235. }, $this->_accessible);
  1236. $this->_accessible['*'] = (bool)$set;
  1237. return $this;
  1238. }
  1239. foreach ((array)$property as $prop) {
  1240. $this->_accessible[$prop] = (bool)$set;
  1241. }
  1242. return $this;
  1243. }
  1244. /**
  1245. * Checks if a property is accessible
  1246. *
  1247. * ### Example:
  1248. *
  1249. * ```
  1250. * $entity->isAccessible('id'); // Returns whether it can be set or not
  1251. * ```
  1252. *
  1253. * @param string $property Property name to check
  1254. * @return bool
  1255. */
  1256. public function isAccessible($property)
  1257. {
  1258. $value = isset($this->_accessible[$property]) ?
  1259. $this->_accessible[$property] :
  1260. null;
  1261. return ($value === null && !empty($this->_accessible['*'])) || $value;
  1262. }
  1263. /**
  1264. * Returns the alias of the repository from which this entity came from.
  1265. *
  1266. * @return string
  1267. */
  1268. public function getSource()
  1269. {
  1270. return $this->_registryAlias;
  1271. }
  1272. /**
  1273. * Sets the source alias
  1274. *
  1275. * @param string $alias the alias of the repository
  1276. * @return $this
  1277. */
  1278. public function setSource($alias)
  1279. {
  1280. $this->_registryAlias = $alias;
  1281. return $this;
  1282. }
  1283. /**
  1284. * Returns the alias of the repository from which this entity came from.
  1285. *
  1286. * If called with no arguments, it returns the alias of the repository
  1287. * this entity came from if it is known.
  1288. *
  1289. * @deprecated 3.4.0 Use EntityTrait::getSource() and EntityTrait::setSource()
  1290. * @param string|null $alias the alias of the repository
  1291. * @return string|$this
  1292. */
  1293. public function source($alias = null)
  1294. {
  1295. deprecationWarning(
  1296. get_called_class() . '::source() is deprecated. ' .
  1297. 'Use setSource()/getSource() instead.'
  1298. );
  1299. if ($alias === null) {
  1300. return $this->getSource();
  1301. }
  1302. $this->setSource($alias);
  1303. return $this;
  1304. }
  1305. /**
  1306. * Returns a string representation of this object in a human readable format.
  1307. *
  1308. * @return string
  1309. */
  1310. public function __toString()
  1311. {
  1312. return json_encode($this, JSON_PRETTY_PRINT);
  1313. }
  1314. /**
  1315. * Returns an array that can be used to describe the internal state of this
  1316. * object.
  1317. *
  1318. * @return array
  1319. */
  1320. public function __debugInfo()
  1321. {
  1322. $properties = $this->_properties;
  1323. foreach ($this->_virtual as $field) {
  1324. $properties[$field] = $this->$field;
  1325. }
  1326. return $properties + [
  1327. '[new]' => $this->isNew(),
  1328. '[accessible]' => $this->_accessible,
  1329. '[dirty]' => $this->_dirty,
  1330. '[original]' => $this->_original,
  1331. '[virtual]' => $this->_virtual,
  1332. '[hasErrors]' => $this->hasErrors(),
  1333. '[errors]' => $this->_errors,
  1334. '[invalid]' => $this->_invalid,
  1335. '[repository]' => $this->_registryAlias
  1336. ];
  1337. }
  1338. }