diff --git a/sources/AppBundle/Event/Model/Repository/SpeakerRepository.php b/sources/AppBundle/Event/Model/Repository/SpeakerRepository.php index 674f6237b..97ab31978 100644 --- a/sources/AppBundle/Event/Model/Repository/SpeakerRepository.php +++ b/sources/AppBundle/Event/Model/Repository/SpeakerRepository.php @@ -10,9 +10,11 @@ use AppBundle\Event\Model\Talk; use AppBundle\Event\Speaker\SpeakerSearchResult; use AppBundle\Event\Speaker\MicrophoneType; +use AppBundle\Event\Speaker\SpeakerTalk; use AppBundle\Ting\JoinHydrator; use CCMBenchmark\Ting\Driver\Mysqli\Serializer\Boolean; use CCMBenchmark\Ting\Repository\CollectionInterface; +use CCMBenchmark\Ting\Repository\Hydrator; use CCMBenchmark\Ting\Repository\HydratorArray; use CCMBenchmark\Ting\Repository\HydratorSingleObject; use CCMBenchmark\Ting\Repository\Metadata; @@ -27,6 +29,25 @@ */ class SpeakerRepository extends Repository implements MetadataInitializer { + /** + * Jointures et conditions d'un talk publié, vu depuis ses speakers : planifié, ni clinique ni + * présentation des speakers (l'équivalent SQL de Talk::isDisplayedOnHistory(), le filtre de la + * page du talk), avec un créneau terminé et une date de publication vide ou passée. + */ + private const string PUBLISHED_SPEAKER_TALKS_JOINS = ' + 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 + INNER JOIN ( + SELECT id_session, MIN(debut) AS debut, MIN(fin) AS fin FROM afup_forum_planning GROUP BY id_session + ) planning ON planning.id_session = talk.session_id'; + + private const string PUBLISHED_SPEAKER_TALKS_CONDITIONS = ' + talk.plannifie = 1 + AND talk.genre NOT IN (' . Talk::TYPE_CLINIC . ', ' . Talk::TYPE_SPEAKER_INTRODUCTIONS . ') + AND planning.fin <= UNIX_TIMESTAMP() + AND (talk.date_publication < NOW() OR talk.date_publication IS NULL)'; + /** * @return CollectionInterface&iterable */ @@ -318,6 +339,89 @@ public function searchSpeakers(Event $event, $sort = 'name', $direction = 'asc', return $query->query($this->getCollection(new HydratorSingleObject())); } + /** + * Les lignes speaker rattachées à une personne qui ont un talk publié, toutes éditions confondues, + * une ligne par couple speaker / talk, sans hydrater d'entité : de quoi construire l'index des personnes. + * Les lignes sans personne sont écartées. + * + * @return list + */ + public function getPublishedTalkAppearances(): array + { + $query = $this->getQuery( + 'SELECT speaker.conferencier_id AS speaker_id, person.id AS person_id, person.slug, + speaker.prenom AS firstname, speaker.nom AS lastname, talk.session_id AS talk_id, planning.debut AS starts_at' + . self::PUBLISHED_SPEAKER_TALKS_JOINS + . ' INNER JOIN afup_speaker_person person ON person.id = speaker.person_id' + . ' WHERE ' . self::PUBLISHED_SPEAKER_TALKS_CONDITIONS, + ); + + $appearances = []; + /** @var array{speaker_id: int|string, person_id: int|string, slug: string, firstname: string|null, lastname: string|null, talk_id: int|string, starts_at: int|string} $row */ + foreach ($query->query($this->getCollection(new HydratorArray())) as $row) { + $appearances[] = [ + 'speaker_id' => (int) $row['speaker_id'], + 'person_id' => (int) $row['person_id'], + 'slug' => $row['slug'], + 'firstname' => (string) $row['firstname'], + 'lastname' => (string) $row['lastname'], + 'talk_id' => (int) $row['talk_id'], + 'starts_at' => (int) $row['starts_at'], + ]; + } + + return $appearances; + } + + /** + * 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 getPublishedSpeakerTalks(array $speakerIds): array + { + if ($speakerIds === []) { + return []; + } + + $params = []; + foreach ($speakerIds as $index => $speakerId) { + $params['speaker' . $index] = $speakerId; + } + + $query = $this->getPreparedQuery( + 'SELECT speaker.conferencier_id, speaker.id_forum, speaker.nom, speaker.prenom, speaker.societe, + speaker.biographie, speaker.twitter, speaker.mastodon, speaker.bluesky, speaker.linkedin, + speaker.user_github, speaker.photo, + talk.session_id, talk.id_forum, talk.titre, talk.genre, talk.plannifie, talk.youtube_id, talk.language_code, + event.id, event.titre, event.path, event.date_debut, event.date_fin, + github.login AS github_login, + planning.debut AS starts_at' + . self::PUBLISHED_SPEAKER_TALKS_JOINS + . ' 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 (:' . implode(', :', array_keys($params)) . ') + AND ' . self::PUBLISHED_SPEAKER_TALKS_CONDITIONS + . ' ORDER BY planning.debut DESC, talk.session_id DESC, speaker.conferencier_id DESC', + )->setParams($params); + + $speakerTalks = []; + /** @var array{speaker: Speaker, talk: Talk, event: Event, 0: object{starts_at: int|string, github_login: string|null}} $row */ + foreach ($query->query($this->getCollection(new Hydrator())) as $row) { + $speakerTalks[] = new SpeakerTalk( + $row['speaker'], + $row['talk'], + $row['event'], + new \DateTimeImmutable('@' . $row[0]->starts_at)->setTimezone(new \DateTimeZone(date_default_timezone_get())), + $row[0]->github_login, + ); + } + + return $speakerTalks; + } + public function countByEvent(Event $event): int { $query = $this->getPreparedQuery('SELECT COUNT(*) AS nb FROM (SELECT nom, prenom FROM afup_conferenciers WHERE id_forum = :eventId GROUP BY nom, prenom) c') 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..61de17689 --- /dev/null +++ b/sources/AppBundle/Event/Speaker/SpeakerProfileResolver.php @@ -0,0 +1,249 @@ +, + * byPersonId: array, + * byLabel: array, + * }|null + */ + private ?array $index = null; + + private readonly Slugify $slugify; + + public function __construct(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 + { + $personId = $speaker->getPersonId(); + if (null === $personId) { + return null; + } + + $index = $this->getIndex(); + $slug = $index['byPersonId'][$personId] ?? 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->speakerRepository->getPublishedSpeakerTalks($identity->speakerIds); + if ($speakerTalks === []) { + return null; + } + + return $this->buildProfile($identity, $speakerTalks); + } + + public function reset(): void + { + $this->index = null; + } + + /** + * @return array{ + * bySlug: array, + * byPersonId: array, + * byLabel: array, + * } + */ + private function getIndex(): array + { + return $this->index ??= $this->buildIndex($this->speakerRepository->getPublishedTalkAppearances()); + } + + /** + * @param list $appearances + * + * @return array{ + * bySlug: array, + * byPersonId: 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['person_id']][] = $appearance; + $slugsByLabel[self::normalizeLabel($appearance['firstname'] . ' ' . $appearance['lastname'])][$appearance['slug']] = true; + } + + $index = ['bySlug' => [], 'byPersonId' => [], 'byLabel' => []]; + $identities = []; + foreach ($groups as $personId => $personAppearances) { + $latest = $personAppearances[0]; + $identities[] = new SpeakerIdentity( + $latest['slug'], + $latest['firstname'], + $latest['lastname'], + array_values(array_unique(array_column($personAppearances, 'speaker_id'))), + new \DateTimeImmutable('@' . $latest['starts_at'])->setTimezone(new \DateTimeZone(date_default_timezone_get())), + ); + $index['byPersonId'][$personId] = $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; + } + + /** + * @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->getId(), + $b->speaker->getId(), + ] <=> [ + $a->startsAt->getTimestamp(), + $a->talk->getId(), + $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[(int) $speakerTalk->talk->getId()] ??= $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..09119768f --- /dev/null +++ b/sources/AppBundle/Event/Speaker/SpeakerTalk.php @@ -0,0 +1,23 @@ +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_speaker_person', ['id' => 1, 'slug' => 'helene-schapira']); + $this->connection->insert('afup_speaker_person', ['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 testGetPublishedTalkAppearancesOnlyReturnsPublishedTalksOfLinkedSpeakers(): void + { + $appearances = self::getContainer()->get(SpeakerRepository::class)->getPublishedTalkAppearances(); + + usort($appearances, static fn(array $a, array $b): int => $a['talk_id'] <=> $b['talk_id']); + self::assertSame([ + ['speaker_id' => 10, 'person_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, 'person_id' => 1, 'slug' => 'helene-schapira', 'firstname' => 'Helene', 'lastname' => 'SCHAPIRA ', 'talk_id' => 200, 'starts_at' => strtotime('2021-10-14 10:00:00')], + ], $appearances); + } + + public function testGetPublishedSpeakerTalksHydratesTalksEventsAndGithubLogins(): void + { + $speakerTalks = self::getContainer()->get(SpeakerRepository::class)->getPublishedSpeakerTalks([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(SpeakerTalk $speakerTalk): array => [ + $speakerTalk->talk->getId(), + $speakerTalk->talk->getTitle(), + $speakerTalk->speaker->getId(), + $speakerTalk->event->getTitle(), + $speakerTalk->event->getPath(), + $speakerTalk->githubLogin, + $speakerTalk->startsAt->format('Y-m-d H:i'), + ], $speakerTalks), + ); + self::assertSame([], self::getContainer()->get(SpeakerRepository::class)->getPublishedSpeakerTalks([])); + } + + public function testResolverBuildsTheProfileOfASpeakerAcrossEditions(): void + { + $resolver = new SpeakerProfileResolver(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->getId(), $profile->talks)); + } + + private function insertSpeaker(int $id, int $eventId, string $firstname, string $lastname, ?int $githubUserId, ?int $personId): 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, + 'person_id' => $personId, + ]); + } + + 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..429f51bc5 --- /dev/null +++ b/tests/unit/AppBundle/Event/Speaker/SpeakerProfileResolverTest.php @@ -0,0 +1,270 @@ + ['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 testGroupsSpeakerRowsByPerson(): 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 testLabelDesignatesThePersonCarryingItOnAnyOfItsRows(): 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 testLabelCarriedBySeveralPersonsDesignatesNoOne(): 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 testFindsTheIdentityOfASpeakerFromAnyEditionByItsPerson(): 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'), + ]; + + $speakerRepository = $this->createMock(SpeakerRepository::class); + $speakerRepository->method('getPublishedTalkAppearances')->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(), + (int) $speakerTalk->talk->getId(), + $speakerTalk->startsAt->format('Y-m-d'), + ), + $speakerTalks, + )); + $speakerRepository->expects(self::once()) + ->method('getPublishedSpeakerTalks') + ->with([3, 2, 1]) + ->willReturn($speakerTalks); + + $profile = new SpeakerProfileResolver($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->getId(), $profile->talks)); + } + + public function testNoProfileForAnUnknownSlug(): void + { + $speakerRepository = $this->createMock(SpeakerRepository::class); + $speakerRepository->method('getPublishedTalkAppearances')->willReturn([]); + $speakerRepository->expects(self::never())->method('getPublishedSpeakerTalks'); + + self::assertNull(new SpeakerProfileResolver($speakerRepository)->getProfileBySlug('inconnu')); + } + + /** + * @param list $appearances + */ + private function resolver(array $appearances): SpeakerProfileResolver + { + $speakerRepository = $this->createStub(SpeakerRepository::class); + $speakerRepository->method('getPublishedTalkAppearances')->willReturn($appearances); + + return new SpeakerProfileResolver($speakerRepository); + } + + /** + * @return array{speaker_id: int, person_id: int, slug: string, firstname: string, lastname: string, talk_id: int, starts_at: int} + */ + private static function appearance(int $speakerId, int $personId, string $slug, string $firstname, string $lastname, int $talkId, string $date): array + { + return [ + 'speaker_id' => $speakerId, + 'person_id' => $personId, + '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 $personId = null): Speaker + { + return new Speaker()->setId($id)->setFirstname($firstname)->setLastname($lastname)->setPersonId($personId); + } + + private static function speakerTalk(Speaker $speaker, int $talkId, string $date, ?string $githubLogin = null): SpeakerTalk + { + return new SpeakerTalk($speaker, new Talk()->setId($talkId), new Event(), 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(); + } +}