|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Hateoas\Helper; |
|
4
|
|
|
|
|
5
|
|
|
use Hateoas\Configuration\RelationsRepository; |
|
6
|
|
|
use Hateoas\Configuration\Relation; |
|
7
|
|
|
use Hateoas\Configuration\Route; |
|
8
|
|
|
use Hateoas\Factory\LinkFactory; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* @author William Durand <[email protected]> |
|
12
|
|
|
*/ |
|
13
|
|
|
class LinkHelper |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var LinkFactory |
|
17
|
|
|
*/ |
|
18
|
|
|
private $linkFactory; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var RelationsRepository |
|
22
|
|
|
*/ |
|
23
|
|
|
private $relationsRepository; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @param LinkFactory $linkFactory |
|
27
|
|
|
* @param RelationsRepository $relationsRepository |
|
28
|
|
|
*/ |
|
29
|
|
|
public function __construct(LinkFactory $linkFactory, RelationsRepository $relationsRepository) |
|
30
|
|
|
{ |
|
31
|
|
|
$this->linkFactory = $linkFactory; |
|
32
|
|
|
$this->relationsRepository = $relationsRepository; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param object $object |
|
37
|
|
|
* @param string $rel |
|
38
|
|
|
* @param boolean $absolute |
|
39
|
|
|
* |
|
40
|
|
|
* @return string |
|
41
|
|
|
*/ |
|
42
|
|
|
public function getLinkHref($object, $rel, $absolute = false) |
|
43
|
|
|
{ |
|
44
|
|
|
foreach ($this->relationsRepository->getRelations($object) as $relation) { |
|
45
|
|
|
if ($rel === $relation->getName()) { |
|
46
|
|
|
$relation = $this->patchAbsolute($relation, $absolute); |
|
47
|
|
|
|
|
48
|
|
|
if (null !== $link = $this->linkFactory->createLink($object, $relation)) { |
|
49
|
|
|
return $link->getHref(); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
return null; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
private function patchAbsolute(Relation $relation, $absolute) |
|
58
|
|
|
{ |
|
59
|
|
|
$href = $relation->getHref(); |
|
60
|
|
|
|
|
61
|
|
|
if ($href instanceof Route) { |
|
62
|
|
|
$href = new Route( |
|
63
|
|
|
$href->getName(), |
|
64
|
|
|
$href->getParameters(), |
|
65
|
|
|
$absolute, |
|
66
|
|
|
$href->getGenerator() |
|
67
|
|
|
); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return new Relation( |
|
71
|
|
|
$relation->getName(), |
|
72
|
|
|
$href, |
|
73
|
|
|
$relation->getEmbedded(), |
|
74
|
|
|
$relation->getAttributes(), |
|
75
|
|
|
$relation->getExclusion() |
|
76
|
|
|
); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|