JsonEncoded.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Eav\Model\Entity\Attribute\Backend;
  7. use Magento\Framework\Serialize\Serializer\Json;
  8. /**
  9. * Backend model for attribute that stores structures in json format
  10. *
  11. * @api
  12. * @since 101.0.0
  13. */
  14. class JsonEncoded extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
  15. {
  16. /**
  17. * @var Json
  18. */
  19. private $jsonSerializer;
  20. /**
  21. * ArrayBackend constructor.
  22. *
  23. * @param Json $jsonSerializer
  24. */
  25. public function __construct(Json $jsonSerializer)
  26. {
  27. $this->jsonSerializer = $jsonSerializer;
  28. }
  29. /**
  30. * Encode before saving
  31. *
  32. * @param \Magento\Framework\DataObject $object
  33. * @return $this
  34. * @since 101.0.0
  35. */
  36. public function beforeSave($object)
  37. {
  38. // parent::beforeSave() is not called intentionally
  39. $attrCode = $this->getAttribute()->getAttributeCode();
  40. if ($object->hasData($attrCode) && !$this->isJsonEncoded($object->getData($attrCode))) {
  41. $object->setData($attrCode, $this->jsonSerializer->serialize($object->getData($attrCode)));
  42. }
  43. return $this;
  44. }
  45. /**
  46. * Decode after loading
  47. *
  48. * @param \Magento\Framework\DataObject $object
  49. * @return $this
  50. * @since 101.0.0
  51. */
  52. public function afterLoad($object)
  53. {
  54. parent::afterLoad($object);
  55. $attrCode = $this->getAttribute()->getAttributeCode();
  56. $object->setData($attrCode, $this->jsonSerializer->unserialize($object->getData($attrCode) ?: '{}'));
  57. return $this;
  58. }
  59. /**
  60. * Returns true if given value is a valid json value, and false otherwise.
  61. *
  62. * @param string|int|float|bool|array|null $value
  63. * @return bool
  64. */
  65. private function isJsonEncoded($value): bool
  66. {
  67. $result = is_string($value);
  68. if ($result) {
  69. try {
  70. $this->jsonSerializer->unserialize($value);
  71. } catch (\InvalidArgumentException $e) {
  72. $result = false;
  73. }
  74. }
  75. return $result;
  76. }
  77. }