Passed
Pull Request — master (#16)
by Paweł
03:04
created

FileHrefProcessor::process()   B

Complexity

Conditions 7
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 9
nc 2
nop 2
dl 0
loc 16
rs 8.8333
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 function is_array;
9
use Symfony\Component\HttpFoundation\RequestStack;
10
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;
11
12
final class FileHrefProcessor
13
{
14
    private $uploaderHelper;
15
    private $requestStack;
16
17
    private const SUPPORTED_KEYS = [
18
        'file_name' => [
19
            'file' => 'file',
20
            'property' => 'download',
21
        ],
22
        'cover_image_name' => [
23
            'file' => 'coverImageFile',
24
            'property' => 'cover_image_url',
25
        ],
26
        'picture' => [
27
            'file' => 'pictureFile',
28
            'property' => 'picture',
29
        ],
30
    ];
31
32
    public function __construct(
33
        UploaderHelper $uploaderHelper,
34
        RequestStack $requestStack
35
    ) {
36
        $this->uploaderHelper = $uploaderHelper;
37
        $this->requestStack = $requestStack;
38
    }
39
40
    public function process(object $object, array $data): array
41
    {
42
        if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
43
            foreach ($data as $key => $value) {
44
                if (array_key_exists($key, self::SUPPORTED_KEYS)) {
45
                    $filePath = $this->uploaderHelper->asset($object, self::SUPPORTED_KEYS[$key]['file']);
46
                    $currentRequest = $this->requestStack->getCurrentRequest();
47
                    if (null !== $filePath && null !== $currentRequest && false === strpos($filePath, '://')) {
48
                        $filePath = $currentRequest->getSchemeAndHttpHost().$filePath;
49
                    }
50
                    $data['href'][self::SUPPORTED_KEYS[$key]['property']] = $filePath;
51
                }
52
            }
53
        }
54
55
        return $data;
56
    }
57
}
58