JsonType.php 1.77 KB
Newer Older
1 2 3 4 5
<?php

namespace Doctrine\DBAL\Types;

use Doctrine\DBAL\Platforms\AbstractPlatform;
6 7 8 9 10 11 12
use const JSON_ERROR_NONE;
use function is_resource;
use function json_decode;
use function json_encode;
use function json_last_error;
use function json_last_error_msg;
use function stream_get_contents;
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

/**
 * Type generating json objects values
 */
class JsonType extends Type
{
    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return $platform->getJsonTypeDeclarationSQL($fieldDeclaration);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
32
        if ($value === null) {
33 34 35
            return null;
        }

36 37
        $encoded = json_encode($value);

38
        if (json_last_error() !== JSON_ERROR_NONE) {
39
            throw ConversionException::conversionFailedSerialization($value, 'json', json_last_error_msg());
40 41 42
        }

        return $encoded;
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null || $value === '') {
            return null;
        }

        if (is_resource($value)) {
            $value = stream_get_contents($value);
        }

        $val = json_decode($value, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw ConversionException::conversionFailed($value, $this->getName());
        }

        return $val;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
72
        return Types::JSON;
73 74 75 76 77 78 79
    }

    /**
     * {@inheritdoc}
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
80
        return ! $platform->hasNativeJsonType();
81 82
    }
}