Passed
Push — master ( bc7cfa...4b81f5 )
by Dominik
02:00
created

CallbackLinkNormalizer::normalizeLink()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 12
cts 12
cp 1
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 13
nc 4
nop 3
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Normalizer;
6
7
use Chubbyphp\Serialization\SerializerLogicException;
8
use Psr\Link\LinkInterface;
9
10
final class CallbackLinkNormalizer implements LinkNormalizerInterface
11
{
12
    /**
13
     * @var callable
14
     */
15
    private $callback;
16
17
    /**
18
     * @param callable $callback
19
     */
20 3
    public function __construct(callable $callback)
21
    {
22 3
        $this->callback = $callback;
23 3
    }
24
25
    /**
26
     * @param string                     $path
27
     * @param object                     $object
28
     * @param NormalizerContextInterface $context
29
     *
30
     * @return array|null
31
     *
32
     * @throws SerializerLogicException
33
     */
34 3
    public function normalizeLink(string $path, $object, NormalizerContextInterface $context)
35
    {
36 3
        $callback = $this->callback;
37
38 3
        $link = $callback($path, $object, $context);
39
40 3
        if (null === $link) {
41 1
            return null;
42
        }
43
44 2
        if (!$link instanceof LinkInterface) {
45 1
            $type = is_object($link) ? get_class($link) : gettype($link);
46
47 1
            throw SerializerLogicException::createInvalidLinkTypeReturned($path, $type);
48
        }
49
50
        return [
51 1
            'href' => $link->getHref(),
52 1
            'templated' => $link->isTemplated(),
53 1
            'rel' => $link->getRels(),
54 1
            'attributes' => $link->getAttributes(),
55
        ];
56
    }
57
}
58