BinaryType.php 1.33 KB
Newer Older
Steve Müller's avatar
Steve Müller committed
1 2 3 4
<?php

namespace Doctrine\DBAL\Types;

5
use Doctrine\DBAL\ParameterType;
Steve Müller's avatar
Steve Müller committed
6
use Doctrine\DBAL\Platforms\AbstractPlatform;
7

Sergei Morozov's avatar
Sergei Morozov committed
8
use function assert;
9 10 11 12 13
use function fopen;
use function fseek;
use function fwrite;
use function is_resource;
use function is_string;
Steve Müller's avatar
Steve Müller committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

/**
 * Type that maps ab SQL BINARY/VARBINARY to a PHP resource stream.
 */
class BinaryType extends Type
{
    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return $platform->getBinaryTypeDeclarationSQL($fieldDeclaration);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
33
        if ($value === null) {
Steve Müller's avatar
Steve Müller committed
34 35 36 37
            return null;
        }

        if (is_string($value)) {
38
            $fp = fopen('php://temp', 'rb+');
Sergei Morozov's avatar
Sergei Morozov committed
39
            assert(is_resource($fp));
40 41 42
            fwrite($fp, $value);
            fseek($fp, 0);
            $value = $fp;
Steve Müller's avatar
Steve Müller committed
43 44
        }

45
        if (! is_resource($value)) {
46
            throw ConversionException::conversionFailed($value, Types::BINARY);
Steve Müller's avatar
Steve Müller committed
47 48 49 50 51 52 53 54 55 56
        }

        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
57
        return Types::BINARY;
Steve Müller's avatar
Steve Müller committed
58 59 60 61 62 63 64
    }

    /**
     * {@inheritdoc}
     */
    public function getBindingType()
    {
65
        return ParameterType::BINARY;
Steve Müller's avatar
Steve Müller committed
66 67
    }
}