PageRenderTime 52ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Datasource/EntityTrait.php

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