|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Netgen\Bundle\SiteBundle\EventListener\Content; |
| 6 | + |
| 7 | +use DateTimeInterface; |
| 8 | +use Ibexa\Contracts\Core\Repository\ContentService; |
| 9 | +use Ibexa\Contracts\Core\Repository\Events\Content\PublishVersionEvent; |
| 10 | +use Ibexa\Contracts\Core\SiteAccess\ConfigResolverInterface; |
| 11 | +use Ibexa\Core\FieldType\DateAndTime\Value as DateAndTimeValue; |
| 12 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 13 | + |
| 14 | +use function array_key_exists; |
| 15 | + |
| 16 | +final class CreationDateEventListener implements EventSubscriberInterface |
| 17 | +{ |
| 18 | + public function __construct( |
| 19 | + private ConfigResolverInterface $configResolver, |
| 20 | + private ContentService $contentService, |
| 21 | + ) { |
| 22 | + } |
| 23 | + |
| 24 | + public static function getSubscribedEvents(): array |
| 25 | + { |
| 26 | + return [ |
| 27 | + PublishVersionEvent::class => ['onPublishVersion', 255], |
| 28 | + ]; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Sets the creation date of the content based on a field value. |
| 33 | + */ |
| 34 | + public function onPublishVersion(PublishVersionEvent $event): void |
| 35 | + { |
| 36 | + /** @var bool $listenerEnabled */ |
| 37 | + $listenerEnabled = $this->configResolver->getParameter('set_creation_date.enabled', 'ngsite'); |
| 38 | + if (!$listenerEnabled) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + /** @var array<string, string> $fieldConfig */ |
| 43 | + $fieldConfig = $this->configResolver->getParameter('set_creation_date.fields', 'ngsite'); |
| 44 | + |
| 45 | + $content = $event->getContent(); |
| 46 | + $contentTypeIdentifier = $content->getContentType()->identifier; |
| 47 | + if (!array_key_exists($contentTypeIdentifier, $fieldConfig)) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + if (!isset($content->fields[$fieldConfig[$contentTypeIdentifier]])) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + $creationDate = $content->getFieldValue($fieldConfig[$contentTypeIdentifier]); |
| 56 | + if (!$creationDate instanceof DateAndTimeValue || !$creationDate->value instanceof DateTimeInterface) { |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + $updateStruct = $this->contentService->newContentMetadataUpdateStruct(); |
| 61 | + $updateStruct->publishedDate = $creationDate->value; |
| 62 | + |
| 63 | + $this->contentService->updateContentMetadata($content->contentInfo, $updateStruct); |
| 64 | + } |
| 65 | +} |
0 commit comments