EntityTrait.php 38 KB

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