Automatically create tweets for new posts

This commit is contained in:
Oliver Davies 2020-07-19 20:12:08 +01:00
parent eafcb103b8
commit f488b5c023
6 changed files with 84 additions and 7 deletions

View file

@ -0,0 +1,6 @@
opdavies_talks.settings:
type: config_object
label: 'Talks module configuration'
mapping:
zapier_post_tweet_url:
type: string

View file

@ -3,5 +3,9 @@ services:
tags:
- { name: event_subscriber }
Drupal\custom\EventSubscriber\PushBlogPostToSocialMedia:
tags:
- { name: event_subscriber }
Drupal\custom\Service\TalkCounter:
autowire: true

View file

@ -22,4 +22,12 @@ class Post extends Node implements ContentEntityBundleInterface {
return (bool) $this->get('field_has_tweet')->getString();
}
public function toTweet(): string {
// TODO: Add tags.
$parts = [$this->label(), $this->url('canonical', ['absolute' => TRUE])];
return implode(PHP_EOL . PHP_EOL, $parts);
}
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Drupal\custom\EventSubscriber;
use Drupal\custom\Entity\Node\Post;
use Drupal\hook_event_dispatcher\Event\Entity\BaseEntityEvent;
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
use Drupal\node\NodeInterface;
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;
}
/** @var NodeInterface $entity */
if ($entity->bundle() != 'post') {
return;
}
if (!$entity->isPublished()) {
return;
}
// TODO: Check that the post has not already been pushed.
$url = \Drupal::configFactory()->get('opdavies_talks.config')
->get('zapier_post_tweet_url');
\Drupal::httpClient()->post($url, [
'form_params' => [
'message' => $entity->toTweet(),
],
]);
}
}