diff --git a/db/seeds/Session.php b/db/seeds/Session.php index c493c208da..e9500c31a4 100644 --- a/db/seeds/Session.php +++ b/db/seeds/Session.php @@ -136,6 +136,45 @@ public function run(): void ], ]; + $forcedPlannings = [ + 6 => [ + 'debut' => new \DateTime('2020-09-15 10:00:00')->format('U'), + 'fin' => new \DateTime('2020-09-15 10:40:00')->format('U'), + ], + ]; + + // Une édition passée avec un planning complet (7 talks publiés, une vidéo sur + // deux, des horaires dans un autre ordre que les identifiants) et un talk dont + // la publication est à venir, pour les liens entre talks de la page talk. + $passedEventTalks = [ + 7 => ['titre' => 'Clôture : le futur de PHP', 'youtube_id' => 'videoTalk07', 'debut' => '16:00'], + 8 => ['titre' => 'Keynote d\'ouverture', 'youtube_id' => null, 'debut' => '09:00'], + 9 => ['titre' => 'Tester sans se ruiner', 'youtube_id' => 'videoTalk09', 'debut' => '11:00'], + 10 => ['titre' => 'Migrer une application legacy', 'youtube_id' => null, 'debut' => '12:00'], + 11 => ['titre' => 'Observabilité avec OpenTelemetry', 'youtube_id' => 'videoTalk11', 'debut' => '14:00'], + 12 => ['titre' => 'Le typage statique en pratique', 'youtube_id' => null, 'debut' => '15:00'], + 13 => ['titre' => 'Un talk pas encore publié', 'youtube_id' => 'videoTalk13', 'debut' => '17:00', 'date_publication' => new \DateTime()->modify('+5 days')->format('Y-m-d H:i:s')], + ]; + foreach ($passedEventTalks as $sessionId => $passedEventTalk) { + $sessions[] = [ + 'session_id' => $sessionId, + 'id_forum' => Event::ID_PASSED, + 'date_soumission' => '2020-05-01', + 'titre' => $passedEventTalk['titre'], + 'abstract' => 'Résumé du talk « ' . $passedEventTalk['titre'] . ' ».', + 'genre' => 1, + 'skill' => 0, + 'plannifie' => 1, + 'youtube_id' => $passedEventTalk['youtube_id'], + 'language_code' => 'fr', + 'date_publication' => $passedEventTalk['date_publication'] ?? null, + ]; + $forcedPlannings[$sessionId] = [ + 'debut' => new \DateTime('2020-09-15 ' . $passedEventTalk['debut'])->format('U'), + 'fin' => new \DateTime('2020-09-15 ' . $passedEventTalk['debut'])->modify('+40 minutes')->format('U'), + ]; + } + $sessionsByIds = []; foreach ($sessions as $session) { $sessionsByIds[$session['session_id']] = $session; @@ -158,6 +197,11 @@ public function run(): void } $conferenciers[2]['conferencier_id'] = 2; + foreach ($conferenciers as $index => $conferencier) { + if (isset($passedEventTalks[$conferencier['session_id']])) { + $conferenciers[$index]['conferencier_id'] = 3; + } + } $table = $this->table('afup_conferenciers_sessions'); $table->truncate(); @@ -179,14 +223,6 @@ public function run(): void ->save(); - $forcedPlannings = [ - 6 => [ - 'debut' => new \DateTime('2020-09-15 10:00:00')->format('U'), - 'fin' => new \DateTime('2020-09-15 10:40:00')->format('U'), - ], - ]; - - $i = 1; $plannings = []; foreach ($sessions as $session) { diff --git a/sources/AppBundle/Controller/Website/Talks/ShowAction.php b/sources/AppBundle/Controller/Website/Talks/ShowAction.php index 1dc238d2d7..a7cb7d049f 100644 --- a/sources/AppBundle/Controller/Website/Talks/ShowAction.php +++ b/sources/AppBundle/Controller/Website/Talks/ShowAction.php @@ -9,6 +9,8 @@ use AppBundle\Event\Model\Repository\SpeakerRepository; use AppBundle\Event\Model\Repository\TalkRepository; use AppBundle\Event\Talk\VideoObjectJsonLd; +use AppBundle\Event\Talk\RelatedTalkRepository; +use AppBundle\Event\Talk\RelatedTalks; use AppBundle\Joindin\JoindinComments; use AppBundle\Subtitles\Parser; use AppBundle\Twig\ViewRenderer; @@ -26,6 +28,7 @@ public function __construct( private readonly PlanningRepository $planningRepository, private readonly EventRepository $eventRepository, private readonly VideoObjectJsonLd $videoObjectJsonLd, + private readonly RelatedTalkRepository $relatedTalkRepository, ) {} public function __invoke(int $id, string $slug): Response @@ -45,8 +48,17 @@ public function __invoke(int $id, string $slug): Response return $this->redirectToRoute('talks_show', ['id' => $id, 'slug' => $talk->getSlug()], Response::HTTP_MOVED_PERMANENTLY); } - $speakers = $this->speakerRepository->getSpeakersByTalk($talk); + $speakers = iterator_to_array($this->speakerRepository->getSpeakersByTalk($talk), false); $event = $this->eventRepository->get($planning->eventId); + if ($event === null) { + throw $this->createNotFoundException(); + } + $relatedTalks = RelatedTalks::build( + $talk, + $this->relatedTalkRepository->getPublishedByEventInPlanningOrder($event), + $speakers, + $this->relatedTalkRepository->getPublishedBySpeakers($speakers, $talk), + ); $comments = $this->joindinComments->getCommentsFromTalk($talk); $parser = new Parser(); @@ -59,6 +71,7 @@ public function __invoke(int $id, string $slug): Response 'comments' => $comments, 'transcript' => $parsedContent, 'video_object' => $this->videoObjectJsonLd->getData($talk, $planning->start, $parsedContent, $this->generateUrl('talks_show', ['id' => $talk->getId(), 'slug' => $talk->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL)), + 'related_talks' => $relatedTalks, ]); } } diff --git a/sources/AppBundle/Event/Talk/RelatedTalkRepository.php b/sources/AppBundle/Event/Talk/RelatedTalkRepository.php new file mode 100644 index 0000000000..718905d319 --- /dev/null +++ b/sources/AppBundle/Event/Talk/RelatedTalkRepository.php @@ -0,0 +1,168 @@ + + */ + public function getPublishedByEventInPlanningOrder(Event $event): array + { + $talkIds = $this->connection->executeQuery( + 'SELECT talk.session_id + FROM afup_sessions AS talk + INNER JOIN ' . self::PLANNING . ' AS planning ON planning.id_session = talk.session_id + WHERE talk.id_forum = :event AND ' . self::PUBLISHED . ' + ORDER BY planning.debut ASC, talk.session_id ASC', + ['event' => $event->getId(), 'hiddenTypes' => self::hiddenTypes()], + ['hiddenTypes' => ArrayParameterType::INTEGER], + )->fetchFirstColumn(); + Assert::allIntegerish($talkIds); + + return array_values($this->loadTalks(array_map(intval(...), $talkIds))); + } + + /** + * Talks publiés, toutes éditions confondues, des personnes qui ont présenté ces speakers, + * du plus récent au plus ancien. + * + * Un speaker étant une ligne par édition, la même personne est retrouvée par son + * compte GitHub ou, à défaut, par son prénom et son nom. + * + * @param list $speakers + * + * @return list}> les speakers de chaque talk qui correspondent à l'un de ceux demandés + */ + public function getPublishedBySpeakers(array $speakers, Talk $excludedTalk): array + { + $conditions = []; + $params = ['excluded' => $excludedTalk->getId(), 'hiddenTypes' => self::hiddenTypes()]; + foreach ($speakers as $index => $speaker) { + $conditions[] = sprintf('(LOWER(TRIM(speaker.prenom)) = :firstname%1$d AND LOWER(TRIM(speaker.nom)) = :lastname%1$d)', $index); + $params['firstname' . $index] = mb_strtolower(trim((string) $speaker->getFirstname())); + $params['lastname' . $index] = mb_strtolower(trim((string) $speaker->getLastname())); + + if ($speaker->getUser()) { + $conditions[] = sprintf('speaker.user_github = :github%d', $index); + $params['github' . $index] = $speaker->getUser(); + } + } + + if ($conditions === []) { + return []; + } + + $rows = $this->connection->executeQuery( + sprintf('SELECT talk.session_id AS talk_id, talk.id_forum AS event_id, speaker.conferencier_id AS speaker_id + FROM afup_sessions AS talk + INNER JOIN ' . self::PLANNING . ' AS planning ON planning.id_session = talk.session_id + INNER JOIN afup_conferenciers_sessions acs ON acs.session_id = talk.session_id + INNER JOIN afup_conferenciers speaker ON speaker.conferencier_id = acs.conferencier_id + WHERE talk.session_id != :excluded AND ' . self::PUBLISHED . ' + AND (%s) + ORDER BY planning.debut DESC, talk.session_id DESC, speaker.conferencier_id ASC', implode(' OR ', $conditions)), + $params, + ['hiddenTypes' => ArrayParameterType::INTEGER], + )->fetchAllAssociative(); + + // Par talk, dans l'ordre de la requête : l'édition et les speakers trouvés. + $matches = []; + foreach ($rows as $row) { + Assert::integerish($row['talk_id']); + Assert::integerish($row['event_id']); + Assert::integerish($row['speaker_id']); + $matches[(int) $row['talk_id']]['event'] = (int) $row['event_id']; + $matches[(int) $row['talk_id']]['speakers'][] = (int) $row['speaker_id']; + } + + $talks = $this->loadTalks(array_keys($matches)); + $events = []; + $talksWithSpeakers = []; + foreach ($talks as $talkId => $talk) { + $eventId = $matches[$talkId]['event']; + $event = $events[$eventId] ??= $this->eventRepository->get($eventId); + $talkSpeakers = array_values(array_filter(array_map($this->speakerRepository->get(...), $matches[$talkId]['speakers']))); + + if ($event instanceof Event && $talkSpeakers !== []) { + $talksWithSpeakers[] = ['talk' => $talk, 'event' => $event, 'speakers' => $talkSpeakers]; + } + } + + return $talksWithSpeakers; + } + + /** + * @param list $talkIds + * + * @return array les talks indexés par identifiant, dans l'ordre des identifiants donnés + */ + private function loadTalks(array $talkIds): array + { + if ($talkIds === []) { + return []; + } + + $talksById = []; + foreach ($this->talkRepository->findList($talkIds) as $talk) { + $talksById[$talk->getId() ?? 0] = $talk; + } + + $talks = []; + foreach ($talkIds as $talkId) { + if (isset($talksById[$talkId])) { + $talks[$talkId] = $talksById[$talkId]; + } + } + + return $talks; + } + + /** + * @return list + */ + private static function hiddenTypes(): array + { + return [Talk::TYPE_CLINIC, Talk::TYPE_SPEAKER_INTRODUCTIONS]; + } +} diff --git a/sources/AppBundle/Event/Talk/RelatedTalks.php b/sources/AppBundle/Event/Talk/RelatedTalks.php new file mode 100644 index 0000000000..33aafd0509 --- /dev/null +++ b/sources/AppBundle/Event/Talk/RelatedTalks.php @@ -0,0 +1,90 @@ + $sameEvent + * @param list}> $bySpeaker + */ + public function __construct( + public ?Talk $previous, + public ?Talk $next, + public array $sameEvent, + public array $bySpeaker, + ) {} + + /** + * @param list $eventTalks talks publiés de l'édition, dans l'ordre du planning + * @param list $speakers speakers du talk + * @param list}> $speakersTalks talks publiés des speakers, du plus récent au plus ancien + */ + public static function build(Talk $talk, array $eventTalks, array $speakers, array $speakersTalks): self + { + $position = array_find_key($eventTalks, fn(Talk $eventTalk): bool => $eventTalk->getId() === $talk->getId()); + + if ($position === null) { + $previous = $next = null; + $others = $eventTalks; + } else { + $previous = $eventTalks[$position - 1] ?? null; + $next = $eventTalks[$position + 1] ?? null; + // On part du talk suivant et on boucle sur le début du planning : chaque talk + // de l'édition reçoit ainsi des liens, pas seulement les premiers du planning. + $others = [...array_slice($eventTalks, $position + 1), ...array_slice($eventTalks, 0, $position)]; + } + + // Tri stable : les vidéos d'abord, l'ordre du planning ensuite. + usort($others, fn(Talk $a, Talk $b): int => $b->hasYoutubeId() <=> $a->hasYoutubeId()); + + $bySpeaker = []; + foreach ($speakers as $speaker) { + $talks = []; + foreach ($speakersTalks as $speakerTalk) { + foreach ($speakerTalk['speakers'] as $candidate) { + if (self::isSamePerson($speaker, $candidate)) { + $talks[] = ['talk' => $speakerTalk['talk'], 'event' => $speakerTalk['event']]; + break; + } + } + } + + if ($talks !== []) { + $bySpeaker[] = ['speaker' => $speaker, 'talks' => $talks]; + } + } + + return new self($previous, $next, array_slice($others, 0, self::SAME_EVENT_LIMIT), $bySpeaker); + } + + /** + * Même règle que RelatedTalkRepository::getPublishedBySpeakers() : même compte GitHub, + * ou même prénom et même nom. + */ + private static function isSamePerson(Speaker $speaker, Speaker $candidate): bool + { + if ($speaker->getUser() && $speaker->getUser() === $candidate->getUser()) { + return true; + } + + return self::normalize($speaker->getFirstname()) === self::normalize($candidate->getFirstname()) + && self::normalize($speaker->getLastname()) === self::normalize($candidate->getLastname()); + } + + private static function normalize(?string $name): string + { + return mb_strtolower(trim((string) $name)); + } +} diff --git a/sources/AppBundle/Twig/TalksExtension.php b/sources/AppBundle/Twig/TalksExtension.php new file mode 100644 index 0000000000..d580ef437d --- /dev/null +++ b/sources/AppBundle/Twig/TalksExtension.php @@ -0,0 +1,36 @@ +eventUrl(...)), + ]; + } + + /** + * URL absolue de la liste des talks d'une édition. Seul endroit où elle est générée : + * la page événement dédiée la remplacera. + */ + public function eventUrl(Event $event): string + { + return $this->urlGenerator->generate( + 'talks_list', + ['fR' => ['event.title' => [$event->getTitle()]]], + UrlGeneratorInterface::ABSOLUTE_URL, + ); + } +} diff --git a/templates/site/talks/show.html.twig b/templates/site/talks/show.html.twig index 03c989d48c..75a8539259 100644 --- a/templates/site/talks/show.html.twig +++ b/templates/site/talks/show.html.twig @@ -1,5 +1,12 @@ {% extends 'layouts/site.html.twig' %} +{% set breadcrumb = [ + { name: 'Accueil', url: url('home') }, + { name: 'Conférences', url: url('talks_list') }, + { name: event.title, url: talks_event_url(event) }, + { name: talk.title, url: url('talks_show', {id: talk.id, slug: talk.slug}) }, +] %} + {% block title %}{{ talk.title }} - {{ event.title }}{% endblock %} {% block metas %} @@ -25,6 +32,19 @@ {% if video_object %} {% endif %} + + {% endblock %} {% block content %} @@ -32,9 +52,24 @@ {% set event_date %} {% if event.dateStart == event.dateEnd %}le {{ event.dateStart|date('d') }}{% else %}les {{ event.dateStart|date('d') }} et {{ event.dateEnd|date('d') }}{% endif %} {{ event.dateEnd|format_date('none', 'MMMM YYYY') }} {% endset %} - {% set event_url = url('talks_list', {"fR": { "event.title" : [ event.title ]}}) %} + {% set event_url = talks_event_url(event) %} {% set speakers_label = speakers|map(speaker => speaker.label)|join(', ') %} + + {% if talk.hasYoutubeId %} {# Scène sombre : le bandeau n'annonce pas la page, il détache le lecteur du fond. #}
@@ -235,6 +270,76 @@ {% endif %}
{% endif %} + + {% if related_talks.previous or related_talks.next or related_talks.sameEvent|length or related_talks.bySpeaker|length %} +
+ {% if related_talks.previous or related_talks.next %} + + {% endif %} + + {% if related_talks.sameEvent|length %} +
+ Aussi au {{ event.title }} + + Tous les talks du {{ event.title }} +
+ {% endif %} + + {% for speaker_talks in related_talks.bySpeaker %} +
+ Autres talks de {{ speaker_talks.speaker.label }} +
    + {% for related in speaker_talks.talks %} +
  • + {{ related.talk.title }} + {{ related.event.title }} +
  • + {% endfor %} +
+
+ {% endfor %} +
+ {% endif %} {% endblock %} {% block javascripts %} diff --git a/tests/behat/bootstrap/FeatureContext.php b/tests/behat/bootstrap/FeatureContext.php index cd61bdd11f..79f2bb9fed 100644 --- a/tests/behat/bootstrap/FeatureContext.php +++ b/tests/behat/bootstrap/FeatureContext.php @@ -27,6 +27,7 @@ class FeatureContext implements Context use EmailContext; use FormContext; use PdfContext; + use SeoContext; use TimeContext; use WaitContext; diff --git a/tests/behat/bootstrap/SeoContext.php b/tests/behat/bootstrap/SeoContext.php new file mode 100644 index 0000000000..a220187d36 --- /dev/null +++ b/tests/behat/bootstrap/SeoContext.php @@ -0,0 +1,71 @@ +minkContext->getSession(); + + preg_match('#^/talks/(\d+)-#', (string) parse_url($session->getCurrentUrl(), PHP_URL_PATH), $matches); + $currentTalkId = $matches[1] ?? null; + + $found = 0; + foreach ($session->getPage()->findAll('css', 'a[href]') as $link) { + $path = (string) parse_url((string) $link->getAttribute('href'), PHP_URL_PATH); + if (preg_match('#^/talks/(\d+)-[^/]+$#', $path, $matches) && $matches[1] !== $currentTalkId) { + ++$found; + } + } + + if ($found < $count) { + throw new ExpectationException( + sprintf('Expected at least %d links to other talks, found %d', $count, $found), + $session->getDriver(), + ); + } + } + + #[Then('the JSON-LD :type should have the following items:')] + public function assertJsonLdHasItems(string $type, TableNode $expectedItems): void + { + $session = $this->minkContext->getSession(); + + $items = null; + foreach ($session->getPage()->findAll('css', 'script[type="application/ld+json"]') as $script) { + $data = json_decode($script->getHtml(), true, flags: JSON_THROW_ON_ERROR); + if (($data['@type'] ?? null) === $type) { + $items = $data['itemListElement'] ?? []; + break; + } + } + + if ($items === null) { + throw new ExpectationException(sprintf('No JSON-LD of type "%s" found', $type), $session->getDriver()); + } + + $actual = array_map( + fn(array $item): array => [ + 'position' => (string) $item['position'], + 'name' => $item['name'], + 'item' => $item['item'], + ], + $items, + ); + + if ($actual !== $expectedItems->getHash()) { + throw new ExpectationException( + sprintf('JSON-LD "%s" items do not match: %s', $type, json_encode($actual, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)), + $session->getDriver(), + ); + } + } +} diff --git a/tests/behat/features/PublicSite/Talks.feature b/tests/behat/features/PublicSite/Talks.feature index 3b2508d475..0cb70fe1cd 100644 --- a/tests/behat/features/PublicSite/Talks.feature +++ b/tests/behat/features/PublicSite/Talks.feature @@ -102,3 +102,42 @@ 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: Fil d'Ariane de la page d'un talk + When I go to "/talks/6-revolutionons-php" + Then I should see "Accueil" in the "nav[aria-label^=Fil]" element + And I should see "Conférences" in the "nav[aria-label^=Fil]" element + And I should see "Un évènement du passé" in the "nav[aria-label^=Fil]" element + And I should see "Révolutionons PHP" in the "nav[aria-label^=Fil] [aria-current=page]" element + And the JSON-LD "BreadcrumbList" should have the following items: + | position | name | item | + | 1 | Accueil | https://apachephptest:80/ | + | 2 | Conférences | https://apachephptest:80/talks/ | + | 3 | Un évènement du passé | https://apachephptest:80/talks/?fR%5Bevent.title%5D%5B0%5D=Un%20%C3%A9v%C3%A8nement%20du%20pass%C3%A9 | + | 4 | Révolutionons PHP | https://apachephptest:80/talks/6-revolutionons-php | + + @reloadDbWithTestData + Scenario: Liens vers les autres talks depuis la page d'un talk + When I go to "/talks/6-revolutionons-php" + Then the page should contain at least 8 links to other talks + And I should see "Keynote d'ouverture" in the "a[rel=prev]" element + And I should see "Tester sans se ruiner" in the "a[rel=next]" element + And I should see "Aussi au Un évènement du passé" + And I should see "Observabilité avec OpenTelemetry" + And I should see "Le typage statique en pratique" + And I should see "Clôture : le futur de PHP" + And I should see "Migrer une application legacy" + And I should see "Autres talks de Geoffrey BACHELET" + And I should see "Jouons tous ensemble à un petit jeu" + And I should see "REST ou GraphQL ? Exemples illustrés avec Symfony et API Platform" + And I should not see "Un talk pas encore publié" + + @reloadDbWithTestData + Scenario: Premier et dernier talks du planning d'une édition + When I go to "/talks/8-keynote-d-ouverture" + Then I should not see "Talk précédent" + And I should see "Révolutionons PHP" in the "a[rel=next]" element + When I go to "/talks/7-cloture-le-futur-de-php" + Then I should see "Le typage statique en pratique" in the "a[rel=prev]" element + And I should not see "Talk suivant" diff --git a/tests/behat/files/admin_talks_export_joind_in.csv b/tests/behat/files/admin_talks_export_joind_in.csv index 338bb4e5bd..df6535afef 100644 --- a/tests/behat/files/admin_talks_export_joind_in.csv +++ b/tests/behat/files/admin_talks_export_joind_in.csv @@ -1,2 +1,8 @@ Title,Description,Speaker,Date,Time,Type -"Révolutionons PHP","Hey ! Viens changer PHP avec moi !","Geoffrey Bachelet",2020-09-15,10:00,Talk \ No newline at end of file +"Keynote d'ouverture","Résumé du talk « Keynote d'ouverture ».","John Doe",2020-09-15,09:00,Talk +"Révolutionons PHP","Hey ! Viens changer PHP avec moi !","Geoffrey Bachelet",2020-09-15,10:00,Talk +"Tester sans se ruiner","Résumé du talk « Tester sans se ruiner ».","John Doe",2020-09-15,11:00,Talk +"Migrer une application legacy","Résumé du talk « Migrer une application legacy ».","John Doe",2020-09-15,12:00,Talk +"Observabilité avec OpenTelemetry","Résumé du talk « Observabilité avec OpenTelemetry ».","John Doe",2020-09-15,14:00,Talk +"Le typage statique en pratique","Résumé du talk « Le typage statique en pratique ».","John Doe",2020-09-15,15:00,Talk +"Clôture : le futur de PHP","Résumé du talk « Clôture : le futur de PHP ».","John Doe",2020-09-15,16:00,Talk \ No newline at end of file diff --git a/tests/unit/AppBundle/Event/Talk/RelatedTalksTest.php b/tests/unit/AppBundle/Event/Talk/RelatedTalksTest.php new file mode 100644 index 0000000000..c0b67f3fcf --- /dev/null +++ b/tests/unit/AppBundle/Event/Talk/RelatedTalksTest.php @@ -0,0 +1,140 @@ +talks([1 => false, 2 => false, 3 => false]); + + $related = RelatedTalks::build($talks[1], array_values($talks), [], []); + + self::assertSame($talks[0], $related->previous); + self::assertSame($talks[2], $related->next); + } + + public function testFirstAndLastTalksHaveNoPreviousOrNext(): void + { + $talks = $this->talks([1 => false, 2 => false]); + + self::assertNull(RelatedTalks::build($talks[0], $talks, [], [])->previous); + self::assertNull(RelatedTalks::build($talks[1], $talks, [], [])->next); + } + + public function testSameEventStartsAfterTheTalkAndPutsVideosFirst(): void + { + // Planning : 1, 2, 3 (courant), 4, 5 ; seuls 2 et 5 ont une vidéo. + $talks = $this->talks([1 => false, 2 => true, 3 => false, 4 => false, 5 => true]); + + $related = RelatedTalks::build($talks[2], $talks, [], []); + + self::assertSame([5, 2, 4, 1], $this->ids($related->sameEvent)); + } + + public function testSameEventIsLimitedToSixTalks(): void + { + $talks = $this->talks(array_fill(1, 9, false)); + + $related = RelatedTalks::build($talks[0], $talks, [], []); + + self::assertSame([2, 3, 4, 5, 6, 7], $this->ids($related->sameEvent)); + } + + public function testUnpublishedTalkHasNoNeighboursButStillLinksToItsEvent(): void + { + $talks = $this->talks([1 => false, 2 => true]); + $unpublished = new Talk()->setId(99)->setTitle('Pas encore publié'); + + $related = RelatedTalks::build($unpublished, $talks, [], []); + + self::assertNull($related->previous); + self::assertNull($related->next); + self::assertSame([2, 1], $this->ids($related->sameEvent)); + } + + public function testTalksAreGroupedBySpeaker(): void + { + $alice = $this->speaker(1, 'Alice', 'Martin', 42); + $bob = $this->speaker(2, 'Bob', 'Durand', null); + + // Mêmes personnes, autres éditions : Alice retrouvée par son compte GitHub + // malgré un nom différent, Bob par son nom malgré la casse et les espaces. + $aliceElsewhere = $this->speaker(10, 'Alicia', 'Martin-Dupont', 42); + $bobElsewhere = $this->speaker(11, ' bob', 'DURAND ', null); + $homonym = $this->speaker(12, 'Alice', 'Martinez', 7); + + $event = new Event(); + $talkByAlice = new Talk()->setId(20)->setTitle('Talk Alice'); + $talkByBoth = new Talk()->setId(21)->setTitle('Talk à deux'); + $talkByHomonym = new Talk()->setId(22)->setTitle('Talk homonyme'); + + $current = new Talk()->setId(1)->setTitle('Talk courant'); + $related = RelatedTalks::build($current, [$current], [$alice, $bob], [ + ['talk' => $talkByAlice, 'event' => $event, 'speakers' => [$aliceElsewhere]], + ['talk' => $talkByBoth, 'event' => $event, 'speakers' => [$aliceElsewhere, $bobElsewhere]], + ['talk' => $talkByHomonym, 'event' => $event, 'speakers' => [$homonym]], + ]); + + self::assertCount(2, $related->bySpeaker); + self::assertSame($alice, $related->bySpeaker[0]['speaker']); + self::assertSame([$talkByAlice, $talkByBoth], array_column($related->bySpeaker[0]['talks'], 'talk')); + self::assertSame($bob, $related->bySpeaker[1]['speaker']); + self::assertSame([$talkByBoth], array_column($related->bySpeaker[1]['talks'], 'talk')); + self::assertSame($event, $related->bySpeaker[1]['talks'][0]['event']); + } + + public function testSpeakerWithoutOtherTalksIsOmitted(): void + { + $current = new Talk()->setId(1)->setTitle('Talk courant'); + + $related = RelatedTalks::build($current, [$current], [$this->speaker(1, 'Alice', 'Martin', null)], []); + + self::assertSame([], $related->bySpeaker); + } + + /** + * @param array $hasVideoById + * + * @return list + */ + private function talks(array $hasVideoById): array + { + $talks = []; + foreach ($hasVideoById as $id => $hasVideo) { + $talks[] = new Talk() + ->setId($id) + ->setTitle('Talk ' . $id) + ->setYoutubeId($hasVideo ? 'video' . $id : null); + } + + return $talks; + } + + private function speaker(int $id, string $firstname, string $lastname, ?int $githubUser): Speaker + { + return new Speaker() + ->setId($id) + ->setFirstname($firstname) + ->setLastname($lastname) + ->setUser($githubUser); + } + + /** + * @param list $talks + * + * @return list + */ + private function ids(array $talks): array + { + return array_map(fn(Talk $talk): ?int => $talk->getId(), $talks); + } +}