WorkflowActionNormalizer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * (c) 2019, Wesley O. Nichols
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Wesnick\WorkflowBundle\Serializer;
13
14
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
15
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
16
use Wesnick\WorkflowBundle\Model\Action;
17
use Wesnick\WorkflowBundle\Model\EntryPoint;
18
19
/**
20
 * Class WorkflowActionNormalizer.
21
 *
22
 * @author Wesley O. Nichols <[email protected]>
23
 */
24
class WorkflowActionNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
25
{
26
    private $customNormalizer;
27
28
    public function __construct(NormalizerInterface $customNormalizer)
29
    {
30
        $this->customNormalizer = $customNormalizer;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function supportsNormalization($data, $format = null): bool
37
    {
38
        return $data instanceof Action || $data instanceof EntryPoint;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function hasCacheableSupportsMethod(): bool
45
    {
46
        return true;
47
    }
48
49
    public function normalize($object, $format = null, array $context = [])
50
    {
51
        if ($object instanceof Action) {
52
            $resourceClass = get_class($object);
53
            $resourceShortName = substr($resourceClass, strrpos($resourceClass, '\\') + 1);
54
55
            return [
56
                    '@context' => 'http://schema.org',
57
                    '@type' => $resourceShortName,
58
            ] + array_filter($this->customNormalizer->normalize($object, 'json'));
59
        } elseif ($object instanceof EntryPoint) {
60
            $data = array_filter($this->customNormalizer->normalize($object, 'json'));
61
            // EntryPoint can be represented as an object or a string in case only url property is present
62
            if (1 === count($data) && array_key_exists('url', $data)) {
63
                return $data['url'];
64
            }
65
66
            return $data;
67
        }
68
69
        return null;
70
    }
71
}
72