postoffice-1.0.x-dev/extensions/postoffice_file/src/EventSubscriber/FileAdjustmentSubscriber.php
extensions/postoffice_file/src/EventSubscriber/FileAdjustmentSubscriber.php
<?php
namespace Drupal\postoffice_file\EventSubscriber;
use Drupal\Component\Utility\Html;
use Drupal\file\Entity\File;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Mailer\Event\MessageEvent;
use Symfony\Component\Mime\Email;
/**
* Applies file adjustments defined by field formatter third party settings.
*
* Runs with priority -50 (after Symfony MessageListener which is responsible
* for body rendering).
*/
class FileAdjustmentSubscriber implements EventSubscriberInterface {
/**
* Constructs new message subscriber for email image adjustments.
*/
public function __construct(protected RequestStack $requestStack) {
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[MessageEvent::class] = ['onMessage', -50];
return $events;
}
/**
* Attach files supplied by file field formatter.
*/
public function onMessage(MessageEvent $event): void {
$message = $event->getMessage();
if (
$message instanceof Email &&
$message->getHtmlBody() && (
strpos($message->getHtmlBody(), 'data-postoffice-file-attach-target-id') !== FALSE ||
strpos($message->getHtmlBody(), 'data-postoffice-file-transform-urls') !== FALSE
)
) {
$dom = Html::load($message->getHtmlBody());
$xpath = new \DOMXpath($dom);
foreach ($xpath->query("//*[@data-postoffice-file-attach-target-id]") as $node) {
$fileId = $node->getAttribute('data-postoffice-file-attach-target-id');
$file = File::load($fileId);
if ($file) {
$uri = $file->getFileUri();
if (!empty($uri)) {
$name = \urlencode(\basename($uri));
$message->attachFromPath($uri, $name);
}
}
}
$changed = FALSE;
foreach ($xpath->query("//*[@data-postoffice-file-transform-urls]/*[starts-with(@href, '/') and not(starts-with(@href, '//'))]") as $node) {
$url = $this->getSchemeAndHttpHost() . $node->getAttribute('href');
$node->setAttribute('href', $url);
$changed = TRUE;
}
foreach ($xpath->query("//*[@data-postoffice-file-remove]") as $node) {
$node->parentNode->removeChild($node);
$changed = TRUE;
}
if ($changed) {
$message->html(Html::serialize($dom));
}
}
}
/**
* Returns scheme and HTTP host.
*/
protected function getSchemeAndHttpHost(): string {
$request = $this->requestStack->getCurrentRequest();
return $request->getSchemeAndHttpHost();
}
}
