BigIntType.php
3 years ago
DateTimeTzToStringType.php
3 years ago
JsonOrSerializedType.php
3 years ago
JsonType.php
3 years ago
SerializedArrayType.php
3 years ago
index.php
3 years ago
JsonType.php
63 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Doctrine\Types; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoetVendor\Doctrine\DBAL\Platforms\AbstractPlatform; |
| 9 | use MailPoetVendor\Doctrine\DBAL\Types\Type; |
| 10 | |
| 11 | class JsonType extends Type { |
| 12 | const NAME = 'json'; |
| 13 | |
| 14 | public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) { |
| 15 | return $platform->getJsonTypeDeclarationSQL($fieldDeclaration); |
| 16 | } |
| 17 | |
| 18 | public function convertToDatabaseValue($value, AbstractPlatform $platform) { |
| 19 | if ($value === null) { |
| 20 | return null; |
| 21 | } |
| 22 | |
| 23 | $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES; |
| 24 | if (defined('JSON_PRESERVE_ZERO_FRACTION')) { |
| 25 | $flags |= JSON_PRESERVE_ZERO_FRACTION; // phpcs:ignore |
| 26 | } |
| 27 | |
| 28 | $encoded = json_encode($value, $flags); |
| 29 | $this->handleErrors(); |
| 30 | return $encoded; |
| 31 | } |
| 32 | |
| 33 | public function convertToPHPValue($value, AbstractPlatform $platform) { |
| 34 | if ($value === null || $value === '') { |
| 35 | return null; |
| 36 | } |
| 37 | |
| 38 | if (is_resource($value)) { |
| 39 | $value = stream_get_contents($value); |
| 40 | } |
| 41 | |
| 42 | $value = mb_convert_encoding((string)$value, 'UTF-8', 'UTF-8'); // sanitize invalid utf8 |
| 43 | $decoded = json_decode($value, true); |
| 44 | $this->handleErrors(); |
| 45 | return $decoded; |
| 46 | } |
| 47 | |
| 48 | public function getName() { |
| 49 | return self::NAME; |
| 50 | } |
| 51 | |
| 52 | public function requiresSQLCommentHint(AbstractPlatform $platform) { |
| 53 | return !$platform->hasNativeJsonType(); |
| 54 | } |
| 55 | |
| 56 | private function handleErrors() { |
| 57 | $error = json_last_error(); |
| 58 | if ($error !== JSON_ERROR_NONE) { |
| 59 | throw new \RuntimeException('Error when parsing JSON database value: "' . json_last_error_msg() . '"', $error); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 |