Base64ToImageTransformer   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 3
dl 0
loc 35
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A transform() 0 8 3
A reverseTransform() 0 21 3
1
<?php
2
3
namespace Presta\ImageBundle\Form\DataTransformer;
4
5
use Presta\ImageBundle\Helper\Base64Helper;
6
use Symfony\Component\Form\DataTransformerInterface;
7
use Symfony\Component\HttpFoundation\File\File;
8
use Symfony\Component\HttpFoundation\File\UploadedFile;
9
10
class Base64ToImageTransformer implements DataTransformerInterface
11
{
12
    use Base64Helper;
13
14
    public function transform($value): array
15
    {
16
        if (!$value instanceof File || false === $value->getRealPath()) {
17
            return ['base64' => null];
18
        }
19
20
        return ['base64' => $this->contentToBase64($value->getRealPath())];
21
    }
22
23
    public function reverseTransform($value): ?UploadedFile
24
    {
25
        if (!isset($value['base64']) || !$value['base64']) {
26
            return null;
27
        }
28
29
        $prefixLength = strpos($value['base64'], 'base64,') + 7;
30
        $base64 = substr($value['base64'], $prefixLength);
31
32
        $filePath = tempnam(sys_get_temp_dir(), 'UploadedFile');
33
        $file = fopen($filePath, 'w');
34
        stream_filter_append($file, 'convert.base64-decode');
35
        fwrite($file, $base64);
36
        $metadata = stream_get_meta_data($file);
37
        $path = $metadata['uri'];
38
        fclose($file);
39
        $mimeType = mime_content_type($path);
40
        $extension = str_replace('image/', '', $mimeType);
41
42
        return new UploadedFile($path, uniqid() . '.' . $extension, $mimeType, null, true);
43
    }
44
}
45