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;
Sergei Morozov's avatar
Sergei Morozov committed
7
use function assert;
8 9 10 11 12
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
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

/**
 * 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)
    {
32
        if ($value === null) {
Steve Müller's avatar
Steve Müller committed
33 34 35 36
            return null;
        }

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

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

        return $value;
    }

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

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