Skip to content

Commit

Permalink
Added support for canonical link handling to html head bag
Browse files Browse the repository at this point in the history
  • Loading branch information
Toflar committed Oct 26, 2021
1 parent e0fd66f commit 6a63d40
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
Expand Up @@ -12,11 +12,14 @@

namespace Contao\CoreBundle\Routing\ResponseContext\HtmlHeadBag;

use Symfony\Component\HttpFoundation\Request;

final class HtmlHeadBag
{
private string $title = '';
private string $metaDescription = '';
private string $metaRobots = 'index,follow';
private array $keepParamsForCanonical = [];

public function getTitle(): string
{
Expand Down Expand Up @@ -53,4 +56,32 @@ public function setMetaRobots(string $metaRobots): self

return $this;
}

public function setKeepParamsForCanonical(array $keepParamsForCanonical): self
{
$this->keepParamsForCanonical = $keepParamsForCanonical;

return $this;
}

public function getKeepParamsForCanonical(): array
{
return $this->keepParamsForCanonical;
}

public function addKeepParamsForCanonical(string $param): self
{
$this->keepParamsForCanonical[] = $param;

return $this;
}

public function getCanonicalUri(Request $request): string
{
return Request::create(
$request->getSchemeAndHttpHost().$request->getBaseUrl().$request->getPathInfo(),
$request->getMethod(),
array_intersect_key($request->query->all(), array_flip($this->getKeepParamsForCanonical()))
)->getUri();
}
}
Expand Up @@ -14,6 +14,7 @@

use Contao\CoreBundle\Routing\ResponseContext\HtmlHeadBag\HtmlHeadBag;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;

class HtmlHeadBagTest extends TestCase
{
Expand All @@ -31,4 +32,21 @@ public function testHeadManagerBasics(): void
$this->assertSame('foobar description', $manager->getMetaDescription());
$this->assertSame('noindex,nofollow', $manager->getMetaRobots());
}

public function testCanonicalHandling(): void
{
$manager = new HtmlHeadBag();
$this->assertSame([], $manager->getKeepParamsForCanonical());

$manager->addKeepParamsForCanonical('page');
$manager->addKeepParamsForCanonical('page2');
$this->assertSame(['page', 'page2'], $manager->getKeepParamsForCanonical());

$manager->setKeepParamsForCanonical(['foo', 'page']);
$this->assertSame(['foo', 'page'], $manager->getKeepParamsForCanonical());

$request = Request::create('https://contao.org/foobar/page?query=test&foo=bar&baz=bak&page=12');

$this->assertSame('https://contao.org/foobar/page?foo=bar&page=12', $manager->getCanonicalUri($request));
}
}

0 comments on commit 6a63d40

Please sign in to comment.