ArrayType.php 1.59 KB
Newer Older
1 2
<?php

3 4
namespace Doctrine\DBAL\Types;

5
use Doctrine\DBAL\Platforms\AbstractPlatform;
6
use function is_resource;
7
use function restore_error_handler;
8
use function serialize;
9
use function set_error_handler;
10 11
use function stream_get_contents;
use function unserialize;
12

13
/**
14
 * Type that maps a PHP array to a clob SQL type.
15
 */
16
class ArrayType extends Type
17
{
Benjamin Morel's avatar
Benjamin Morel committed
18 19 20 21
    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
22
    {
23
        return $platform->getClobTypeDeclarationSQL($fieldDeclaration);
24 25
    }

Benjamin Morel's avatar
Benjamin Morel committed
26 27 28 29
    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
30
    {
31
        // @todo 3.0 - $value === null check to save real NULL in database
32 33 34
        return serialize($value);
    }

Benjamin Morel's avatar
Benjamin Morel committed
35 36 37 38
    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
39
    {
40 41
        if ($value === null) {
            return null;
42 43
        }

44
        $value = is_resource($value) ? stream_get_contents($value) : $value;
Benjamin Morel's avatar
Benjamin Morel committed
45

46
        set_error_handler(function (int $code, string $message) : bool {
47 48 49 50 51 52 53 54
            throw ConversionException::conversionFailedUnserialization($this->getName(), $message);
        });

        try {
            return unserialize($value);
        } finally {
            restore_error_handler();
        }
55 56
    }

Benjamin Morel's avatar
Benjamin Morel committed
57 58 59
    /**
     * {@inheritdoc}
     */
60 61
    public function getName()
    {
62
        return Types::ARRAY;
63
    }
64

Benjamin Morel's avatar
Benjamin Morel committed
65 66 67
    /**
     * {@inheritdoc}
     */
68 69 70 71
    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
Benjamin Eberlei's avatar
Benjamin Eberlei committed
72
}