Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SerializedToJson.php
Go to the documentation of this file.
1 <?php
7 
10 
15 {
19  private $serialize;
20 
24  private $json;
25 
32  public function __construct(
33  Serialize $serialize,
34  Json $json
35  ) {
36  $this->serialize = $serialize;
37  $this->json = $json;
38  }
39 
47  public function convert($value)
48  {
49  if ($this->isValidJsonValue($value)) {
50  return $value;
51  }
52  return $this->encodeJson($this->unserializeValue($value));
53  }
54 
61  protected function isValidJsonValue($value)
62  {
63  if (in_array($value, ['null', 'false', '0', '""', '[]'])
64  || (json_decode($value) !== null && json_last_error() === JSON_ERROR_NONE)
65  ) {
66  return true;
67  }
68  //JSON last error reset
69  json_encode([]);
70  return false;
71  }
72 
80  protected function unserializeValue($value)
81  {
82  try {
83  set_error_handler(function ($errorNumber, $errorString) {
84  throw new DataConversionException($errorString, $errorNumber);
85  });
86  $value = $this->serialize->unserialize($value);
87  } catch (\Throwable $throwable) {
88  throw new DataConversionException($throwable->getMessage());
89  } finally {
90  restore_error_handler();
91  }
92  return $value;
93  }
94 
112  protected function encodeJson($value)
113  {
114  $storedPrecision = ini_get('precision');
115  $storedSerializePrecision = ini_get('serialize_precision');
116 
117  if (PHP_VERSION_ID < 70100) {
118  // In PHP version < 7.1.0 json_encode() uses EG(precision).
119  ini_set('precision', 17);
120  } else {
121  // In PHP version >= 7.1.0 json_encode() uses PG(serialize_precision).
122  ini_set('serialize_precision', 17);
123  }
124 
125  $value = $this->json->serialize($value);
126 
127  ini_set('precision', $storedPrecision);
128  ini_set('serialize_precision', $storedSerializePrecision);
129 
130  if (json_last_error()) {
131  throw new DataConversionException(json_last_error_msg());
132  }
133  return $value;
134  }
135 }
ini_set($varName, $newValue)
$value
Definition: gender.phtml:16