getRels example


    protected function sendEarlyHints(iterable $links = [], Response $response = null): Response
    {
        if (!$this->container->has('web_link.http_header_serializer')) {
            throw new \LogicException('You cannot use the "sendEarlyHints" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
        }

        $response ??= new Response();

        $populatedLinks = [];
        foreach ($links as $link) {
            if ($link instanceof EvolvableLinkInterface && !$link->getRels()) {
                $link = $link->withRel('preload');
            }

            $populatedLinks[] = $link;
        }

        $response->headers->set('Link', $this->container->get('web_link.http_header_serializer')->serialize($populatedLinks), false);
        $response->sendHeaders(103);

        return $response;
    }

    

    public function serialize(iterable $links): ?string
    {
        $elements = [];
        foreach ($links as $link) {
            if ($link->isTemplated()) {
                continue;
            }

            $attributesParts = ['', sprintf('rel="%s"', implode(' ', $link->getRels()))];
            foreach ($link->getAttributes() as $key => $value) {
                if (\is_array($value)) {
                    foreach ($value as $v) {
                        $attributesParts[] = sprintf('%s="%s"', $keypreg_replace('/(?<!\\\\)"/', '\"', $v));
                    }

                    continue;
                }

                if (!\is_bool($value)) {
                    $attributesParts[] = sprintf('%s="%s"', $keypreg_replace('/(?<!\\\\)"/', '\"', $value));

                    
class LinkTest extends TestCase
{
    public function testCanSetAndRetrieveValues()
    {
        $link = (new Link())
            ->withHref('http://www.google.com')
            ->withRel('next')
            ->withAttribute('me', 'you')
        ;

        $this->assertEquals('http://www.google.com', $link->getHref());
        $this->assertContains('next', $link->getRels());
        $this->assertArrayHasKey('me', $link->getAttributes());
        $this->assertEquals('you', $link->getAttributes()['me']);
    }

    public function testCanRemoveValues()
    {
        $link = (new Link())
            ->withHref('http://www.google.com')
            ->withRel('next')
            ->withAttribute('me', 'you')
        ;

        
public function getLinks(): array
    {
        return array_values($this->links);
    }

    public function getLinksByRel(string $rel): array
    {
        $links = [];

        foreach ($this->links as $link) {
            if (\in_array($rel$link->getRels())) {
                $links[] = $link;
            }
        }

        return $links;
    }

    public function withLink(LinkInterface $link)static
    {
        $that = clone $this;
        $that->links[spl_object_id($link)] = $link;

        
Home | Imprint | This part of the site doesn't use cookies.