oliverdavies.uk/modules/opd_daily_emails/src/AddRandomCtaToDailyEmail.php
Oliver Davies 9abf64b504 Don't add a CTA if an emails contains a P.S.
Don't automatically add a CTA to a daily email if the email body text
already contains a "P.S.".
2025-06-21 00:34:47 +01:00

45 lines
1.1 KiB
PHP

<?php
declare(strict_types=1);
namespace Drupal\opd_daily_emails;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\NodeInterface;
use Drupal\opd_daily_emails\Ctas;
readonly final class AddRandomCtaToDailyEmail {
public function __construct(private EntityTypeManagerInterface $entityTypeManager) {
}
public function __invoke(DailyEmail $email): void {
if (!$email->isNew()) {
return;
}
if ($email->get('field_daily_email_cta')->getValue() !== []) {
return;
}
if (str_contains(haystack: $email->get('body')->value, needle: 'P.S.')) {
return;
}
$nodeStorage = $this->entityTypeManager->getStorage('node');
$query = $nodeStorage->getQuery();
$query->condition('status', NodeInterface::PUBLISHED);
$query->condition('type', 'daily_email_cta');
$query->accessCheck();
$ctaNodes = $nodeStorage->loadMultiple($query->execute());
$ctas = Ctas::fromNodes($ctaNodes);
if ($ctas->isEmpty()) {
return;
}
$email->set('field_daily_email_cta', $ctas->getRandomCta());
}
}