2020-05-08 18:46:31 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
2020-08-24 09:26:44 +01:00
|
|
|
namespace Drupal\opdavies_talks\EventSubscriber;
|
2020-05-08 18:46:31 +01:00
|
|
|
|
2020-05-09 21:51:04 +01:00
|
|
|
use Carbon\Carbon;
|
2020-09-06 12:05:45 +01:00
|
|
|
use Drupal\core_event_dispatcher\Event\Entity\AbstractEntityEvent;
|
2020-05-08 18:46:31 +01:00
|
|
|
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
|
2020-08-24 09:26:44 +01:00
|
|
|
use Drupal\opdavies_talks\Entity\Node\Talk;
|
2020-05-29 02:30:29 +01:00
|
|
|
use Drupal\paragraphs\ParagraphInterface;
|
2020-05-08 18:46:31 +01:00
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
|
|
|
|
|
|
/**
|
2020-05-29 02:30:29 +01:00
|
|
|
* Update a talk node before it's saved.
|
2020-05-08 18:46:31 +01:00
|
|
|
*/
|
2020-05-29 02:30:29 +01:00
|
|
|
final class UpdateTalkNodeBeforeSave implements EventSubscriberInterface {
|
2020-05-08 18:46:31 +01:00
|
|
|
|
|
|
|
public static function getSubscribedEvents() {
|
|
|
|
return [
|
2020-05-26 12:00:35 +01:00
|
|
|
HookEventDispatcherInterface::ENTITY_PRE_SAVE => 'onEntityPreSave',
|
2020-05-08 18:46:31 +01:00
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2020-09-06 12:05:45 +01:00
|
|
|
public function onEntityPreSave(AbstractEntityEvent $event): void {
|
2020-05-10 13:15:07 +01:00
|
|
|
if ($event->getEntity()->getEntityTypeId() != 'node') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($event->getEntity()->bundle() != 'talk') {
|
2020-05-08 18:46:31 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-09-04 20:49:23 +01:00
|
|
|
/** @var Talk $talk */
|
2020-06-01 19:03:25 +01:00
|
|
|
$talk = $event->getEntity();
|
|
|
|
$this->reorderEvents($talk);
|
|
|
|
$this->updateCreatedDate($talk);
|
2020-05-08 18:46:31 +01:00
|
|
|
}
|
|
|
|
|
2020-05-29 02:30:29 +01:00
|
|
|
private function reorderEvents(Talk $talk): void {
|
|
|
|
$events = $talk->getEvents();
|
|
|
|
|
|
|
|
$eventsByDate = $events
|
|
|
|
->sortBy(fn(ParagraphInterface $event) => $event->get('field_date')
|
|
|
|
->getString())
|
|
|
|
->values();
|
|
|
|
|
|
|
|
// If the original event IDs don't match the sorted event IDs, update the
|
|
|
|
// event field to use the sorted ones.
|
|
|
|
if ($events->map->id() != $eventsByDate->map->id()) {
|
2020-11-10 19:34:15 +00:00
|
|
|
$talk->set(Talk::FIELD_EVENTS, $eventsByDate->toArray());
|
2020-05-29 02:30:29 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private function updateCreatedDate(Talk $talk): void {
|
2020-05-09 22:31:34 +01:00
|
|
|
if (!$eventDate = $talk->findLatestEventDate()) {
|
2020-05-08 18:46:31 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-05-09 21:51:04 +01:00
|
|
|
$talkDate = Carbon::parse($eventDate)->getTimestamp();
|
2020-05-08 18:46:31 +01:00
|
|
|
|
|
|
|
if ($talkDate == $talk->get('created')->getString()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
$talk->set('created', $talkDate);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|