GenericLinkProvider.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\WebLink;
  11. use Psr\Link\EvolvableLinkProviderInterface;
  12. use Psr\Link\LinkInterface;
  13. class GenericLinkProvider implements EvolvableLinkProviderInterface
  14. {
  15. /**
  16. * @var LinkInterface[]
  17. */
  18. private $links = [];
  19. /**
  20. * @param LinkInterface[] $links
  21. */
  22. public function __construct(array $links = [])
  23. {
  24. $that = $this;
  25. foreach ($links as $link) {
  26. $that = $that->withLink($link);
  27. }
  28. $this->links = $that->links;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function getLinks(): array
  34. {
  35. return array_values($this->links);
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public function getLinksByRel($rel): array
  41. {
  42. $links = [];
  43. foreach ($this->links as $link) {
  44. if (\in_array($rel, $link->getRels())) {
  45. $links[] = $link;
  46. }
  47. }
  48. return $links;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. *
  53. * @return static
  54. */
  55. public function withLink(LinkInterface $link)
  56. {
  57. $that = clone $this;
  58. $that->links[spl_object_id($link)] = $link;
  59. return $that;
  60. }
  61. /**
  62. * {@inheritdoc}
  63. *
  64. * @return static
  65. */
  66. public function withoutLink(LinkInterface $link)
  67. {
  68. $that = clone $this;
  69. unset($that->links[spl_object_id($link)]);
  70. return $that;
  71. }
  72. }