diff --git a/sources/AppBundle/Event/Speaker/SpeakerIdentity.php b/sources/AppBundle/Event/Speaker/SpeakerIdentity.php new file mode 100644 index 000000000..eef403050 --- /dev/null +++ b/sources/AppBundle/Event/Speaker/SpeakerIdentity.php @@ -0,0 +1,44 @@ + $speakerIds les lignes speaker (une par édition) de cette personne + */ + public function __construct( + public string $slug, + public string $firstname, + public string $lastname, + public array $speakerIds, + public \DateTimeImmutable $latestTalkAt, + ) {} + + /** + * « Prénom Nom », tel que saisi, espaces superflus retirés. + */ + public function getName(): string + { + return self::cleanSpaces($this->firstname . ' ' . $this->lastname); + } + + /** + * « Prénom NOM », comme Speaker::getLabel(), espaces superflus retirés. + */ + public function getLabel(): string + { + return self::cleanSpaces($this->firstname . ' ' . mb_strtoupper($this->lastname)); + } + + private static function cleanSpaces(string $value): string + { + return trim((string) preg_replace('/\s+/u', ' ', $value)); + } +} diff --git a/sources/AppBundle/Event/Speaker/SpeakerProfile.php b/sources/AppBundle/Event/Speaker/SpeakerProfile.php new file mode 100644 index 000000000..2800fc960 --- /dev/null +++ b/sources/AppBundle/Event/Speaker/SpeakerProfile.php @@ -0,0 +1,29 @@ + $socialLinks URL par réseau + * @param non-empty-list $talks les talks publiés, du plus récent au plus ancien + */ + public function __construct( + public SpeakerIdentity $identity, + public Speaker $speaker, + public ?string $biography, + public ?Speaker $photoSpeaker, + public array $socialLinks, + public array $talks, + ) {} +} diff --git a/sources/AppBundle/Event/Speaker/SpeakerProfileResolver.php b/sources/AppBundle/Event/Speaker/SpeakerProfileResolver.php new file mode 100644 index 000000000..f371c1726 --- /dev/null +++ b/sources/AppBundle/Event/Speaker/SpeakerProfileResolver.php @@ -0,0 +1,273 @@ +, + * byPersonneId: array, + * byLabel: array, + * }|null + */ + private ?array $index = null; + + private readonly Slugify $slugify; + + public function __construct( + private readonly PublishedTalkRepository $publishedTalkRepository, + private readonly SpeakerRepository $speakerRepository, + ) { + // Le même slugifier que Talk::getSlug(), pour le tri. + $this->slugify = new Slugify(); + } + + /** + * Libellé normalisé : sans espaces superflus, sans accents, en minuscules. + */ + public static function normalizeLabel(string $label): string + { + return u($label)->ascii()->lower()->collapseWhitespace()->toString(); + } + + /** + * Toutes les personnes ayant au moins un talk publié, triées par nom puis prénom. + * + * @return list + */ + public function getIdentities(): array + { + return array_values($this->getIndex()['bySlug']); + } + + public function getIdentityBySlug(string $slug): ?SpeakerIdentity + { + return $this->getIndex()['bySlug'][$slug] ?? null; + } + + /** + * La personne qui porte ce libellé sur l'une de ses lignes speaker (par exemple la facette Algolia + * `speakers.label`), aux accents, à la casse et aux espaces près. Null si personne ou plusieurs personnes le portent. + */ + public function getIdentityByLabel(string $label): ?SpeakerIdentity + { + $index = $this->getIndex(); + $slug = $index['byLabel'][self::normalizeLabel($label)] ?? null; + + return null !== $slug ? $index['bySlug'][$slug] : null; + } + + /** + * La personne d'une ligne speaker de n'importe quelle édition, y compris une édition dont + * les talks ne sont pas encore publiés. Null si la ligne n'est rattachée à aucune personne + * ou si sa personne n'a aucun talk publié. + */ + public function getIdentityForSpeaker(Speaker $speaker): ?SpeakerIdentity + { + $personneId = $speaker->getPersonneId(); + if (null === $personneId) { + return null; + } + + $index = $this->getIndex(); + $slug = $index['byPersonneId'][$personneId] ?? null; + + return null !== $slug ? $index['bySlug'][$slug] : null; + } + + /** + * Le profil consolidé et les talks publiés de la personne qui porte ce slug. + */ + public function getProfileBySlug(string $slug): ?SpeakerProfile + { + $identity = $this->getIdentityBySlug($slug); + if (null === $identity) { + return null; + } + + $speakerTalks = $this->loadSpeakerTalks($identity->speakerIds); + if ($speakerTalks === []) { + return null; + } + + return $this->buildProfile($identity, $speakerTalks); + } + + public function reset(): void + { + $this->index = null; + } + + /** + * @return array{ + * bySlug: array, + * byPersonneId: array, + * byLabel: array, + * } + */ + private function getIndex(): array + { + return $this->index ??= $this->buildIndex($this->publishedTalkRepository->getSpeakerAppearances()); + } + + /** + * @param list $appearances + * + * @return array{ + * bySlug: array, + * byPersonneId: array, + * byLabel: array, + * } + */ + private function buildIndex(array $appearances): array + { + // Du plus récent au plus ancien, quel que soit l'ordre de lecture. + usort($appearances, static fn(array $a, array $b): int => [$b['starts_at'], $b['talk_id'], $b['speaker_id']] <=> [$a['starts_at'], $a['talk_id'], $a['speaker_id']]); + + /** @var array> $groups */ + $groups = []; + $slugsByLabel = []; + foreach ($appearances as $appearance) { + $groups[$appearance['personne_id']][] = $appearance; + $slugsByLabel[self::normalizeLabel($appearance['firstname'] . ' ' . $appearance['lastname'])][$appearance['slug']] = true; + } + + $index = ['bySlug' => [], 'byPersonneId' => [], 'byLabel' => []]; + $identities = []; + foreach ($groups as $personneId => $personneAppearances) { + $latest = $personneAppearances[0]; + $identities[] = new SpeakerIdentity( + $latest['slug'], + $latest['firstname'], + $latest['lastname'], + array_values(array_unique(array_column($personneAppearances, 'speaker_id'))), + new \DateTimeImmutable('@' . $latest['starts_at'])->setTimezone(new \DateTimeZone(date_default_timezone_get())), + ); + $index['byPersonneId'][$personneId] = $latest['slug']; + } + + // Un libellé porté par deux personnes distinctes ne désigne personne. + foreach ($slugsByLabel as $label => $slugs) { + $index['byLabel'][$label] = count($slugs) === 1 ? array_key_first($slugs) : null; + } + + $sortKeys = array_map(fn(SpeakerIdentity $identity): string => $this->slugify->slugify($identity->lastname . ' ' . $identity->firstname) . ' ' . $identity->slug, $identities); + array_multisort($sortKeys, SORT_STRING, $identities); + + foreach ($identities as $identity) { + $index['bySlug'][$identity->slug] = $identity; + } + + return $index; + } + + /** + * Les talks publiés de ces lignes speaker ; chaque ligne speaker est chargée une fois, pour le profil. + * + * @param list $speakerIds + * + * @return list + */ + private function loadSpeakerTalks(array $speakerIds): array + { + $speakers = []; + $speakerTalks = []; + foreach ($this->publishedTalkRepository->getSpeakerTalks($speakerIds) as $row) { + $speaker = $speakers[$row['speaker_id']] ??= $this->speakerRepository->get($row['speaker_id']); + if ($speaker instanceof Speaker) { + $speakerTalks[] = new SpeakerTalk($speaker, $row['talk'], $row['event'], $row['starts_at'], $row['github_login']); + } + } + + return $speakerTalks; + } + + /** + * @param non-empty-list $speakerTalks + */ + private function buildProfile(SpeakerIdentity $identity, array $speakerTalks): SpeakerProfile + { + // Du plus récent au plus ancien, quel que soit l'ordre de lecture. + usort($speakerTalks, static fn(SpeakerTalk $a, SpeakerTalk $b): int => [ + $b->startsAt->getTimestamp(), + $b->talk->id, + $b->speaker->getId(), + ] <=> [ + $a->startsAt->getTimestamp(), + $a->talk->id, + $a->speaker->getId(), + ]); + + /** @var non-empty-array $speakers lignes speaker, de la plus récente à la plus ancienne */ + $speakers = []; + $githubLogins = []; + $talks = []; + foreach ($speakerTalks as $speakerTalk) { + $speakers[(int) $speakerTalk->speaker->getId()] ??= $speakerTalk->speaker; + if (null !== $speakerTalk->githubLogin) { + $githubLogins[] = $speakerTalk->githubLogin; + } + // Deux lignes de la même personne sur un même talk : le talk n'est listé qu'une fois. + $talks[$speakerTalk->talk->id] ??= $speakerTalk; + } + + $socialLinks = array_filter([ + 'twitter' => self::first($speakers, static fn(Speaker $speaker): string => $speaker->getUrlTwitter()), + 'mastodon' => self::first($speakers, static fn(Speaker $speaker): string => (string) $speaker->getUrlMastodon()), + 'bluesky' => self::first($speakers, static fn(Speaker $speaker): string => trim((string) $speaker->getBluesky()) !== '' ? (string) $speaker->getUrlBluesky() : ''), + 'linkedin' => self::first($speakers, static fn(Speaker $speaker): string => (string) $speaker->getUrlLinkedin()), + 'github' => self::first($githubLogins, static fn(string $login): string => '' !== $login ? 'https://github.com/' . $login : ''), + ], static fn(?string $url): bool => null !== $url); + + $photoSpeakers = array_filter($speakers, static fn(Speaker $speaker): bool => trim((string) $speaker->getPhoto()) !== ''); + + return new SpeakerProfile( + $identity, + reset($speakers), + self::first($speakers, static fn(Speaker $speaker): string => trim((string) $speaker->getBiography())), + reset($photoSpeakers) ?: null, + $socialLinks, + array_values($talks), + ); + } + + /** + * La première valeur non vide, dans l'ordre des éléments. + * + * @template T + * + * @param array $items + * @param callable(T): string $value + */ + private static function first(array $items, callable $value): ?string + { + foreach ($items as $item) { + $result = $value($item); + if ('' !== $result) { + return $result; + } + } + + return null; + } +} diff --git a/sources/AppBundle/Event/Speaker/SpeakerTalk.php b/sources/AppBundle/Event/Speaker/SpeakerTalk.php new file mode 100644 index 000000000..f052efe44 --- /dev/null +++ b/sources/AppBundle/Event/Speaker/SpeakerTalk.php @@ -0,0 +1,23 @@ +slug = new Slugify()->slugify($title); + } + + public function hasYoutubeId(): bool + { + return null !== $this->youtubeId && '' !== $this->youtubeId; + } +} diff --git a/sources/AppBundle/Event/Talk/PublishedTalkRepository.php b/sources/AppBundle/Event/Talk/PublishedTalkRepository.php new file mode 100644 index 000000000..62a06053c --- /dev/null +++ b/sources/AppBundle/Event/Talk/PublishedTalkRepository.php @@ -0,0 +1,155 @@ + + */ + public function getSpeakerAppearances(): array + { + $rows = $this->connection->fetchAllAssociative( + 'SELECT speaker.conferencier_id, personne.id AS personne_id, personne.slug, speaker.prenom, speaker.nom, + talk.session_id, planning.debut + FROM afup_conferenciers speaker + INNER JOIN afup_conferenciers_personnes personne ON personne.id = speaker.personne_id + INNER JOIN afup_conferenciers_sessions cs ON cs.conferencier_id = speaker.conferencier_id + INNER JOIN afup_sessions talk ON talk.session_id = cs.session_id' + . self::PLANNING_JOIN . ' + WHERE ' . self::CONDITIONS, + ); + + return array_map(static fn(array $row): array => [ + 'speaker_id' => self::toInt($row['conferencier_id']), + 'personne_id' => self::toInt($row['personne_id']), + 'slug' => self::toString($row['slug']), + 'firstname' => self::nullableString($row['prenom']) ?? '', + 'lastname' => self::nullableString($row['nom']) ?? '', + 'talk_id' => self::toInt($row['session_id']), + 'starts_at' => self::toInt($row['debut']), + ], $rows); + } + + /** + * Les talks publiés de ces lignes speaker, avec leur événement, du plus récent au plus ancien. + * + * @param list $speakerIds + * + * @return list + */ + public function getSpeakerTalks(array $speakerIds): array + { + if ($speakerIds === []) { + return []; + } + + $rows = $this->connection->fetchAllAssociative( + 'SELECT speaker.conferencier_id, github.login AS github_login, planning.debut, ' . self::TALK_AND_EVENT_COLUMNS . ' + FROM afup_conferenciers speaker + INNER JOIN afup_conferenciers_sessions cs ON cs.conferencier_id = speaker.conferencier_id + INNER JOIN afup_sessions talk ON talk.session_id = cs.session_id' + . self::PLANNING_JOIN . ' + INNER JOIN afup_forum event ON event.id = talk.id_forum + LEFT JOIN afup_user_github github ON github.id = speaker.user_github + WHERE speaker.conferencier_id IN (:speakerIds) + AND ' . self::CONDITIONS . ' + ORDER BY planning.debut DESC, talk.session_id DESC, speaker.conferencier_id DESC', + ['speakerIds' => $speakerIds], + ['speakerIds' => ArrayParameterType::INTEGER], + ); + + return array_map(static fn(array $row): array => [ + 'speaker_id' => self::toInt($row['conferencier_id']), + 'talk' => self::talk($row), + 'event' => self::event($row), + 'starts_at' => self::timestamp($row['debut']), + 'github_login' => null !== $row['github_login'] ? self::toString($row['github_login']) : null, + ], $rows); + } + + /** + * @param array $row + */ + private static function talk(array $row): PublishedTalk + { + return new PublishedTalk( + self::toInt($row['session_id']), + self::toString($row['titre']), + self::nullableString($row['youtube_id']), + ); + } + + /** + * @param array $row + */ + private static function event(array $row): PublishedEvent + { + return new PublishedEvent( + self::toInt($row['event_id']), + self::toString($row['event_titre']), + self::toString($row['event_path']), + null !== $row['event_date_debut'] ? new \DateTimeImmutable(self::toString($row['event_date_debut'])) : null, + null !== $row['event_date_fin'] ? new \DateTimeImmutable(self::toString($row['event_date_fin'])) : null, + ); + } + + private static function timestamp(mixed $value): \DateTimeImmutable + { + return new \DateTimeImmutable('@' . self::toInt($value))->setTimezone(new \DateTimeZone(date_default_timezone_get())); + } + + private static function toInt(mixed $value): int + { + Assert::integerish($value); + + return (int) $value; + } + + private static function toString(mixed $value): string + { + Assert::scalar($value); + + return (string) $value; + } + + private static function nullableString(mixed $value): ?string + { + return null !== $value && '' !== $value ? self::toString($value) : null; + } +} diff --git a/tests/integration/AppBundle/Event/Talk/PublishedTalkRepositoryTest.php b/tests/integration/AppBundle/Event/Talk/PublishedTalkRepositoryTest.php new file mode 100644 index 000000000..32a8832d8 --- /dev/null +++ b/tests/integration/AppBundle/Event/Talk/PublishedTalkRepositoryTest.php @@ -0,0 +1,146 @@ +connection = self::getContainer()->get(Connection::class); + + $this->connection->insert('afup_forum', ['id' => 1, 'titre' => 'Forum PHP 2019', 'path' => 'forumphp2019', 'date_debut' => '2019-10-24', 'date_fin' => '2019-10-25', 'nb_places' => 100]); + $this->connection->insert('afup_forum', ['id' => 2, 'titre' => 'Forum PHP 2021', 'path' => 'forumphp2021', 'date_debut' => '2021-10-14', 'date_fin' => '2021-10-15', 'nb_places' => 100]); + $this->connection->insert('afup_user_github', ['id' => 7, 'github_id' => 1007, 'login' => 'hschapira', 'profile_url' => '', 'avatar_url' => '', 'afup_crew' => 0]); + + $this->connection->insert('afup_conferenciers_personnes', ['id' => 1, 'slug' => 'helene-schapira']); + $this->connection->insert('afup_conferenciers_personnes', ['id' => 2, 'slug' => 'benjamin-moules']); + + $this->insertSpeaker(10, 1, 'Hélène', 'SCHAPIRA', null, 1); + $this->insertSpeaker(20, 2, 'Helene', 'SCHAPIRA ', 7, 1); + $this->insertSpeaker(30, 2, 'Benjamin', 'MOULÈS', null, 2); + // Homonyme non rattaché à une personne : pas de page, même avec un talk publié + $this->insertSpeaker(40, 1, 'Hélène', 'SCHAPIRA', null, null); + + $past = strtotime('2019-10-24 10:00:00'); + $this->insertTalk(100, 1, 10, 'Talk publié 2019', Talk::TYPE_FULL_LONG, $past); + $this->insertTalk(200, 2, 20, 'Talk publié 2021', Talk::TYPE_FULL_LONG, strtotime('2021-10-14 10:00:00'), publishedOn: '2021-11-01 00:00:00'); + $this->insertTalk(201, 2, 20, 'Clinique', Talk::TYPE_CLINIC, $past); + $this->insertTalk(202, 2, 20, 'Présentation des speakers', Talk::TYPE_SPEAKER_INTRODUCTIONS, $past); + $this->insertTalk(203, 2, 20, 'Non planifié', Talk::TYPE_FULL_LONG, $past, scheduled: false); + $this->insertTalk(204, 2, 20, 'Publication à venir', Talk::TYPE_FULL_LONG, $past, publishedOn: '+1 day'); + $this->insertTalk(205, 2, 20, 'Créneau pas encore terminé', Talk::TYPE_FULL_LONG, time() - 600, slotEnd: time() + 600); + $this->insertTalk(206, 2, 20, 'Sans créneau', Talk::TYPE_FULL_LONG, null); + $this->insertTalk(300, 2, 30, 'Talk à venir', Talk::TYPE_FULL_LONG, strtotime('+1 month')); + $this->insertTalk(400, 1, 40, 'Talk publié sans personne', Talk::TYPE_FULL_LONG, $past); + } + + public function testSpeakerAppearancesOnlyReturnPublishedTalksOfLinkedSpeakers(): void + { + $appearances = new PublishedTalkRepository($this->connection)->getSpeakerAppearances(); + + usort($appearances, static fn(array $a, array $b): int => $a['talk_id'] <=> $b['talk_id']); + self::assertSame([ + ['speaker_id' => 10, 'personne_id' => 1, 'slug' => 'helene-schapira', 'firstname' => 'Hélène', 'lastname' => 'SCHAPIRA', 'talk_id' => 100, 'starts_at' => strtotime('2019-10-24 10:00:00')], + ['speaker_id' => 20, 'personne_id' => 1, 'slug' => 'helene-schapira', 'firstname' => 'Helene', 'lastname' => 'SCHAPIRA ', 'talk_id' => 200, 'starts_at' => strtotime('2021-10-14 10:00:00')], + ], $appearances); + } + + public function testSpeakerAppearancesAcceptARowWithoutFirstname(): void + { + // Une entreprise saisie comme speaker : prénom NULL en base (cas réel en prod). + $this->connection->insert('afup_conferenciers_personnes', ['id' => 3, 'slug' => 'alterway']); + $this->insertSpeaker(50, 1, null, 'ALTERWAY', null, 3); + $this->insertTalk(500, 1, 50, 'Talk sponsor', Talk::TYPE_FULL_LONG, strtotime('2019-10-24 11:00:00')); + + $appearances = array_values(array_filter( + new PublishedTalkRepository($this->connection)->getSpeakerAppearances(), + static fn(array $appearance): bool => $appearance['speaker_id'] === 50, + )); + + self::assertSame([['speaker_id' => 50, 'personne_id' => 3, 'slug' => 'alterway', 'firstname' => '', 'lastname' => 'ALTERWAY', 'talk_id' => 500, 'starts_at' => strtotime('2019-10-24 11:00:00')]], $appearances); + } + + public function testSpeakerTalksReturnTalksEventsAndGithubLogins(): void + { + $speakerTalks = new PublishedTalkRepository($this->connection)->getSpeakerTalks([10, 20, 30]); + + self::assertSame( + [ + [200, 'Talk publié 2021', 20, 'Forum PHP 2021', 'forumphp2021', 'hschapira', '2021-10-14 10:00'], + [100, 'Talk publié 2019', 10, 'Forum PHP 2019', 'forumphp2019', null, '2019-10-24 10:00'], + ], + array_map(static fn(array $speakerTalk): array => [ + $speakerTalk['talk']->id, + $speakerTalk['talk']->title, + $speakerTalk['speaker_id'], + $speakerTalk['event']->title, + $speakerTalk['event']->path, + $speakerTalk['github_login'], + $speakerTalk['starts_at']->format('Y-m-d H:i'), + ], $speakerTalks), + ); + self::assertSame([], new PublishedTalkRepository($this->connection)->getSpeakerTalks([])); + } + + public function testResolverBuildsTheProfileOfASpeakerAcrossEditions(): void + { + $resolver = new SpeakerProfileResolver(new PublishedTalkRepository($this->connection), self::getContainer()->get(SpeakerRepository::class)); + + self::assertSame(['helene-schapira'], array_map(static fn($identity): string => $identity->slug, $resolver->getIdentities())); + self::assertSame('helene-schapira', $resolver->getIdentityByLabel('Hélène SCHAPIRA')?->slug); + + $profile = $resolver->getProfileBySlug('helene-schapira'); + self::assertNotNull($profile); + self::assertSame([20, 10], $profile->identity->speakerIds); + self::assertSame('Bio de 20', $profile->biography); + self::assertSame(['github' => 'https://github.com/hschapira'], $profile->socialLinks); + self::assertSame([200, 100], array_map(static fn(SpeakerTalk $speakerTalk): int => $speakerTalk->talk->id, $profile->talks)); + } + + private function insertSpeaker(int $id, int $eventId, ?string $firstname, ?string $lastname, ?int $githubUserId, ?int $personneId): void + { + $this->connection->insert('afup_conferenciers', [ + 'conferencier_id' => $id, + 'id_forum' => $eventId, + 'prenom' => $firstname, + 'nom' => $lastname, + 'email' => 'speaker' . $id . '@example.com', + 'biographie' => 'Bio de ' . $id, + 'user_github' => $githubUserId, + 'personne_id' => $personneId, + ]); + } + + private function insertTalk(int $id, int $eventId, int $speakerId, string $title, int $type, ?int $slotStart, bool $scheduled = true, ?string $publishedOn = null, ?int $slotEnd = null): void + { + $this->connection->insert('afup_sessions', [ + 'session_id' => $id, + 'id_forum' => $eventId, + 'date_soumission' => '2019-01-01', + 'titre' => $title, + 'abstract' => '', + 'genre' => $type, + 'plannifie' => (int) $scheduled, + 'date_publication' => null !== $publishedOn ? date('Y-m-d H:i:s', (int) strtotime($publishedOn)) : null, + ]); + $this->connection->insert('afup_conferenciers_sessions', ['session_id' => $id, 'conferencier_id' => $speakerId]); + + if (null !== $slotStart) { + $this->connection->insert('afup_forum_planning', ['id_session' => $id, 'debut' => $slotStart, 'fin' => $slotEnd ?? $slotStart + 2400, 'id_forum' => $eventId]); + } + } +} diff --git a/tests/unit/AppBundle/Event/Speaker/SpeakerProfileResolverTest.php b/tests/unit/AppBundle/Event/Speaker/SpeakerProfileResolverTest.php new file mode 100644 index 000000000..a8344e6ae --- /dev/null +++ b/tests/unit/AppBundle/Event/Speaker/SpeakerProfileResolverTest.php @@ -0,0 +1,280 @@ + ['Hélène SCHAPIRA', 'helene schapira']; + yield 'sans accent' => ['Helene SCHAPIRA', 'helene schapira']; + yield 'double espace et accent majuscule' => ['Benjamin MOULÈS', 'benjamin moules']; + yield 'espace final' => ['Cyrille GRANDVAL ', 'cyrille grandval']; + yield 'espaces en tête et tabulation' => [" \tCyrille\t GRANDVAL", 'cyrille grandval']; + } + + public function testGroupsSpeakerRowsByPersonne(): void + { + $resolver = $this->resolver([ + self::appearance(1, 1, 'helene-schapira', 'Hélène', 'SCHAPIRA', 10, '2019-10-24'), + self::appearance(2, 1, 'helene-schapira', 'H.', 'Schapira-Martin', 20, '2021-10-14'), + self::appearance(3, 2, 'benjamin-moules', 'Benjamin', 'MOULÈS', 30, '2019-10-24'), + // Même libellé qu'une ligne de la personne 1, mais une autre personne + self::appearance(4, 3, 'helene-schapira-2', 'Hélène', 'SCHAPIRA', 40, '2022-10-13'), + // Deux talks pour la même ligne + self::appearance(3, 2, 'benjamin-moules', 'Benjamin', 'MOULÈS', 31, '2019-10-25'), + ]); + + // Triées sur le nom le plus récent : « Schapira-Martin » après « Schapira » + self::assertSame(['benjamin-moules', 'helene-schapira-2', 'helene-schapira'], self::slugs($resolver)); + self::assertSame([2, 1], $resolver->getIdentityBySlug('helene-schapira')?->speakerIds); + self::assertSame([3], $resolver->getIdentityBySlug('benjamin-moules')?->speakerIds); + self::assertSame([4], $resolver->getIdentityBySlug('helene-schapira-2')?->speakerIds); + } + + public function testSlugComesFromTheDatabaseAndNameFromTheMostRecentSpeaker(): void + { + $resolver = $this->resolver([ + self::appearance(1, 7, 'fred-dupont', 'Fred', 'Dupont', 10, '2015-10-24'), + self::appearance(2, 7, 'fred-dupont', 'Frédéric', 'Dupont', 20, '2023-10-12'), + ]); + + self::assertNull($resolver->getIdentityBySlug('frederic-dupont'), 'le slug n\'est pas recalculé depuis le nom'); + $identity = $resolver->getIdentityBySlug('fred-dupont'); + self::assertNotNull($identity); + self::assertSame('fred-dupont', $identity->slug); + self::assertSame('Frédéric Dupont', $identity->getName()); + self::assertSame('Frédéric DUPONT', $identity->getLabel()); + self::assertSame([2, 1], $identity->speakerIds); + self::assertSame('2023-10-12', $identity->latestTalkAt->format('Y-m-d')); + } + + public function testLabelDesignatesThePersonneCarryingItOnAnyOfItsRows(): void + { + $resolver = $this->resolver([ + self::appearance(1, 7, 'frederic-dupont', 'Fred', 'Dupont', 10, '2015-10-24'), + self::appearance(2, 7, 'frederic-dupont', 'Frédéric', 'Dupont', 20, '2023-10-12'), + ]); + + self::assertSame('frederic-dupont', $resolver->getIdentityByLabel('Frédéric DUPONT')?->slug); + self::assertSame('frederic-dupont', $resolver->getIdentityByLabel('Fred DUPONT ')?->slug); + self::assertSame('frederic-dupont', $resolver->getIdentityByLabel('Frederic dupont')?->slug); + self::assertNull($resolver->getIdentityByLabel('Inconnu SPEAKER')); + } + + public function testLabelCarriedBySeveralPersonnesDesignatesNoOne(): void + { + $resolver = $this->resolver([ + self::appearance(1, 5, 'jean-martin', 'Jean', 'Martin', 10, '2012-11-20'), + self::appearance(2, 6, 'jean-martin-lyon', 'Jean', 'MARTIN ', 20, '2018-10-25'), + self::appearance(3, 6, 'jean-martin-lyon', 'Jean-Paul', 'Martin', 30, '2020-10-25'), + ]); + + self::assertSame(['jean-martin', 'jean-martin-lyon'], self::slugs($resolver)); + self::assertNull($resolver->getIdentityByLabel('Jean MARTIN'), 'un libellé porté par plusieurs personnes ne désigne personne'); + self::assertSame('jean-martin-lyon', $resolver->getIdentityByLabel('Jean-Paul MARTIN')?->slug); + } + + public function testIdentitiesDoNotDependOnReadingOrder(): void + { + $appearances = [ + self::appearance(1, 1, 'helene-schapira', 'Hélène', 'SCHAPIRA', 10, '2019-10-24'), + self::appearance(2, 1, 'helene-schapira', 'Helene', 'Schapira', 20, '2021-10-14'), + self::appearance(3, 2, 'julien-durand', 'Julien', 'Durand', 30, '2016-10-27'), + self::appearance(4, 3, 'julien-durand-2', 'Julien', 'Durand', 40, '2014-06-23'), + self::appearance(5, 3, 'julien-durand-2', 'Julien', 'Durand', 50, '2024-10-10'), + self::appearance(6, 4, 'benjamin-moules', 'Benjamin', 'MOULÈS', 60, '2022-10-13'), + self::appearance(6, 4, 'benjamin-moules', 'Benjamin', 'MOULÈS', 70, '2022-10-14'), + ]; + + $expected = self::identities($this->resolver($appearances)); + + self::assertEquals($expected, self::identities($this->resolver(array_reverse($appearances)))); + // Toutes les rotations de la liste + for ($offset = 1, $count = count($appearances); $offset < $count; $offset++) { + $rotated = [...array_slice($appearances, $offset), ...array_slice($appearances, 0, $offset)]; + self::assertEquals($expected, self::identities($this->resolver($rotated))); + } + } + + public function testIdentitiesAreSortedByLastnameThenFirstname(): void + { + $resolver = $this->resolver([ + self::appearance(1, 1, 'zoe-elan', 'Zoé', 'Élan', 10, '2019-10-24'), + self::appearance(2, 2, 'anne-martin', 'Anne', 'Martin', 20, '2019-10-24'), + self::appearance(3, 3, 'aline-martin', 'Aline', 'Martin', 30, '2019-10-24'), + self::appearance(4, 4, 'paul-albert', 'Paul', 'Albert', 40, '2019-10-24'), + ]); + + self::assertSame(['paul-albert', 'zoe-elan', 'aline-martin', 'anne-martin'], self::slugs($resolver)); + } + + public function testFindsTheIdentityOfASpeakerFromAnyEditionByItsPersonne(): void + { + $resolver = $this->resolver([ + self::appearance(1, 1, 'helene-schapira', 'Hélène', 'SCHAPIRA', 10, '2019-10-24'), + self::appearance(2, 5, 'cyrille-grandval', 'Cyrille', 'Grandval', 20, '2018-10-25'), + ]); + + // Une ligne speaker connue + self::assertSame('helene-schapira', $resolver->getIdentityForSpeaker(self::speaker(1, 'Hélène', 'SCHAPIRA', 1))?->slug); + // Une ligne d'une édition à venir, rattachée à la personne + self::assertSame('cyrille-grandval', $resolver->getIdentityForSpeaker(self::speaker(99, 'C.', 'Grandval', 5))?->slug); + // Une ligne non rattachée n'a pas de personne, même si son libellé est connu + self::assertNull($resolver->getIdentityForSpeaker(self::speaker(100, 'Hélène', 'SCHAPIRA'))); + // Une personne sans talk publié + self::assertNull($resolver->getIdentityForSpeaker(self::speaker(101, 'Inconnu', 'Speaker', 9))); + + self::assertNull($resolver->getIdentityBySlug('inconnu')); + } + + public function testProfileConsolidatesTheMostRecentNonEmptyValues(): void + { + $old = self::speaker(1, 'Hélène', 'SCHAPIRA') + ->setBiography('Ancienne bio') + ->setPhoto('1.jpg') + ->setTwitter('@helene_old') + ->setLinkedin('helene-schapira'); + $middle = self::speaker(2, 'Helene', 'SCHAPIRA') + ->setBiography('Bio intermédiaire') + ->setPhoto('') + ->setMastodon('https://phpc.social/@helene') + ->setBluesky(''); + $latest = self::speaker(3, 'Hélène', 'Schapira', 1) + ->setBiography(' ') + ->setPhoto(null) + ->setTwitter('helene'); + + $speakerTalks = [ + self::speakerTalk($old, 10, '2017-10-26'), + self::speakerTalk($latest, 30, '2023-10-12', 'hschapira'), + self::speakerTalk($middle, 20, '2020-10-22'), + self::speakerTalk($middle, 21, '2020-10-23'), + // La même personne deux fois sur un même talk + self::speakerTalk($old, 21, '2020-10-23'), + ]; + + $publishedTalkRepository = $this->createMock(PublishedTalkRepository::class); + $publishedTalkRepository->method('getSpeakerAppearances')->willReturn(array_map( + static fn(SpeakerTalk $speakerTalk): array => self::appearance( + (int) $speakerTalk->speaker->getId(), + 1, + 'helene-schapira', + (string) $speakerTalk->speaker->getFirstname(), + (string) $speakerTalk->speaker->getLastname(), + $speakerTalk->talk->id, + $speakerTalk->startsAt->format('Y-m-d'), + ), + $speakerTalks, + )); + $publishedTalkRepository->expects(self::once()) + ->method('getSpeakerTalks') + ->with([3, 2, 1]) + ->willReturn(array_map(static fn(SpeakerTalk $speakerTalk): array => [ + 'speaker_id' => (int) $speakerTalk->speaker->getId(), + 'talk' => $speakerTalk->talk, + 'event' => $speakerTalk->event, + 'starts_at' => $speakerTalk->startsAt, + 'github_login' => $speakerTalk->githubLogin, + ], $speakerTalks)); + // Chaque ligne speaker est chargée une seule fois, quel que soit son nombre de talks. + $speakerRepository = $this->createMock(SpeakerRepository::class); + $speakerRepository->expects(self::exactly(3))->method('get')->willReturnMap([[3, $latest], [2, $middle], [1, $old]]); + + $profile = new SpeakerProfileResolver($publishedTalkRepository, $speakerRepository)->getProfileBySlug('helene-schapira'); + + self::assertNotNull($profile); + self::assertSame('helene-schapira', $profile->identity->slug); + self::assertSame($latest, $profile->speaker); + self::assertSame('Bio intermédiaire', $profile->biography); + self::assertSame($old, $profile->photoSpeaker); + self::assertSame([ + 'twitter' => 'https://x.com/helene', + 'mastodon' => 'https://phpc.social/@helene', + 'linkedin' => 'https://www.linkedin.com/in/helene-schapira', + 'github' => 'https://github.com/hschapira', + ], $profile->socialLinks); + self::assertSame([30, 21, 20, 10], array_map(static fn(SpeakerTalk $speakerTalk): int => $speakerTalk->talk->id, $profile->talks)); + } + + public function testNoProfileForAnUnknownSlug(): void + { + $publishedTalkRepository = $this->createMock(PublishedTalkRepository::class); + $publishedTalkRepository->method('getSpeakerAppearances')->willReturn([]); + $publishedTalkRepository->expects(self::never())->method('getSpeakerTalks'); + + self::assertNull(new SpeakerProfileResolver($publishedTalkRepository, $this->createStub(SpeakerRepository::class))->getProfileBySlug('inconnu')); + } + + /** + * @param list $appearances + */ + private function resolver(array $appearances): SpeakerProfileResolver + { + $publishedTalkRepository = $this->createStub(PublishedTalkRepository::class); + $publishedTalkRepository->method('getSpeakerAppearances')->willReturn($appearances); + + return new SpeakerProfileResolver($publishedTalkRepository, $this->createStub(SpeakerRepository::class)); + } + + /** + * @return array{speaker_id: int, personne_id: int, slug: string, firstname: string, lastname: string, talk_id: int, starts_at: int} + */ + private static function appearance(int $speakerId, int $personneId, string $slug, string $firstname, string $lastname, int $talkId, string $date): array + { + return [ + 'speaker_id' => $speakerId, + 'personne_id' => $personneId, + 'slug' => $slug, + 'firstname' => $firstname, + 'lastname' => $lastname, + 'talk_id' => $talkId, + 'starts_at' => new \DateTimeImmutable($date)->getTimestamp(), + ]; + } + + private static function speaker(int $id, string $firstname, string $lastname, ?int $personneId = null): Speaker + { + return new Speaker()->setId($id)->setFirstname($firstname)->setLastname($lastname)->setPersonneId($personneId); + } + + private static function speakerTalk(Speaker $speaker, int $talkId, string $date, ?string $githubLogin = null): SpeakerTalk + { + return new SpeakerTalk($speaker, new PublishedTalk($talkId, 'Talk ' . $talkId), new PublishedEvent(1, 'Forum PHP', 'forumphp'), new \DateTimeImmutable($date), $githubLogin); + } + + /** + * @return list + */ + private static function slugs(SpeakerProfileResolver $resolver): array + { + return array_map(static fn(SpeakerIdentity $identity): string => $identity->slug, $resolver->getIdentities()); + } + + /** + * @return list + */ + private static function identities(SpeakerProfileResolver $resolver): array + { + return $resolver->getIdentities(); + } +}