Add the ability to add links to external blog posts within my blog feed. This is done based on a new `field_external_link` field that allows for adding the external link URL and the domain name as the title. The node links are then overridden to use the external link if there is one, so the node title and 'read more' links are changed to use the external link. Currently, automated tweets are not generated for external posts. Fixes #182
60 lines
1.3 KiB
PHP
60 lines
1.3 KiB
PHP
<?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 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 Post $entity */
|
|
if ($entity->bundle() != 'post') {
|
|
return;
|
|
}
|
|
|
|
if (!$entity->isPublished()) {
|
|
return;
|
|
}
|
|
|
|
// If this post has already been sent to social media, do not send it again.
|
|
if ($entity->hasBeenSentToSocialMedia()) {
|
|
return;
|
|
}
|
|
|
|
if ($entity->isExternalPost()) {
|
|
return;
|
|
}
|
|
|
|
$url = \Drupal::configFactory()->get('opdavies_talks.config')
|
|
->get('zapier_post_tweet_url');
|
|
|
|
\Drupal::httpClient()->post($url, [
|
|
'form_params' => [
|
|
'message' => $entity->toTweet(),
|
|
],
|
|
]);
|
|
|
|
$entity->set('field_sent_to_social_media', TRUE);
|
|
}
|
|
|
|
}
|