EntityTrait.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  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. * Get 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 visibleProperties()
  510. {
  511. $properties = array_keys($this->_properties);
  512. $properties = array_merge($properties, $this->_virtual);
  513. return array_diff($properties, $this->_hidden);
  514. }
  515. /**
  516. * Returns an array with all the properties that have been set
  517. * to this entity
  518. *
  519. * This method will recursively transform entities assigned to properties
  520. * into arrays as well.
  521. *
  522. * @return array
  523. */
  524. public function toArray()
  525. {
  526. $result = [];
  527. foreach ($this->visibleProperties() as $property) {
  528. $value = $this->get($property);
  529. if (is_array($value)) {
  530. $result[$property] = [];
  531. foreach ($value as $k => $entity) {
  532. if ($entity instanceof EntityInterface) {
  533. $result[$property][$k] = $entity->toArray();
  534. } else {
  535. $result[$property][$k] = $entity;
  536. }
  537. }
  538. } elseif ($value instanceof EntityInterface) {
  539. $result[$property] = $value->toArray();
  540. } else {
  541. $result[$property] = $value;
  542. }
  543. }
  544. return $result;
  545. }
  546. /**
  547. * Returns the properties that will be serialized as JSON
  548. *
  549. * @return array
  550. */
  551. public function jsonSerialize()
  552. {
  553. return $this->extract($this->visibleProperties());
  554. }
  555. /**
  556. * Implements isset($entity);
  557. *
  558. * @param mixed $offset The offset to check.
  559. * @return bool Success
  560. */
  561. public function offsetExists($offset)
  562. {
  563. return $this->has($offset);
  564. }
  565. /**
  566. * Implements $entity[$offset];
  567. *
  568. * @param mixed $offset The offset to get.
  569. * @return mixed
  570. */
  571. public function &offsetGet($offset)
  572. {
  573. return $this->get($offset);
  574. }
  575. /**
  576. * Implements $entity[$offset] = $value;
  577. *
  578. * @param mixed $offset The offset to set.
  579. * @param mixed $value The value to set.
  580. * @return void
  581. */
  582. public function offsetSet($offset, $value)
  583. {
  584. $this->set($offset, $value);
  585. }
  586. /**
  587. * Implements unset($result[$offset]);
  588. *
  589. * @param mixed $offset The offset to remove.
  590. * @return void
  591. */
  592. public function offsetUnset($offset)
  593. {
  594. $this->unsetProperty($offset);
  595. }
  596. /**
  597. * Fetch accessor method name
  598. * Accessor methods (available or not) are cached in $_accessors
  599. *
  600. * @param string $property the field name to derive getter name from
  601. * @param string $type the accessor type ('get' or 'set')
  602. * @return string method name or empty string (no method available)
  603. */
  604. protected static function _accessor($property, $type)
  605. {
  606. $class = static::class;
  607. if (isset(static::$_accessors[$class][$type][$property])) {
  608. return static::$_accessors[$class][$type][$property];
  609. }
  610. if (!empty(static::$_accessors[$class])) {
  611. return static::$_accessors[$class][$type][$property] = '';
  612. }
  613. if ($class === 'Cake\ORM\Entity') {
  614. return '';
  615. }
  616. foreach (get_class_methods($class) as $method) {
  617. $prefix = substr($method, 1, 3);
  618. if ($method[0] !== '_' || ($prefix !== 'get' && $prefix !== 'set')) {
  619. continue;
  620. }
  621. $field = lcfirst(substr($method, 4));
  622. $snakeField = Inflector::underscore($field);
  623. $titleField = ucfirst($field);
  624. static::$_accessors[$class][$prefix][$snakeField] = $method;
  625. static::$_accessors[$class][$prefix][$field] = $method;
  626. static::$_accessors[$class][$prefix][$titleField] = $method;
  627. }
  628. if (!isset(static::$_accessors[$class][$type][$property])) {
  629. static::$_accessors[$class][$type][$property] = '';
  630. }
  631. return static::$_accessors[$class][$type][$property];
  632. }
  633. /**
  634. * Returns an array with the requested properties
  635. * stored in this entity, indexed by property name
  636. *
  637. * @param array $properties list of properties to be returned
  638. * @param bool $onlyDirty Return the requested property only if it is dirty
  639. * @return array
  640. */
  641. public function extract(array $properties, $onlyDirty = false)
  642. {
  643. $result = [];
  644. foreach ($properties as $property) {
  645. if (!$onlyDirty || $this->isDirty($property)) {
  646. $result[$property] = $this->get($property);
  647. }
  648. }
  649. return $result;
  650. }
  651. /**
  652. * Returns an array with the requested original properties
  653. * stored in this entity, indexed by property name.
  654. *
  655. * Properties that are unchanged from their original value will be included in the
  656. * return of this method.
  657. *
  658. * @param array $properties List of properties to be returned
  659. * @return array
  660. */
  661. public function extractOriginal(array $properties)
  662. {
  663. $result = [];
  664. foreach ($properties as $property) {
  665. $result[$property] = $this->getOriginal($property);
  666. }
  667. return $result;
  668. }
  669. /**
  670. * Returns an array with only the original properties
  671. * stored in this entity, indexed by property name.
  672. *
  673. * This method will only return properties that have been modified since
  674. * the entity was built. Unchanged properties will be omitted.
  675. *
  676. * @param array $properties List of properties to be returned
  677. * @return array
  678. */
  679. public function extractOriginalChanged(array $properties)
  680. {
  681. $result = [];
  682. foreach ($properties as $property) {
  683. $original = $this->getOriginal($property);
  684. if ($original !== $this->get($property)) {
  685. $result[$property] = $original;
  686. }
  687. }
  688. return $result;
  689. }
  690. /**
  691. * Sets the dirty status of a single property. If called with no second
  692. * argument, it will return whether the property was modified or not
  693. * after the object creation.
  694. *
  695. * When called with no arguments it will return whether or not there are any
  696. * dirty property in the entity
  697. *
  698. * @deprecated 3.4.0 Use EntityTrait::setDirty() and EntityTrait::isDirty()
  699. * @param string|null $property the field to set or check status for
  700. * @param null|bool $isDirty true means the property was changed, false means
  701. * it was not changed and null will make the function return current state
  702. * for that property
  703. * @return bool Whether the property was changed or not
  704. */
  705. public function dirty($property = null, $isDirty = null)
  706. {
  707. deprecationWarning(
  708. get_called_class() . '::dirty() is deprecated. ' .
  709. 'Use setDirty()/isDirty() instead.'
  710. );
  711. if ($property === null) {
  712. return $this->isDirty();
  713. }
  714. if ($isDirty === null) {
  715. return $this->isDirty($property);
  716. }
  717. $this->setDirty($property, $isDirty);
  718. return true;
  719. }
  720. /**
  721. * Sets the dirty status of a single property.
  722. *
  723. * @param string $property the field to set or check status for
  724. * @param bool $isDirty true means the property was changed, false means
  725. * it was not changed. Defaults to true.
  726. * @return $this
  727. */
  728. public function setDirty($property, $isDirty = true)
  729. {
  730. if ($isDirty === false) {
  731. unset($this->_dirty[$property]);
  732. return $this;
  733. }
  734. $this->_dirty[$property] = true;
  735. unset($this->_errors[$property], $this->_invalid[$property]);
  736. return $this;
  737. }
  738. /**
  739. * Checks if the entity is dirty or if a single property of it is dirty.
  740. *
  741. * @param string|null $property The field to check the status for. Null for the whole entity.
  742. * @return bool Whether the property was changed or not
  743. */
  744. public function isDirty($property = null)
  745. {
  746. if ($property === null) {
  747. return !empty($this->_dirty);
  748. }
  749. return isset($this->_dirty[$property]);
  750. }
  751. /**
  752. * Gets the dirty properties.
  753. *
  754. * @return string[]
  755. */
  756. public function getDirty()
  757. {
  758. return array_keys($this->_dirty);
  759. }
  760. /**
  761. * Sets the entire entity as clean, which means that it will appear as
  762. * no properties being modified or added at all. This is an useful call
  763. * for an initial object hydration
  764. *
  765. * @return void
  766. */
  767. public function clean()
  768. {
  769. $this->_dirty = [];
  770. $this->_errors = [];
  771. $this->_invalid = [];
  772. $this->_original = [];
  773. }
  774. /**
  775. * Returns whether or not this entity has already been persisted.
  776. * This method can return null in the case there is no prior information on
  777. * the status of this entity.
  778. *
  779. * If called with a boolean it will set the known status of this instance,
  780. * true means that the instance is not yet persisted in the database, false
  781. * that it already is.
  782. *
  783. * @param bool|null $new true if it is known this instance was not yet persisted
  784. * @return bool Whether or not the entity has been persisted.
  785. */
  786. public function isNew($new = null)
  787. {
  788. if ($new === null) {
  789. return $this->_new;
  790. }
  791. $new = (bool)$new;
  792. if ($new) {
  793. foreach ($this->_properties as $k => $p) {
  794. $this->_dirty[$k] = true;
  795. }
  796. }
  797. return $this->_new = $new;
  798. }
  799. /**
  800. * Returns whether this entity has errors.
  801. *
  802. * @param bool $includeNested true will check nested entities for hasErrors()
  803. * @return bool
  804. */
  805. public function hasErrors($includeNested = true)
  806. {
  807. if (Hash::filter($this->_errors)) {
  808. return true;
  809. }
  810. if ($includeNested === false) {
  811. return false;
  812. }
  813. foreach ($this->_properties as $property) {
  814. if ($this->_readHasErrors($property)) {
  815. return true;
  816. }
  817. }
  818. return false;
  819. }
  820. /**
  821. * Returns all validation errors.
  822. *
  823. * @return array
  824. */
  825. public function getErrors()
  826. {
  827. $diff = array_diff_key($this->_properties, $this->_errors);
  828. return $this->_errors + (new Collection($diff))
  829. ->filter(function ($value) {
  830. return is_array($value) || $value instanceof EntityInterface;
  831. })
  832. ->map(function ($value) {
  833. return $this->_readError($value);
  834. })
  835. ->filter()
  836. ->toArray();
  837. }
  838. /**
  839. * Returns validation errors of a field
  840. *
  841. * @param string $field Field name to get the errors from
  842. * @return array
  843. */
  844. public function getError($field)
  845. {
  846. $errors = isset($this->_errors[$field]) ? $this->_errors[$field] : [];
  847. if ($errors) {
  848. return $errors;
  849. }
  850. return $this->_nestedErrors($field);
  851. }
  852. /**
  853. * Sets error messages to the entity
  854. *
  855. * ## Example
  856. *
  857. * ```
  858. * // Sets the error messages for multiple fields at once
  859. * $entity->setErrors(['salary' => ['message'], 'name' => ['another message']]);
  860. * ```
  861. *
  862. * @param array $fields The array of errors to set.
  863. * @param bool $overwrite Whether or not to overwrite pre-existing errors for $fields
  864. * @return $this
  865. */
  866. public function setErrors(array $fields, $overwrite = false)
  867. {
  868. if ($overwrite) {
  869. foreach ($fields as $f => $error) {
  870. $this->_errors[$f] = (array)$error;
  871. }
  872. return $this;
  873. }
  874. foreach ($fields as $f => $error) {
  875. $this->_errors += [$f => []];
  876. // String messages are appended to the list,
  877. // while more complex error structures need their
  878. // keys preserved for nested validator.
  879. if (is_string($error)) {
  880. $this->_errors[$f][] = $error;
  881. } else {
  882. foreach ($error as $k => $v) {
  883. $this->_errors[$f][$k] = $v;
  884. }
  885. }
  886. }
  887. return $this;
  888. }
  889. /**
  890. * Sets errors for a single field
  891. *
  892. * ### Example
  893. *
  894. * ```
  895. * // Sets the error messages for a single field
  896. * $entity->setError('salary', ['must be numeric', 'must be a positive number']);
  897. * ```
  898. *
  899. * @param string $field The field to get errors for, or the array of errors to set.
  900. * @param string|array $errors The errors to be set for $field
  901. * @param bool $overwrite Whether or not to overwrite pre-existing errors for $field
  902. * @return $this
  903. */
  904. public function setError($field, $errors, $overwrite = false)
  905. {
  906. if (is_string($errors)) {
  907. $errors = [$errors];
  908. }
  909. return $this->setErrors([$field => $errors], $overwrite);
  910. }
  911. /**
  912. * Sets the error messages for a field or a list of fields. When called
  913. * without the second argument it returns the validation
  914. * errors for the specified fields. If called with no arguments it returns
  915. * all the validation error messages stored in this entity and any other nested
  916. * entity.
  917. *
  918. * ### Example
  919. *
  920. * ```
  921. * // Sets the error messages for a single field
  922. * $entity->errors('salary', ['must be numeric', 'must be a positive number']);
  923. *
  924. * // Returns the error messages for a single field
  925. * $entity->getErrors('salary');
  926. *
  927. * // Returns all error messages indexed by field name
  928. * $entity->getErrors();
  929. *
  930. * // Sets the error messages for multiple fields at once
  931. * $entity->getErrors(['salary' => ['message'], 'name' => ['another message']);
  932. * ```
  933. *
  934. * When used as a setter, this method will return this entity instance for method
  935. * chaining.
  936. *
  937. * @deprecated 3.4.0 Use EntityTrait::setError(), EntityTrait::setErrors(), EntityTrait::getError() and EntityTrait::getErrors()
  938. * @param string|array|null $field The field to get errors for, or the array of errors to set.
  939. * @param string|array|null $errors The errors to be set for $field
  940. * @param bool $overwrite Whether or not to overwrite pre-existing errors for $field
  941. * @return array|$this
  942. */
  943. public function errors($field = null, $errors = null, $overwrite = false)
  944. {
  945. deprecationWarning(
  946. get_called_class() . '::errors() is deprecated. ' .
  947. 'Use setError()/getError() or setErrors()/getErrors() instead.'
  948. );
  949. if ($field === null) {
  950. return $this->getErrors();
  951. }
  952. if (is_string($field) && $errors === null) {
  953. return $this->getError($field);
  954. }
  955. if (!is_array($field)) {
  956. $field = [$field => $errors];
  957. }
  958. return $this->setErrors($field, $overwrite);
  959. }
  960. /**
  961. * Auxiliary method for getting errors in nested entities
  962. *
  963. * @param string $field the field in this entity to check for errors
  964. * @return array errors in nested entity if any
  965. */
  966. protected function _nestedErrors($field)
  967. {
  968. $path = explode('.', $field);
  969. // Only one path element, check for nested entity with error.
  970. if (count($path) === 1) {
  971. return $this->_readError($this->get($path[0]));
  972. }
  973. $entity = $this;
  974. $len = count($path);
  975. while ($len) {
  976. $part = array_shift($path);
  977. $len = count($path);
  978. $val = null;
  979. if ($entity instanceof EntityInterface) {
  980. $val = $entity->get($part);
  981. } elseif (is_array($entity)) {
  982. $val = isset($entity[$part]) ? $entity[$part] : false;
  983. }
  984. if (is_array($val) ||
  985. $val instanceof Traversable ||
  986. $val instanceof EntityInterface
  987. ) {
  988. $entity = $val;
  989. } else {
  990. $path[] = $part;
  991. break;
  992. }
  993. }
  994. if (count($path) <= 1) {
  995. return $this->_readError($entity, array_pop($path));
  996. }
  997. return [];
  998. }
  999. /**
  1000. * Reads if there are errors for one or many objects.
  1001. *
  1002. * @param mixed $object The object to read errors from.
  1003. * @return bool
  1004. */
  1005. protected function _readHasErrors($object)
  1006. {
  1007. if ($object instanceof EntityInterface && $object->hasErrors()) {
  1008. return true;
  1009. }
  1010. if (is_array($object)) {
  1011. foreach ($object as $value) {
  1012. if ($this->_readHasErrors($value)) {
  1013. return true;
  1014. }
  1015. }
  1016. }
  1017. return false;
  1018. }
  1019. /**
  1020. * Read the error(s) from one or many objects.
  1021. *
  1022. * @param array|\Cake\Datasource\EntityInterface $object The object to read errors from.
  1023. * @param string|null $path The field name for errors.
  1024. * @return array
  1025. */
  1026. protected function _readError($object, $path = null)
  1027. {
  1028. if ($path !== null && $object instanceof EntityInterface) {
  1029. return $object->getError($path);
  1030. }
  1031. if ($object instanceof EntityInterface) {
  1032. return $object->getErrors();
  1033. }
  1034. if (is_array($object)) {
  1035. $array = array_map(function ($val) {
  1036. if ($val instanceof EntityInterface) {
  1037. return $val->getErrors();
  1038. }
  1039. }, $object);
  1040. return array_filter($array);
  1041. }
  1042. return [];
  1043. }
  1044. /**
  1045. * Get a list of invalid fields and their data for errors upon validation/patching
  1046. *
  1047. * @return array
  1048. */
  1049. public function getInvalid()
  1050. {
  1051. return $this->_invalid;
  1052. }
  1053. /**
  1054. * Get a single value of an invalid field. Returns null if not set.
  1055. *
  1056. * @param string $field The name of the field.
  1057. * @return mixed
  1058. */
  1059. public function getInvalidField($field)
  1060. {
  1061. $value = isset($this->_invalid[$field]) ? $this->_invalid[$field] : null;
  1062. return $value;
  1063. }
  1064. /**
  1065. * Set fields as invalid and not patchable into the entity.
  1066. *
  1067. * This is useful for batch operations when one needs to get the original value for an error message after patching.
  1068. * This value could not be patched into the entity and is simply copied into the _invalid property for debugging purposes
  1069. * or to be able to log it away.
  1070. *
  1071. * @param array $fields The values to set.
  1072. * @param bool $overwrite Whether or not to overwrite pre-existing values for $field.
  1073. * @return $this
  1074. */
  1075. public function setInvalid(array $fields, $overwrite = false)
  1076. {
  1077. foreach ($fields as $field => $value) {
  1078. if ($overwrite === true) {
  1079. $this->_invalid[$field] = $value;
  1080. continue;
  1081. }
  1082. $this->_invalid += [$field => $value];
  1083. }
  1084. return $this;
  1085. }
  1086. /**
  1087. * Sets a field as invalid and not patchable into the entity.
  1088. *
  1089. * @param string $field The value to set.
  1090. * @param mixed $value The invalid value to be set for $field.
  1091. * @return $this
  1092. */
  1093. public function setInvalidField($field, $value)
  1094. {
  1095. $this->_invalid[$field] = $value;
  1096. return $this;
  1097. }
  1098. /**
  1099. * Sets a field as invalid and not patchable into the entity.
  1100. *
  1101. * This is useful for batch operations when one needs to get the original value for an error message after patching.
  1102. * This value could not be patched into the entity and is simply copied into the _invalid property for debugging purposes
  1103. * or to be able to log it away.
  1104. *
  1105. * @deprecated 3.5 Use getInvalid()/getInvalidField()/setInvalid() instead.
  1106. * @param string|array|null $field The field to get invalid value for, or the value to set.
  1107. * @param mixed|null $value The invalid value to be set for $field.
  1108. * @param bool $overwrite Whether or not to overwrite pre-existing values for $field.
  1109. * @return $this|mixed
  1110. */
  1111. public function invalid($field = null, $value = null, $overwrite = false)
  1112. {
  1113. deprecationWarning(
  1114. get_called_class() . '::invalid() is deprecated. ' .
  1115. 'Use setInvalid()/getInvalid()/getInvalidField() instead.'
  1116. );
  1117. if ($field === null) {
  1118. return $this->_invalid;
  1119. }
  1120. if (is_string($field) && $value === null) {
  1121. $value = isset($this->_invalid[$field]) ? $this->_invalid[$field] : null;
  1122. return $value;
  1123. }
  1124. if (!is_array($field)) {
  1125. $field = [$field => $value];
  1126. }
  1127. foreach ($field as $f => $value) {
  1128. if ($overwrite) {
  1129. $this->_invalid[$f] = $value;
  1130. continue;
  1131. }
  1132. $this->_invalid += [$f => $value];
  1133. }
  1134. return $this;
  1135. }
  1136. /**
  1137. * Stores whether or not a property value can be changed or set in this entity.
  1138. * The special property `*` can also be marked as accessible or protected, meaning
  1139. * that any other property specified before will take its value. For example
  1140. * `$entity->accessible('*', true)` means that any property not specified already
  1141. * will be accessible by default.
  1142. *
  1143. * You can also call this method with an array of properties, in which case they
  1144. * will each take the accessibility value specified in the second argument.
  1145. *
  1146. * ### Example:
  1147. *
  1148. * ```
  1149. * $entity->accessible('id', true); // Mark id as not protected
  1150. * $entity->accessible('author_id', false); // Mark author_id as protected
  1151. * $entity->accessible(['id', 'user_id'], true); // Mark both properties as accessible
  1152. * $entity->accessible('*', false); // Mark all properties as protected
  1153. * ```
  1154. *
  1155. * When called without the second param it will return whether or not the property
  1156. * can be set.
  1157. *
  1158. * ### Example:
  1159. *
  1160. * ```
  1161. * $entity->accessible('id'); // Returns whether it can be set or not
  1162. * ```
  1163. *
  1164. * @deprecated 3.4.0 Use EntityTrait::setAccess() and EntityTrait::isAccessible()
  1165. * @param string|array $property single or list of properties to change its accessibility
  1166. * @param bool|null $set true marks the property as accessible, false will
  1167. * mark it as protected.
  1168. * @return $this|bool
  1169. */
  1170. public function accessible($property, $set = null)
  1171. {
  1172. deprecationWarning(
  1173. get_called_class() . '::accessible() is deprecated. ' .
  1174. 'Use setAccess()/isAccessible() instead.'
  1175. );
  1176. if ($set === null) {
  1177. return $this->isAccessible($property);
  1178. }
  1179. return $this->setAccess($property, $set);
  1180. }
  1181. /**
  1182. * Stores whether or not a property value can be changed or set in this entity.
  1183. * The special property `*` can also be marked as accessible or protected, meaning
  1184. * that any other property specified before will take its value. For example
  1185. * `$entity->setAccess('*', true)` means that any property not specified already
  1186. * will be accessible by default.
  1187. *
  1188. * You can also call this method with an array of properties, in which case they
  1189. * will each take the accessibility value specified in the second argument.
  1190. *
  1191. * ### Example:
  1192. *
  1193. * ```
  1194. * $entity->setAccess('id', true); // Mark id as not protected
  1195. * $entity->setAccess('author_id', false); // Mark author_id as protected
  1196. * $entity->setAccess(['id', 'user_id'], true); // Mark both properties as accessible
  1197. * $entity->setAccess('*', false); // Mark all properties as protected
  1198. * ```
  1199. *
  1200. * @param string|array $property single or list of properties to change its accessibility
  1201. * @param bool $set true marks the property as accessible, false will
  1202. * mark it as protected.
  1203. * @return $this
  1204. */
  1205. public function setAccess($property, $set)
  1206. {
  1207. if ($property === '*') {
  1208. $this->_accessible = array_map(function ($p) use ($set) {
  1209. return (bool)$set;
  1210. }, $this->_accessible);
  1211. $this->_accessible['*'] = (bool)$set;
  1212. return $this;
  1213. }
  1214. foreach ((array)$property as $prop) {
  1215. $this->_accessible[$prop] = (bool)$set;
  1216. }
  1217. return $this;
  1218. }
  1219. /**
  1220. * Checks if a property is accessible
  1221. *
  1222. * ### Example:
  1223. *
  1224. * ```
  1225. * $entity->isAccessible('id'); // Returns whether it can be set or not
  1226. * ```
  1227. *
  1228. * @param string $property Property name to check
  1229. * @return bool
  1230. */
  1231. public function isAccessible($property)
  1232. {
  1233. $value = isset($this->_accessible[$property]) ?
  1234. $this->_accessible[$property] :
  1235. null;
  1236. return ($value === null && !empty($this->_accessible['*'])) || $value;
  1237. }
  1238. /**
  1239. * Returns the alias of the repository from which this entity came from.
  1240. *
  1241. * @return string
  1242. */
  1243. public function getSource()
  1244. {
  1245. return $this->_registryAlias;
  1246. }
  1247. /**
  1248. * Sets the source alias
  1249. *
  1250. * @param string $alias the alias of the repository
  1251. * @return $this
  1252. */
  1253. public function setSource($alias)
  1254. {
  1255. $this->_registryAlias = $alias;
  1256. return $this;
  1257. }
  1258. /**
  1259. * Returns the alias of the repository from which this entity came from.
  1260. *
  1261. * If called with no arguments, it returns the alias of the repository
  1262. * this entity came from if it is known.
  1263. *
  1264. * @deprecated 3.4.0 Use EntityTrait::getSource() and EntityTrait::setSource()
  1265. * @param string|null $alias the alias of the repository
  1266. * @return string|$this
  1267. */
  1268. public function source($alias = null)
  1269. {
  1270. deprecationWarning(
  1271. get_called_class() . '::source() is deprecated. ' .
  1272. 'Use setSource()/getSource() instead.'
  1273. );
  1274. if ($alias === null) {
  1275. return $this->getSource();
  1276. }
  1277. $this->setSource($alias);
  1278. return $this;
  1279. }
  1280. /**
  1281. * Returns a string representation of this object in a human readable format.
  1282. *
  1283. * @return string
  1284. */
  1285. public function __toString()
  1286. {
  1287. return json_encode($this, JSON_PRETTY_PRINT);
  1288. }
  1289. /**
  1290. * Returns an array that can be used to describe the internal state of this
  1291. * object.
  1292. *
  1293. * @return array
  1294. */
  1295. public function __debugInfo()
  1296. {
  1297. $properties = $this->_properties;
  1298. foreach ($this->_virtual as $field) {
  1299. $properties[$field] = $this->$field;
  1300. }
  1301. return $properties + [
  1302. '[new]' => $this->isNew(),
  1303. '[accessible]' => $this->_accessible,
  1304. '[dirty]' => $this->_dirty,
  1305. '[original]' => $this->_original,
  1306. '[virtual]' => $this->_virtual,
  1307. '[hasErrors]' => $this->hasErrors(),
  1308. '[errors]' => $this->_errors,
  1309. '[invalid]' => $this->_invalid,
  1310. '[repository]' => $this->_registryAlias
  1311. ];
  1312. }
  1313. }