1<?php
2
3namespace Doctrine\DBAL\Types;
4
5use Doctrine\DBAL\ParameterType;
6use Doctrine\DBAL\Platforms\AbstractPlatform;
7use function assert;
8use function fopen;
9use function fseek;
10use function fwrite;
11use function is_resource;
12use function is_string;
13
14/**
15 * Type that maps an SQL BLOB to a PHP resource stream.
16 */
17class BlobType extends Type
18{
19    /**
20     * {@inheritdoc}
21     */
22    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
23    {
24        return $platform->getBlobTypeDeclarationSQL($fieldDeclaration);
25    }
26
27    /**
28     * {@inheritdoc}
29     */
30    public function convertToPHPValue($value, AbstractPlatform $platform)
31    {
32        if ($value === null) {
33            return null;
34        }
35
36        if (is_string($value)) {
37            $fp = fopen('php://temp', 'rb+');
38            assert(is_resource($fp));
39            fwrite($fp, $value);
40            fseek($fp, 0);
41            $value = $fp;
42        }
43
44        if (! is_resource($value)) {
45            throw ConversionException::conversionFailed($value, Types::BLOB);
46        }
47
48        return $value;
49    }
50
51    /**
52     * {@inheritdoc}
53     */
54    public function getName()
55    {
56        return Types::BLOB;
57    }
58
59    /**
60     * {@inheritdoc}
61     */
62    public function getBindingType()
63    {
64        return ParameterType::LARGE_OBJECT;
65    }
66}
67