diff --git a/sources/AppBundle/Twig/TalkPageTitleExtension.php b/sources/AppBundle/Twig/TalkPageTitleExtension.php new file mode 100644 index 000000000..b3851c445 --- /dev/null +++ b/sources/AppBundle/Twig/TalkPageTitleExtension.php @@ -0,0 +1,61 @@ + d'une page talk en restant sous la limite affichée par les moteurs de recherche. + */ +final class TalkPageTitleExtension extends AbstractExtension +{ + public const int MAX_LENGTH = 65; + + private const string SEPARATOR = ' – '; + private const string ELLIPSIS = '…'; + + #[\Override] + public function getFunctions(): array + { + return [ + new TwigFunction('talk_page_title', $this->talkPageTitle(...)), + ]; + } + + /** + * « {titre} – {événement} » si l'ensemble tient dans la limite, sinon le titre seul, + * tronqué sur une frontière de mot avec « … » s'il la dépasse encore. + */ + public function talkPageTitle(string $talkTitle, string $eventTitle): string + { + $talkTitle = trim($talkTitle); + $eventTitle = trim($eventTitle); + + if ($eventTitle !== '') { + $withEvent = $talkTitle . self::SEPARATOR . $eventTitle; + if (mb_strlen($withEvent) <= self::MAX_LENGTH) { + return $withEvent; + } + } + + if (mb_strlen($talkTitle) <= self::MAX_LENGTH) { + return $talkTitle; + } + + $available = self::MAX_LENGTH - mb_strlen(self::ELLIPSIS); + $truncated = mb_substr($talkTitle, 0, $available); + + // Le mot est coupé si le caractère suivant la coupe n'est pas un espace : on recule au dernier espace. + if (!preg_match('/^\s/u', mb_substr($talkTitle, $available, 1))) { + $lastSpace = mb_strrpos($truncated, ' '); + if ($lastSpace !== false && $lastSpace > 0) { + $truncated = mb_substr($truncated, 0, $lastSpace); + } + } + + return rtrim($truncated, " \t\n\r\0\x0B,;:-–—") . self::ELLIPSIS; + } +} diff --git a/templates/site/talks/show.html.twig b/templates/site/talks/show.html.twig index 03c989d48..fdbd09d94 100644 --- a/templates/site/talks/show.html.twig +++ b/templates/site/talks/show.html.twig @@ -1,6 +1,6 @@ {% extends 'layouts/site.html.twig' %} -{% block title %}{{ talk.title }} - {{ event.title }}{% endblock %} +{% block title %}{{ talk_page_title(talk.title, event.title) }}{% endblock %} {% block metas %} {{ parent() }} diff --git a/tests/behat/features/PublicSite/Talks.feature b/tests/behat/features/PublicSite/Talks.feature index 3b2508d47..54a0436ce 100644 --- a/tests/behat/features/PublicSite/Talks.feature +++ b/tests/behat/features/PublicSite/Talks.feature @@ -102,3 +102,13 @@ Feature: Site Public - Talks When I go to "/talks/6-revolutionons-php" Then the response status code should be 200 And the response should not contain a JSON-LD "VideoObject" + + @reloadDbWithTestData + Scenario: Le title d'un talk au titre court contient l'évènement + When I go to "/talks/1-jouons-tous-ensemble-a-un-petit-jeu" + Then the response should contain "