Properties.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * Validates properties of entity (\Magento\Framework\DataObject).
  4. *
  5. * Copyright © Magento, Inc. All rights reserved.
  6. * See COPYING.txt for license details.
  7. */
  8. namespace Magento\Framework\Validator\Entity;
  9. use Magento\Framework\DataObject;
  10. use Magento\Framework\Model\AbstractModel;
  11. class Properties extends \Magento\Framework\Validator\AbstractValidator
  12. {
  13. /**
  14. * @var string[]
  15. */
  16. protected $_readOnlyProperties = [];
  17. /**
  18. * Set read-only properties.
  19. *
  20. * @param string[] $readOnlyProperties
  21. * @return void
  22. */
  23. public function setReadOnlyProperties(array $readOnlyProperties)
  24. {
  25. $this->_readOnlyProperties = $readOnlyProperties;
  26. }
  27. /**
  28. * Successful if $value is \Magento\Framework\Model\AbstractModel an all condition are fulfilled.
  29. *
  30. * If read-only properties are set than $value mustn't have changes in them.
  31. *
  32. * @param AbstractModel $value
  33. * @return bool
  34. * @throws \InvalidArgumentException when $value is not instanceof \Magento\Framework\DataObject
  35. * @api
  36. */
  37. public function isValid($value)
  38. {
  39. $this->_clearMessages();
  40. if (!$value instanceof AbstractModel) {
  41. throw new \InvalidArgumentException('Instance of \Magento\Framework\Model\AbstractModel is expected.');
  42. }
  43. if ($this->_readOnlyProperties) {
  44. if (!$value->hasDataChanges()) {
  45. return true;
  46. }
  47. foreach ($this->_readOnlyProperties as $property) {
  48. if ($this->_hasChanges($value->getData($property), $value->getOrigData($property))) {
  49. $this->_messages[__CLASS__] = [
  50. (string)new \Magento\Framework\Phrase("Read-only property cannot be changed.")
  51. ];
  52. break;
  53. }
  54. }
  55. }
  56. return !count($this->_messages);
  57. }
  58. /**
  59. * Compare two values as numbers and as other types
  60. *
  61. * @param mixed $firstValue
  62. * @param mixed $secondValue
  63. * @return bool
  64. */
  65. protected function _hasChanges($firstValue, $secondValue)
  66. {
  67. if ($firstValue === $secondValue || $firstValue == $secondValue && is_numeric(
  68. $firstValue
  69. ) && is_numeric(
  70. $secondValue
  71. )
  72. ) {
  73. return false;
  74. }
  75. return true;
  76. }
  77. }