Don't send posts to social media multiple times

Check if a post has previously been sent to social media, by checking
the value of a `field_sent_to_social_media` field.

This field is hidden on the node add/edit forms, and populated when a
post is sent to social media. Once this happens, it will not be sent to
social media again.

This change also populates the field for all existing posts, so that
they won't be re-sent to social media either.
This commit is contained in:
Oliver Davies 2020-08-12 20:28:19 +01:00
parent 8761f9c4cc
commit 8385d6fef7
10 changed files with 114 additions and 2 deletions

View file

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
use Drupal\custom\Repository\PostRepository;
/**
* Mark existing blog posts as sent to social media.
*/
function custom_update_8001(): void {
$posts = \Drupal::service(PostRepository::class)->getAll();
foreach ($posts as $post) {
$post->set('field_sent_to_social_media', TRUE);
$post->save();
}
}

View file

@ -7,5 +7,8 @@ services:
tags:
- { name: event_subscriber }
Drupal\custom\Repository\PostRepository:
autowire: true
Drupal\custom\Service\TalkCounter:
autowire: true

View file

@ -18,6 +18,10 @@ use Drupal\node\Entity\Node;
*/
class Post extends Node implements ContentEntityBundleInterface {
public function hasBeenSentToSocialMedia(): bool {
return (bool) $this->get('field_sent_to_social_media')->getString();
}
public function hasTweet(): bool {
return (bool) $this->get('field_has_tweet')->getString();
}

View file

@ -37,7 +37,10 @@ final class PushBlogPostToSocialMedia implements EventSubscriberInterface {
return;
}
// TODO: Check that the post has not already been pushed.
// If this post has already been sent to social media, do not send it again.
if ($entity->hasBeenSentToSocialMedia()) {
return;
}
$url = \Drupal::configFactory()->get('opdavies_talks.config')
->get('zapier_post_tweet_url');
@ -47,6 +50,8 @@ final class PushBlogPostToSocialMedia implements EventSubscriberInterface {
'message' => $entity->toTweet(),
],
]);
$entity->set('field_sent_to_social_media', TRUE);
}
}

View file

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Drupal\custom\Repository;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Illuminate\Support\Collection;
final class PostRepository {
private EntityStorageInterface $nodeStorage;
public function __construct(EntityTypeManagerInterface $entityTypeManager) {
$this->nodeStorage = $entityTypeManager->getStorage('node');
}
public function getAll(): Collection {
return new Collection(
$this->nodeStorage->loadByProperties([
'type' => 'post',
])
);
}
}