Completed
Push — master ( 08acda...fe47f9 )
by Paweł
11s
created

FileHrefProcessor::process()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 8
nc 4
nop 2
dl 0
loc 14
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Serializer\Processor;
6
7
use function array_key_exists;
8
use Symfony\Component\HttpFoundation\RequestStack;
9
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;
10
11
final class FileHrefProcessor
12
{
13
    private $uploaderHelper;
14
    private $requestStack;
15
16
    private const SUPPORTED_KEYS = [
17
        'file_name' => [
18
            'file' => 'file',
19
            'property' => 'download',
20
        ],
21
        'cover_image_name' => [
22
            'file' => 'coverImageFile',
23
            'property' => 'cover_image_url',
24
        ],
25
        'picture' => [
26
            'file' => 'pictureFile',
27
            'property' => 'picture',
28
        ],
29
    ];
30
31
    public function __construct(
32
        UploaderHelper $uploaderHelper,
33
        RequestStack $requestStack
34
    ) {
35
        $this->uploaderHelper = $uploaderHelper;
36
        $this->requestStack = $requestStack;
37
    }
38
39
    public function process(object $object, array $data): array
40
    {
41
        foreach ($data as $key => $value) {
42
            if (array_key_exists($key, self::SUPPORTED_KEYS)) {
43
                $filePath = $this->uploaderHelper->asset($object, self::SUPPORTED_KEYS[$key]['file']);
44
                $currentRequest = $this->requestStack->getCurrentRequest();
45
                if (null !== $filePath && null !== $currentRequest && false === strpos($filePath, '://')) {
46
                    $filePath = $currentRequest->getSchemeAndHttpHost().$filePath;
47
                }
48
                $data['href'][self::SUPPORTED_KEYS[$key]['property']] = $filePath;
49
            }
50
        }
51
52
        return $data;
53
    }
54
}
55