Completed
Branch master (973d74)
by Nicolas
27:46 queued 17:55
created

Base64ToImageTransformer::transform()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Presta\ImageBundle\Form\DataTransformer;
4
5
use Symfony\Component\Form\DataTransformerInterface;
6
use Symfony\Component\HttpFoundation\File\UploadedFile;
7
8
/**
9
 * @author Thomas Courthial <[email protected]>
10
 */
11
class Base64ToImageTransformer implements DataTransformerInterface
12
{
13
    /**
14
     * {@inheritdoc}
15
     */
16
    public function transform($value)
17
    {
18
        if (!$value instanceof UploadedFile) {
19
            return null;
20
        }
21
22
        return file_get_contents($value->getRealPath());
23
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function reverseTransform($value)
29
    {
30
        if (null === $value['base64']) {
31
            return null;
32
        }
33
34
        $base64 = str_replace('data:image/png;base64,', '', $value['base64']);
35
36
        $filePath = tempnam(sys_get_temp_dir(), 'UploadedFile');
37
        $file = fopen($filePath, 'w');
38
        stream_filter_append($file, 'convert.base64-decode');
39
        fwrite($file, $base64);
40
        $meta_data = stream_get_meta_data($file);
41
        $path = $meta_data['uri'];
42
        fclose($file);
43
44
        // Force "test" parameters to true to bypass http file validation (as the file isn't a "real" uploaded file)
45
        return new UploadedFile($path, uniqid(), null, null, null, true);
46
    }
47
}
48