2020-07-19 20:12:08 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
2020-08-24 09:26:44 +01:00
|
|
|
namespace Drupal\opdavies_blog\EventSubscriber;
|
2020-07-19 20:12:08 +01:00
|
|
|
|
2020-09-06 12:05:45 +01:00
|
|
|
use Drupal\core_event_dispatcher\Event\Entity\AbstractEntityEvent;
|
2020-07-19 20:12:08 +01:00
|
|
|
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
|
2020-08-24 09:26:44 +01:00
|
|
|
use Drupal\opdavies_blog\Entity\Node\Post;
|
2021-01-01 22:35:52 +00:00
|
|
|
use Drupal\opdavies_blog\Service\PostPusher\PostPusher;
|
2020-07-19 20:12:08 +01:00
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
|
|
|
|
|
|
final class PushBlogPostToSocialMedia implements EventSubscriberInterface {
|
|
|
|
|
2021-01-01 22:35:52 +00:00
|
|
|
private PostPusher $postPusher;
|
2020-08-28 12:35:00 +01:00
|
|
|
|
2021-01-01 22:35:52 +00:00
|
|
|
public function __construct(PostPusher $postPusher) {
|
|
|
|
$this->postPusher = $postPusher;
|
2020-08-28 12:35:00 +01:00
|
|
|
}
|
|
|
|
|
2020-07-19 20:12:08 +01:00
|
|
|
/**
|
|
|
|
* @inheritDoc
|
|
|
|
*/
|
|
|
|
public static function getSubscribedEvents() {
|
|
|
|
return [
|
2020-09-04 19:19:18 +01:00
|
|
|
HookEventDispatcherInterface::ENTITY_INSERT => 'onEntityUpdate',
|
|
|
|
HookEventDispatcherInterface::ENTITY_UPDATE => 'onEntityUpdate',
|
2020-07-19 20:12:08 +01:00
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2020-09-06 12:05:45 +01:00
|
|
|
public function onEntityUpdate(AbstractEntityEvent $event): void {
|
2020-07-19 20:12:08 +01:00
|
|
|
$entity = $event->getEntity();
|
|
|
|
|
|
|
|
if ($entity->getEntityTypeId() != 'node') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-08-14 14:01:23 +01:00
|
|
|
/** @var Post $entity */
|
2020-07-19 20:12:08 +01:00
|
|
|
if ($entity->bundle() != 'post') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-01-01 21:50:30 +00:00
|
|
|
if (!$this->shouldBePushed($entity)) {
|
2020-08-28 11:35:54 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-01-01 22:35:52 +00:00
|
|
|
$this->postPusher->push($entity);
|
2020-08-12 20:28:19 +01:00
|
|
|
|
2020-11-10 19:51:53 +00:00
|
|
|
$entity->markAsSentToSocialMedia();
|
2020-09-04 19:19:18 +01:00
|
|
|
$entity->save();
|
2020-07-19 20:12:08 +01:00
|
|
|
}
|
|
|
|
|
2021-01-01 21:50:30 +00:00
|
|
|
private function shouldBePushed(Post $post): bool {
|
|
|
|
if ($post->isExternalPost()) {
|
|
|
|
return FALSE;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!$post->isPublished()) {
|
|
|
|
return FALSE;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!$post->shouldSendToSocialMedia()) {
|
|
|
|
return FALSE;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($post->hasBeenSentToSocialMedia()) {
|
|
|
|
return FALSE;
|
|
|
|
}
|
|
|
|
|
|
|
|
return TRUE;
|
|
|
|
}
|
|
|
|
|
2020-07-19 20:12:08 +01:00
|
|
|
}
|