Completed
Push — master ( 20a8c8...036714 )
by Paweł
26s queued 11s
created

CoverImageSerializer   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 35
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A supportsNormalization() 0 3 2
A normalize() 0 14 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Serializer;
6
7
use App\Model\CourseInterface;
8
use App\Model\LessonInterface;
9
use function array_key_exists;
10
use function is_array;
11
use Symfony\Component\HttpFoundation\RequestStack;
12
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
13
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
14
use Vich\UploaderBundle\Templating\Helper\UploaderHelper;
15
16
class CoverImageSerializer implements NormalizerInterface
17
{
18
    private $uploaderHelper;
19
    private $normalizer;
20
    private $requestStack;
21
22
    public function __construct(
23
        UploaderHelper $uploaderHelper,
24
        ObjectNormalizer $normalizer,
25
        RequestStack $requestStack
26
    ) {
27
        $this->uploaderHelper = $uploaderHelper;
28
        $this->normalizer = $normalizer;
29
        $this->requestStack = $requestStack;
30
    }
31
32
    public function normalize($object, $format = null, array $context = [])
33
    {
34
        $data = $this->normalizer->normalize($object, $format, $context);
35
36
        if (is_array($data) && array_key_exists('cover_image_name', $data)) {
37
            $imagePath = $this->uploaderHelper->asset($object, 'coverImageFile');
38
            $currentRequest = $this->requestStack->getCurrentRequest();
39
            if (null !== $imagePath && null !== $currentRequest && false === strpos($imagePath, '://')) {
40
                $imagePath = $currentRequest->getSchemeAndHttpHost().$imagePath;
41
            }
42
            $data['href']['coverImageUrl'] = $imagePath;
43
        }
44
45
        return $data;
46
    }
47
48
    public function supportsNormalization($data, $format = null): bool
49
    {
50
        return $data instanceof CourseInterface || $data instanceof LessonInterface;
51
    }
52
}
53