-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkProvider.php
62 lines (54 loc) · 1.63 KB
/
LinkProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\Link;
use InvalidArgumentException;
use Psr\Link\LinkInterface;
use Psr\Link\LinkProviderInterface;
/**
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class LinkProvider implements LinkProviderInterface
{
protected array $links = [];
public function __construct(
array $links = [],
) {
foreach ($links as $link) {
if (!$link instanceof LinkInterface) {
throw new InvalidArgumentException('At least one link does not implement LinkInterface');
}
$this->links[spl_object_hash($link)] = $link;
}
}
/**
* Returns an iterable of LinkInterface objects.
*
* The iterable may be an array or any PHP \Traversable object. If no links
* are available, an empty array or \Traversable MUST be returned.
*
* @return iterable<LinkInterface>
*/
public function getLinks(): iterable
{
return array_values($this->links);
}
/**
* Returns an iterable of LinkInterface objects that have a specific relationship.
*
* The iterable may be an array or any PHP \Traversable object. If no links
* with that relationship are available, an empty array or \Traversable MUST be returned.
*
* @param string $rel
* The relationship name for which to retrieve links.
*
* @return iterable<LinkInterface>
*/
public function getLinksByRel(string $rel): iterable
{
foreach ($this->links as $link) {
if (in_array($rel, $link->getRels())) {
yield $link;
}
}
}
}