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
|
|
|
|
|
|
|
use Drupal\hook_event_dispatcher\Event\Entity\BaseEntityEvent;
|
|
|
|
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
|
2020-08-24 09:26:44 +01:00
|
|
|
use Drupal\opdavies_blog\Entity\Node\Post;
|
2020-07-19 20:12:08 +01:00
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
|
|
|
|
|
|
|
|
final class PushBlogPostToSocialMedia implements EventSubscriberInterface {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @inheritDoc
|
|
|
|
*/
|
|
|
|
public static function getSubscribedEvents() {
|
|
|
|
return [
|
|
|
|
HookEventDispatcherInterface::ENTITY_PRE_SAVE => 'onEntityPreSave',
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
public function onEntityPresave(BaseEntityEvent $event): void {
|
|
|
|
$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;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!$entity->isPublished()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-08-12 20:28:19 +01:00
|
|
|
// If this post has already been sent to social media, do not send it again.
|
|
|
|
if ($entity->hasBeenSentToSocialMedia()) {
|
|
|
|
return;
|
|
|
|
}
|
2020-07-19 20:12:08 +01:00
|
|
|
|
2020-08-14 14:01:23 +01:00
|
|
|
if ($entity->isExternalPost()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-07-19 20:12:08 +01:00
|
|
|
$url = \Drupal::configFactory()->get('opdavies_talks.config')
|
|
|
|
->get('zapier_post_tweet_url');
|
|
|
|
|
2020-08-28 11:35:54 +01:00
|
|
|
if (!$url) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-07-19 20:12:08 +01:00
|
|
|
\Drupal::httpClient()->post($url, [
|
|
|
|
'form_params' => [
|
|
|
|
'message' => $entity->toTweet(),
|
|
|
|
],
|
|
|
|
]);
|
2020-08-12 20:28:19 +01:00
|
|
|
|
|
|
|
$entity->set('field_sent_to_social_media', TRUE);
|
2020-07-19 20:12:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|