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

CallbackLinkNormalizer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
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