HttpHeaderSerializer example

/** * Adds the Link HTTP header to the response. * * @author Kévin Dunglas <dunglas@gmail.com> * * @final */
class AddLinkHeaderListener implements EventSubscriberInterface
{
    public function __construct(
        private readonly HttpHeaderSerializer $serializer = new HttpHeaderSerializer(),
    ) {
    }

    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $linkProvider = $event->getRequest()->attributes->get('_links');
        if (!$linkProvider instanceof LinkProviderInterface || !$links = $linkProvider->getLinks()) {
            
$controller->addLink($request$link1);
        $controller->addLink($request$link2);

        $links = $request->attributes->get('_links')->getLinks();
        $this->assertContains($link1$links);
        $this->assertContains($link2$links);
    }

    public function testSendEarlyHints()
    {
        $container = new Container();
        $container->set('web_link.http_header_serializer', new HttpHeaderSerializer());

        $controller = $this->createController();
        $controller->setContainer($container);

        $response = $controller->sendEarlyHints([
            (new Link(href: '/style.css'))->withAttribute('as', 'stylesheet'),
            (new Link(href: '/script.js'))->withAttribute('as', 'script'),
        ]);

        $this->assertSame('</style.css>; rel="preload"; as="stylesheet",</script.js>; rel="preload"; as="script"', $response->headers->get('Link'));
    }
}
use PHPUnit\Framework\TestCase;
use Symfony\Component\WebLink\HttpHeaderSerializer;
use Symfony\Component\WebLink\Link;

class HttpHeaderSerializerTest extends TestCase
{
    private HttpHeaderSerializer $serializer;

    protected function setUp(): void
    {
        $this->serializer = new HttpHeaderSerializer();
    }

    public function testSerialize()
    {
        $links = [
            new Link('prerender', '/1'),
            (new Link('dns-prefetch', '/2'))->withAttribute('pr', 0.7),
            (new Link('preload', '/3'))->withAttribute('as', 'script')->withAttribute('nopush', false),
            (new Link('preload', '/4'))->withAttribute('as', 'image')->withAttribute('nopush', true),
            (new Link('alternate', '/5'))->withRel('next')->withAttribute('hreflang', ['fr', 'de'])->withAttribute('title', 'Hello'),
        ];

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