Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
JsonEncoded.php
Go to the documentation of this file.
1 <?php
7 
9 
16 class JsonEncoded extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
17 {
21  private $jsonSerializer;
22 
28  public function __construct(Json $jsonSerializer)
29  {
30  $this->jsonSerializer = $jsonSerializer;
31  }
32 
40  public function beforeSave($object)
41  {
42  // parent::beforeSave() is not called intentionally
43  $attrCode = $this->getAttribute()->getAttributeCode();
44  if ($object->hasData($attrCode) && !$this->isJsonEncoded($object->getData($attrCode))) {
45  $object->setData($attrCode, $this->jsonSerializer->serialize($object->getData($attrCode)));
46  }
47  return $this;
48  }
49 
57  public function afterLoad($object)
58  {
59  parent::afterLoad($object);
60  $attrCode = $this->getAttribute()->getAttributeCode();
61  $object->setData($attrCode, $this->jsonSerializer->unserialize($object->getData($attrCode) ?: '{}'));
62  return $this;
63  }
64 
71  private function isJsonEncoded($value): bool
72  {
73  $result = is_string($value);
74  if ($result) {
75  try {
76  $this->jsonSerializer->unserialize($value);
77  } catch (\InvalidArgumentException $e) {
78  $result = false;
79  }
80  }
81 
82  return $result;
83  }
84 }
$value
Definition: gender.phtml:16