HttpHeaderSerializer.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\LinkInterface;
  12. /**
  13. * Serializes a list of Link instances to an HTTP Link header.
  14. *
  15. * @see https://tools.ietf.org/html/rfc5988
  16. *
  17. * @author Kévin Dunglas <dunglas@gmail.com>
  18. */
  19. final class HttpHeaderSerializer
  20. {
  21. /**
  22. * Builds the value of the "Link" HTTP header.
  23. *
  24. * @param LinkInterface[]|\Traversable $links
  25. */
  26. public function serialize(iterable $links): ?string
  27. {
  28. $elements = [];
  29. foreach ($links as $link) {
  30. if ($link->isTemplated()) {
  31. continue;
  32. }
  33. $attributesParts = ['', sprintf('rel="%s"', implode(' ', $link->getRels()))];
  34. foreach ($link->getAttributes() as $key => $value) {
  35. if (\is_array($value)) {
  36. foreach ($value as $v) {
  37. $attributesParts[] = sprintf('%s="%s"', $key, preg_replace('/(?<!\\\\)"/', '\"', $v));
  38. }
  39. continue;
  40. }
  41. if (!\is_bool($value)) {
  42. $attributesParts[] = sprintf('%s="%s"', $key, preg_replace('/(?<!\\\\)"/', '\"', $value));
  43. continue;
  44. }
  45. if (true === $value) {
  46. $attributesParts[] = $key;
  47. }
  48. }
  49. $elements[] = sprintf('<%s>%s', $link->getHref(), implode('; ', $attributesParts));
  50. }
  51. return $elements ? implode(',', $elements) : null;
  52. }
  53. }