1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Mikemirten\Component\JsonApi\Hydrator\Extension; |
5
|
|
|
|
6
|
|
|
use Mikemirten\Component\JsonApi\Document\Behaviour\LinksAwareInterface; |
7
|
|
|
use Mikemirten\Component\JsonApi\Document\LinkObject; |
8
|
|
|
use Mikemirten\Component\JsonApi\Exception\InvalidDocumentException; |
9
|
|
|
use Mikemirten\Component\JsonApi\Hydrator\DocumentHydrator; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* "links" object extension |
13
|
|
|
* |
14
|
|
|
* @see http://jsonapi.org/format/#document-links |
15
|
|
|
* |
16
|
|
|
* @package Mikemirten\Component\JsonApi\Hydrator\Extension |
17
|
|
|
*/ |
18
|
|
|
class LinksExtension implements ExtensionInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* {@inheritdoc} |
22
|
|
|
*/ |
23
|
2 |
View Code Duplication |
public function hydrate($object, $source, DocumentHydrator $hydrator) |
|
|
|
|
24
|
|
|
{ |
25
|
2 |
|
if (! $object instanceof LinksAwareInterface) { |
26
|
1 |
|
throw new InvalidDocumentException(sprintf( |
27
|
1 |
|
'Given instance of "%s" does not implements "%s"', |
28
|
1 |
|
get_class($object), |
29
|
1 |
|
LinksAwareInterface::class |
30
|
|
|
)); |
31
|
|
|
} |
32
|
|
|
|
33
|
1 |
|
foreach ($source as $name => $content) |
34
|
|
|
{ |
35
|
1 |
|
$link = $this->createLink($content, $hydrator); |
36
|
|
|
|
37
|
1 |
|
$object->setLink($name, $link); |
38
|
|
|
} |
39
|
1 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Create link |
43
|
|
|
* |
44
|
|
|
* @param mixed $source |
45
|
|
|
* @param DocumentHydrator $hydrator |
46
|
|
|
* @return LinkObject |
47
|
|
|
*/ |
48
|
1 |
|
protected function createLink($source, DocumentHydrator $hydrator): LinkObject |
49
|
|
|
{ |
50
|
1 |
|
if (is_string($source)) { |
51
|
1 |
|
return new LinkObject($source); |
52
|
|
|
} |
53
|
|
|
|
54
|
1 |
|
if (! isset($source->href)) { |
55
|
|
|
throw new InvalidDocumentException('Link must be a string or an object contains "href" attribute.'); |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
$link = new LinkObject($source->href); |
59
|
|
|
|
60
|
1 |
|
$hydrator->hydrateObject($link, $source); |
61
|
|
|
|
62
|
1 |
|
return $link; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* {@inheritdoc} |
67
|
|
|
*/ |
68
|
1 |
|
public function supports(): array |
69
|
|
|
{ |
70
|
1 |
|
return ['links']; |
71
|
|
|
} |
72
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.