diff --git a/.idea/php.xml b/.idea/php.xml index 6d17c0687..d34eca7ef 100644 --- a/.idea/php.xml +++ b/.idea/php.xml @@ -139,6 +139,8 @@ + + diff --git a/web/modules/custom/custom/custom.services.yml b/web/modules/custom/custom/custom.services.yml index 21bb95742..1993b99c1 100644 --- a/web/modules/custom/custom/custom.services.yml +++ b/web/modules/custom/custom/custom.services.yml @@ -2,3 +2,6 @@ services: Drupal\custom\EventSubscriber\UpdateTalkNodeBeforeSave: tags: - { name: event_subscriber } + + Drupal\custom\Service\TalkCounter: + autowire: true diff --git a/web/modules/custom/custom/src/Service/TalkCounter.php b/web/modules/custom/custom/src/Service/TalkCounter.php new file mode 100644 index 000000000..933ab00fa --- /dev/null +++ b/web/modules/custom/custom/src/Service/TalkCounter.php @@ -0,0 +1,41 @@ +nodeStorage = $entityTypeManager->getStorage('node'); + } + + public function getCount(): int { + $today = Carbon::today()->format('Y-m-d H:i:s'); + + return $this->getTalks() + ->flatMap->getEvents() + ->filter(fn(ParagraphInterface $event) => $event->get('field_date')->getString() <= $today) + ->count(); + } + + private function getTalks(): Collection { + $talks = $this->nodeStorage->loadByProperties([ + 'status' => NodeInterface::PUBLISHED, + 'type' => 'talk', + ]); + + return new Collection($talks); + } + +} diff --git a/web/modules/custom/custom/tests/src/Kernel/CountPreviousTalksTest.php b/web/modules/custom/custom/tests/src/Kernel/CountPreviousTalksTest.php new file mode 100644 index 000000000..861f5fa4f --- /dev/null +++ b/web/modules/custom/custom/tests/src/Kernel/CountPreviousTalksTest.php @@ -0,0 +1,66 @@ +createTalk([ + 'field_events' => [ + $this->createEvent(), + $this->createEvent(), + ], + ]); + + $this->createTalk([ + 'field_events' => [ + $this->createEvent(), + ], + ]); + + Assert::assertSame(3, $this->talkCounter->getCount()); + } + + /** @test */ + public function future_talks_are_not_counted(): void { + $this->createTalk([ + 'field_events' => [ + $this->createEvent([ + 'field_date' => Carbon::now()->subDay(), + ]), + $this->createEvent([ + 'field_date' => Carbon::now()->addDay(), + ]), + ], + ]); + + Assert::assertSame(1, $this->talkCounter->getCount()); + } + + /** @test */ + public function unpublished_talks_are_not_counted(): void { + $this->createTalk([ + 'field_events' => [$this->createEvent()], + 'status' => NodeInterface::NOT_PUBLISHED, + ]); + + Assert::assertSame(0, $this->talkCounter->getCount()); + } + + protected function setUp() { + parent::setUp(); + + $this->talkCounter = $this->container->get(TalkCounter::class); + } + +}