repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/MemoryDriver.php
Mailer/extensions/mailer-module/src/Hermes/MemoryDriver.php
<?php namespace Remp\MailerModule\Hermes; use Closure; use Tomaj\Hermes\Dispatcher; use Tomaj\Hermes\Driver\DriverInterface; use Tomaj\Hermes\Driver\NotSupportedException; use Tomaj\Hermes\Driver\SerializerAwareTrait; use Tomaj\Hermes\MessageInterface; use Tomaj\Hermes\MessageSerializer; class MemoryDriver implements DriverInterface { use SerializerAwareTrait; private $events = []; private $waitResult = null; private $executeAtCheckEnabled = false; private $oneLoopDurationSeconds = 60; public function __construct($events = null) { $this->serializer = new MessageSerializer(); if (!$events) { $events = []; } foreach ($events as $event) { $this->events[] = $this->serializer->serialize($event); } } // To simulate execute_at functionality, call this function after initialization public function enableExecuteAtCheck($oneLoopDurationSeconds = 60) { $this->executeAtCheckEnabled = true; $this->oneLoopDurationSeconds = $oneLoopDurationSeconds; } public function send(MessageInterface $message, int $priority = Dispatcher::DEFAULT_PRIORITY): bool { $this->events[] = $this->serializer->serialize($message); return true; } public function setupPriorityQueue(string $name, int $priority): void { throw new NotSupportedException(); } public function getMessage() { $message = array_pop($this->events); if (!$message) { return null; } return $this->serializer->unserialize($message); } public function wait(Closure $callback, array $priorities): void { $futureMessages = []; while (count($this->events) > 0) { $event = array_pop($this->events); $m = $this->serializer->unserialize($event); if ($this->executeAtCheckEnabled && $m->getExecuteAt() > time()) { $futureMessages[] = new HermesMessage( $m->getType(), $m->getPayload(), $m->getId(), $m->getCreated(), $m->getExecuteAt() - $this->oneLoopDurationSeconds, // Decrease execute_at time to simulate time pass $m->getRetries() ); continue; } $this->waitResult = $callback($m); } // To prevent endless loop in tests, add future messages here if ($futureMessages) { foreach ($futureMessages as $futureMessage) { $this->send($futureMessage); } } } public function waitResult() { return $this->waitResult; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/HermesTasksQueue.php
Mailer/extensions/mailer-module/src/Hermes/HermesTasksQueue.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Hermes; use Remp\MailerModule\Models\RedisClientFactory; use Remp\MailerModule\Models\RedisClientTrait; class HermesTasksQueue { use RedisClientTrait; const STATS_KEY = 'hermes_stats'; public function __construct(RedisClientFactory $redisClientFactory) { $this->redisClientFactory = $redisClientFactory; } // Tasks public function addTask(string $key, string $task, float $executeAt): bool { return $this->redis()->zadd($key, [$task => $executeAt]) > 0; } public function getTask(string $key): ?array { $task = $this->redis()->zrangebyscore($key, 0, time(), [ 'LIMIT' => [ 'OFFSET' => 0, 'COUNT' => 1, ] ]); if (!empty($task)) { $result = $this->redis()->zrem($key, $task); if ($result == 1) { return $task; } } return null; } // Stats public function incrementType(string $type): string { return $this->redis()->zincrby(static::STATS_KEY, 1, $type); } public function decrementType(string $type): string { return $this->redis()->zincrby(static::STATS_KEY, -1, $type); } public function getTypeCounts(): array { return $this->redis()->zrange(static::STATS_KEY, 0, -1, ['withscores' => true]); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/LogRedact.php
Mailer/extensions/mailer-module/src/Hermes/LogRedact.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Hermes; use Monolog\LogRecord; class LogRedact { public static function add(array $filters): callable { return function (LogRecord $record) use ($filters) { $context = $record->context; foreach ($filters as $filter) { if (isset($context['payload'][$filter])) { $context['payload'][$filter] = '******'; } if (isset($context['payload']['params'][$filter])) { $context['payload']['params'][$filter] = '******'; } } return $record->with(context: $context); }; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/SubscribeHandler.php
Mailer/extensions/mailer-module/src/Hermes/SubscribeHandler.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Hermes; use Nette\Utils\DateTime; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\MailTypesRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Tomaj\Hermes\Emitter; use Tomaj\Hermes\Handler\HandlerInterface; use Tomaj\Hermes\MessageInterface; class SubscribeHandler implements HandlerInterface { private $emitter; private $mailTypesRepository; private $mailTemplatesRepository; private $mailLogsRepository; public function __construct( Emitter $emitter, MailTypesRepository $mailTypesRepository, TemplatesRepository $mailTemplatesRepository, LogsRepository $mailLogsRepository ) { $this->emitter = $emitter; $this->mailTypesRepository = $mailTypesRepository; $this->mailTemplatesRepository = $mailTemplatesRepository; $this->mailLogsRepository = $mailLogsRepository; } public function handle(MessageInterface $message): bool { $payload = $message->getPayload(); if (!isset($payload['user_id'])) { throw new HermesException('unable to handle event: user_id is missing'); } if (!isset($payload['user_email'])) { throw new HermesException('unable to handle event: user_email is missing'); } if (!isset($payload['mail_type_id'])) { throw new HermesException('unable to handle event: mail_type_id is missing'); } if (isset($payload['send_welcome_email']) && !$payload['send_welcome_email']) { return true; } $welcomeEmail = $this->mailTypesRepository->find($payload['mail_type_id'])->subscribe_mail_template; if (!$welcomeEmail) { return true; } $today = new DateTime('today'); $this->emitter->emit(new HermesMessage('send-email', [ 'mail_template_code' => $welcomeEmail->code, 'email' => $payload['user_email'], 'context' => "nl_welcome_email.{$payload['user_id']}.{$payload['mail_type_id']}.{$today->format('Ymd')}", ])); return true; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/HermesException.php
Mailer/extensions/mailer-module/src/Hermes/HermesException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Hermes; use Exception; class HermesException extends Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/HermesMessage.php
Mailer/extensions/mailer-module/src/Hermes/HermesMessage.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Hermes; use Tomaj\Hermes\Message; class HermesMessage extends Message { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/SendEmailHandler.php
Mailer/extensions/mailer-module/src/Hermes/SendEmailHandler.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Hermes; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Models\Sender; use Tomaj\Hermes\Handler\HandlerInterface; use Tomaj\Hermes\MessageInterface; use Tracy\Debugger; class SendEmailHandler implements HandlerInterface { // Default value copied from Tomaj\Hermes\Handler\RetryTrait private int $maxRetries = 25; public function __construct( private TemplatesRepository $templatesRepository, private Sender $sender, ) { } public function setMaxRetries(int $maxRetries) { $this->maxRetries = $maxRetries; } public function handle(MessageInterface $message): bool { $payload = $message->getPayload(); $mailTemplate = $this->templatesRepository->getByCode($payload['mail_template_code']); if (!$mailTemplate) { Debugger::log("could not load mail template: record with code [{$payload['mail_template_code']}] doesn't exist"); return false; } $email = $this->sender ->reset() ->setTemplate($mailTemplate) ->addRecipient($payload['email']) ->setParams($payload['params'] ?? []) ->setLocale($payload['locale'] ?? null); if ($mailTemplate->attachments_enabled) { foreach ($payload['attachments'] ?? [] as $attachment) { $email->addAttachment($attachment['file'], base64_decode($attachment['content']) ?? null); } } if (isset($payload['context'])) { $email->setContext($payload['context']); } $email->send(false); return true; } public function canRetry(): bool { return $this->maxRetries > 0; } public function maxRetry(): int { return $this->maxRetries; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/PingMysql.php
Mailer/extensions/mailer-module/src/Hermes/PingMysql.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Hermes; use Nette\Database\Explorer; use Tomaj\Hermes\Handler\HandlerInterface; use Tomaj\Hermes\MessageInterface; class PingMysql implements HandlerInterface { private $database; public function __construct(Explorer $database) { $this->database = $database; } public function handle(MessageInterface $message): bool { $this->database->query('SELECT "heartbeat"'); return true; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Hermes/ListCreatedHandler.php
Mailer/extensions/mailer-module/src/Hermes/ListCreatedHandler.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Hermes; use Nette\Database\Explorer; use Nette\Utils\DateTime; use Psr\Log\LoggerAwareTrait; use Psr\Log\LogLevel; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Remp\MailerModule\Models\Users\IUser; use Tomaj\Hermes\Emitter; use Tomaj\Hermes\Handler\HandlerInterface; use Tomaj\Hermes\MessageInterface; class ListCreatedHandler implements HandlerInterface { use LoggerAwareTrait; public function __construct( private readonly ListsRepository $listsRepository, private readonly IUser $userProvider, private readonly UserSubscriptionsRepository $userSubscriptionsRepository, private readonly Explorer $database, private Emitter $emitter, ) { } public function handle(MessageInterface $message): bool { $payload = $message->getPayload(); if (!isset($payload['list_id'])) { throw new HermesException('unable to handle event: mail_type_id is missing'); } $list = $this->listsRepository->find($payload['list_id']); if ($payload['copy_subscribers'] ?? false) { $sql = <<<SQL INSERT INTO mail_user_subscriptions (user_id, user_email, mail_type_id, subscribed, created_at, updated_at, rtm_source, rtm_medium, rtm_campaign, rtm_content) SELECT user_id, user_email, ?, 1, ?, ?, rtm_source, rtm_medium, rtm_campaign, rtm_content FROM mail_user_subscriptions WHERE mail_type_id = ? AND subscribed = 1 SQL; $this->database->query( $sql, $payload['list_id'], new DateTime(), new DateTime(), $payload['source_list_id'] ); $subscribers = $this->userSubscriptionsRepository ->getTable() ->where('mail_type_id', $payload['list_id']); foreach ($subscribers as $subscriber) { $this->emitter->emit(new HermesMessage('user-subscribed', [ 'user_id' => $subscriber->user_id, 'user_email' => $subscriber->user_email, 'mail_type_id' => $payload['list_id'], 'send_welcome_email' => false, 'time' => new DateTime(), 'rtm_source' => $subscriber->rtm_source, 'rtm_medium' => $subscriber->rtm_medium, 'rtm_campaign' => $subscriber->rtm_campaign, 'rtm_content' => $subscriber->rtm_content, ])); } } else { $page = 1; while ($users = $this->userProvider->list([], $page)) { foreach ($users as $user) { $this->logger->log(LogLevel::INFO, sprintf("Subscribing user: %s (%s).", $user['email'], $user['id'])); if ($list->auto_subscribe) { $this->userSubscriptionsRepository->subscribeUser($list, $user['id'], $user['email']); } else { $this->userSubscriptionsRepository->unsubscribeUser($list, $user['id'], $user['email']); } } $page++; } } return true; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/TestUserProvider.php
Mailer/extensions/mailer-module/src/Tests/Feature/TestUserProvider.php
<?php namespace Tests\Feature; use Remp\MailerModule\Models\Users\IUser; class TestUserProvider implements IUser { private const PAGE_SIZE = 1000; // TODO: this is fixed in CRM, refactor private $users; /** * TestUserProvider constructor. * * @param array $users array of arrays having items 'id' and 'email' */ public function __construct(array $users) { $this->users = $users; } /** * List provides list of information about users. * * @param array $userIds List of userIDs to check. Empty array means all users. * @param int $page Page to obtain. Numbering starts with 1. * @return array */ public function list(array $userIds, int $page, bool $includeDeactivated = false): array { $toReturn = []; foreach ($userIds as $userId) { if (isset($this->users[$userId])) { $toReturn[$userId] = $this->users[$userId]; } } $offset = ($page-1) * self::PAGE_SIZE; return array_slice($toReturn, $offset, self::PAGE_SIZE, true); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/BaseFeatureTestCase.php
Mailer/extensions/mailer-module/src/Tests/Feature/BaseFeatureTestCase.php
<?php declare(strict_types=1); namespace Tests\Feature; use Nette\Database\Explorer; use Nette\DI\Container; use Nette\Utils\Random; use Nette\Utils\Strings; use PHPUnit\Framework\TestCase; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Repositories\AutoLoginTokensRepository; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\BatchTemplatesRepository; use Remp\MailerModule\Repositories\JobQueueRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListCategoriesRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\ListVariantsRepository; use Remp\MailerModule\Repositories\LogConversionsRepository; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\Repository; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Remp\MailerModule\Repositories\UserSubscriptionVariantsRepository; class BaseFeatureTestCase extends TestCase { private Container $container; protected Explorer $database; protected AutoLoginTokensRepository $autoLoginTokensRepository; protected JobsRepository $jobsRepository; protected JobQueueRepository $jobQueueRepository; protected BatchesRepository $batchesRepository; protected LayoutsRepository $layoutsRepository; protected TemplatesRepository $templatesRepository; protected BatchTemplatesRepository $batchTemplatesRepository; protected ListsRepository $listsRepository; protected ListVariantsRepository $listVariantsRepository; protected ListCategoriesRepository $listCategoriesRepository; protected UserSubscriptionsRepository $userSubscriptionsRepository; protected UserSubscriptionVariantsRepository $userSubscriptionVariantsRepository; protected LogsRepository $mailLogsRepository; protected LogConversionsRepository $mailLogConversionsRepository; protected function setUp(): void { $this->container = $GLOBALS['container']; $this->database = $this->inject(Explorer::class); $this->autoLoginTokensRepository = $this->inject(AutoLoginTokensRepository::class); $this->jobsRepository = $this->inject(JobsRepository::class); $this->batchTemplatesRepository = $this->inject(BatchTemplatesRepository::class); $this->templatesRepository = $this->inject(TemplatesRepository::class); $this->layoutsRepository = $this->inject(LayoutsRepository::class); $this->jobQueueRepository = $this->inject(JobQueueRepository::class); $this->mailLogsRepository = $this->inject(LogsRepository::class); $this->mailLogConversionsRepository = $this->inject(LogConversionsRepository::class); $this->batchesRepository = $this->inject(BatchesRepository::class); $this->listsRepository = $this->inject(ListsRepository::class); $this->listVariantsRepository = $this->inject(ListVariantsRepository::class); $this->listCategoriesRepository = $this->inject(ListCategoriesRepository::class); $this->userSubscriptionsRepository = $this->inject(UserSubscriptionsRepository::class); $this->userSubscriptionVariantsRepository = $this->inject(UserSubscriptionVariantsRepository::class); $repositories = [ $this->autoLoginTokensRepository, $this->jobsRepository, $this->batchTemplatesRepository, $this->templatesRepository, $this->layoutsRepository, $this->jobQueueRepository, $this->batchesRepository, $this->listsRepository, $this->mailLogsRepository, $this->mailLogConversionsRepository, $this->listVariantsRepository, $this->listCategoriesRepository, $this->userSubscriptionsRepository, $this->userSubscriptionVariantsRepository, ]; foreach ($repositories as $repository) { $this->truncate($repository); } } protected function tearDown(): void { parent::tearDown(); \Mockery::close(); } protected function inject($className) { return $this->container->getByType($className); } protected function createJob($context = null, $mailTypeVariant = null, $includeSegments = [['code' => 'segment', 'provider' => 'provider']], $excludeSegments = []) { $jobSegmentsManager = new JobSegmentsManager(); foreach ($includeSegments as $includeSegment) { $jobSegmentsManager->includeSegment($includeSegment['code'], $includeSegment['provider']); } foreach ($excludeSegments as $excludeSegment) { $jobSegmentsManager->excludeSegment($excludeSegment['code'], $excludeSegment['provider']); } return $this->jobsRepository->add($jobSegmentsManager, $context, $mailTypeVariant); } protected function createBatch($mailJob, $template, $maxEmailsCount = null) { $batch = $this->batchesRepository->add($mailJob->id, $maxEmailsCount, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $template); $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND); return $batch; } protected function createJobAndBatch($template, $mailTypeVariant = null, $context = null, $maxEmailsCount = null) { $mailJob = $this->createJob($context, $mailTypeVariant); return $this->createBatch($mailJob, $template, $maxEmailsCount); } protected function createTemplate($layout, $mailType, $code = null) { if (!$code) { $code = 'template_' . Random::generate(15); } return $this->templatesRepository->add('name', $code, '', 'from@sample.com', 'SUBJECT', 'test', 'test', $layout->id, $mailType->id); } protected function createMailLayout() { return $this->layoutsRepository->add('Layout', 'layout', '', ''); } protected function createMailTypeCategory($categoryName) { $categoryCode = Strings::webalize($categoryName); $listCategory = $this->listCategoriesRepository->getByCode($categoryCode)->fetch(); if (!$listCategory) { $listCategory = $this->listCategoriesRepository->add($categoryName, $categoryCode, 100); } return $listCategory; } protected function createMailTypeWithCategory( string $categoryName = 'category', string $typeCode = 'code', string $typeName = 'name', bool $publicListing = true, bool $isMultiVariant = false, int $defaultVariantId = null, string $mailFrom = null, ) { $listCategory = $this->createMailTypeCategory($categoryName); return $this->listsRepository->add( categoryId: $listCategory->id, priority: 1, code: $typeCode, name: $typeName, sorting: 1, isAutoSubscribe: true, isLocked: false, description: 'XXX', publicListing: $publicListing, mailFrom: $mailFrom, isMultiVariant: $isMultiVariant, defaultVariantId: $defaultVariantId, ); } protected function truncate(Repository $repository) { $truncateTables = implode(' ', array_map(function ($repo) { $property = (new \ReflectionClass($repo))->getProperty('tableName'); $property->setAccessible(true); return "DELETE FROM `{$property->getValue($repo)}`;"; }, [ $repository, ])); $db = $this->database->getConnection()->getPdo(); $sql = " SET FOREIGN_KEY_CHECKS=0; {$truncateTables} SET FOREIGN_KEY_CHECKS=1; "; try { $db->exec($sql); } catch (\PDOException $e) { echo $e->getMessage(); } } protected function createMailTypeVariant($mailType, string $title = 'variant', string $code = 'variant', int $sorting = 100, bool $isDefaultVariant = false) { $variant = $this->listVariantsRepository->add($mailType, $title, $code, $sorting); if ($isDefaultVariant) { $this->listsRepository->update($mailType, ['default_variant_id' => $variant->id]); } return $variant; } protected function createMailUserSubscription($mailType, int $userID = 123, string $email = 'example@example.com', int $variantID = null) { $this->userSubscriptionsRepository->subscribeUser($mailType, $userID, $email, $variantID); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/TestSegmentProvider.php
Mailer/extensions/mailer-module/src/Tests/Feature/TestSegmentProvider.php
<?php declare(strict_types=1); namespace Tests\Feature; use Remp\MailerModule\Models\Segment\ISegment; class TestSegmentProvider implements ISegment { public const PROVIDER_ALIAS = 'test-segment'; public array $testUsers = []; public function provider(): string { return static::PROVIDER_ALIAS; } public function list(): array { return [ ]; } public function users(array $segment): array { return $this->testUsers; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Mails/SenderTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Mails/SenderTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Mails; use PHPUnit\Framework\Attributes\DataProvider; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\Mailer\EmailAllowList; use Remp\MailerModule\Models\Sender; use Remp\MailerModule\Models\Sender\MailerBatchException; use Remp\MailerModule\Models\Sender\MailerFactory; use Remp\MailerModule\Repositories\ConfigsRepository; use Tests\Feature\BaseFeatureTestCase; class SenderTest extends BaseFeatureTestCase { protected Sender $applicationMailer; protected EmailAllowList $emailAllowList; protected ConfigsRepository $configsRepository; protected MailerFactory $mailerFactory; protected TestMailer $testMailer; private Config $config; protected array $usersList = []; protected $mailType; protected $mailTypeVariant; protected $mailLayout; protected $mailTemplate; protected function setUp(): void { parent::setUp(); $this->applicationMailer = $this->inject(Sender::class); $this->emailAllowList = $this->inject(EmailAllowList::class); $this->configsRepository = $this->inject(ConfigsRepository::class); $this->mailerFactory = $this->inject(MailerFactory::class); $this->config = $this->inject(Config::class); $this->setDefaultMailer(TestMailer::ALIAS); $this->testMailer = $this->mailerFactory->getMailer(TestMailer::ALIAS); $this->testMailer->supportsBatch = true; $this->testMailer->clearSent(); $this->emailAllowList->reset(); $this->mailType = $this->createMailTypeWithCategory( 'test_category', 'test_mail_type', 'Test Mail Type', true ); $this->mailTypeVariant = $this->createMailTypeVariant($this->mailType); $this->mailLayout = $this->createMailLayout(); $this->mailTemplate = $this->createTemplate($this->mailLayout, $this->mailType); } protected function tearDown(): void { parent::tearDown(); $this->truncate($this->configsRepository); } public static function dataProvider() { return [ 'SendEmailSuccess' => [ 'allowList' => [], 'subscribedEmails' => [ '111@example.com', ], 'recipientEmails' => [ '111@example.com', ], 'expectedDeliveredEmails' => [ '111@example.com', ], ], 'SendEmailFailBecauseUserIsNotSubscribed' => [ 'allowList' => [], 'subscribedEmails' => [], 'recipientEmails' => [ '111@example.com', ], 'expectedDeliveredEmails' => [], ], 'SendEmailSuccessWithUserInAllowList' => [ 'allowList' => [ '111@example.com', ], 'subscribedEmails' => [ '111@example.com', ], 'recipientEmails' => [ '111@example.com', ], 'expectedDeliveredEmails' => [ '111@example.com', ], ], 'SendEmailFailBecauseUserIsNotAllowList' => [ 'allowList' => [ '111@example.com', ], 'subscribedEmails' => [ '222@example.com', ], 'recipientEmails' => [ '222@example.com', ], 'expectedDeliveredEmails' => [], ], 'SendBatchToSubscribedUsersSuccess' => [ 'allowList' => [], 'subscribedEmails' => [ '111@example.com', '222@example.com', ], 'recipientEmails' => [ '111@example.com', '222@example.com', '333@example.com', ], 'expectedDeliveredEmails' => [ '111@example.com', '222@example.com', ], ], 'SendBatchToSubscribedAndAllowListedUsers' => [ 'allowList' => [ '111@example.com', '333@example.com', ], 'subscribedEmails' => [ '111@example.com', '222@example.com', '333@example.com', '444@example.com', ], 'recipientEmails' => [ '111@example.com', '222@example.com', '333@example.com', '444@example.com', ], 'expectedDeliveredEmails' => [ '111@example.com', '333@example.com', ], ], ]; } #[DataProvider('dataProvider')] public function testSender( array $allowList = [], array $subscribedEmails = [], array $recipientEmails = [], array $expectedDeliveredEmails = [] ) { foreach ($allowList as $allowEmail) { $this->emailAllowList->allow($allowEmail); } $userId = 1; foreach ($subscribedEmails as $subscribedEmail) { $user = $this->createUser($userId, $subscribedEmail); $this->createMailUserSubscription($this->mailType, $user['id'], $user['email'], $this->mailTypeVariant->id); $userId++; } $email = $this->applicationMailer ->reset() ->setTemplate($this->mailTemplate); foreach ($recipientEmails as $recipientEmail) { $email->addRecipient($recipientEmail); } if (count($recipientEmails) > 1) { $email->sendBatch(); } else { $email->send(); } $this->assertEqualsCanonicalizing($this->testMailer->getSentToEmails(), $expectedDeliveredEmails); } public function testSendEmailWithMailerSpecifiedInTemplateInsteadOfDefaultOne() { $this->setDefaultMailer('not_existing_mailer'); $this->listsRepository->update($this->mailType, ['mailer_alias' => $this->testMailer->getMailerAlias()]); $this->emailAllowList->allow('111@example.com'); $user = $this->createUser(1, '111@example.com'); $this->createMailUserSubscription($this->mailType, $user['id'], $user['email'], $this->mailTypeVariant->id); $email = $this->applicationMailer ->reset() ->setTemplate($this->mailTemplate); $email->addRecipient($user['email']); $email->send(); $this->assertEqualsCanonicalizing(['111@example.com'], $this->testMailer->getSentToEmails()); } public function testDoNotSendEmailBecauseOfEmailWithSameContextAlreadySent() { $user1 = $this->createUser(1, '111@example.com'); $this->createMailUserSubscription($this->mailType, $user1['id'], $user1['email'], $this->mailTypeVariant->id); $email = $this->applicationMailer ->reset() ->setTemplate($this->mailTemplate) ->setContext('testing.context'); $email->addRecipient($user1['email']); $email->send(); $this->assertEqualsCanonicalizing(['111@example.com'], $this->testMailer->getSentToEmails()); $user2 = $this->createUser(2, '222@example.com'); $email = $this->applicationMailer ->reset() ->setTemplate($this->mailTemplate) ->setContext('testing.context'); $email->addRecipient($user2['email']); $email->send(); $this->assertEqualsCanonicalizing(['111@example.com'], $this->testMailer->getSentToEmails()); } public function testSendBatchFailBecauseMailerDoesntSupportBatchSending() { $this->testMailer->supportsBatch = false; $user = $this->createUser(1, '111@example.com'); $this->createMailUserSubscription($this->mailType, $user['id'], $user['email'], $this->mailTypeVariant->id); $email = $this->applicationMailer ->reset() ->setTemplate($this->mailTemplate); $email->addRecipient($user['email']); $this->expectException(MailerBatchException::class); $email->sendBatch(); } private function createUser(int $id, string $email) { $this->usersList[$id] = [ 'id' => $id, 'email' => $email ]; return $this->usersList[$id]; } private function setDefaultMailer(string $name) { $defaultMailer = $this->configsRepository->findBy('name', 'default_mailer'); if ($defaultMailer) { $this->configsRepository->update($defaultMailer, [ 'value' => $name ]); } else { $this->configsRepository->add('default_mailer', 'Default mailer', $name, '', ''); } /** * Normally it isn't needed to force refresh as the possibly new source code/behavior is not reloaded yet and * the config isn't needed to be reloaded immediately (as it's needed in the test). */ $this->config->refresh(force: true); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Mails/BatchEmailGeneratorWrapper.php
Mailer/extensions/mailer-module/src/Tests/Feature/Mails/BatchEmailGeneratorWrapper.php
<?php declare(strict_types=1); namespace Tests\Feature\Mails; use Psr\Log\NullLogger; use Remp\MailerModule\Models\Beam\UnreadArticlesResolver; use Remp\MailerModule\Models\Job\BatchEmailGenerator; use Remp\MailerModule\Models\Job\MailCache; use Remp\MailerModule\Models\Segment\Aggregator; use Remp\MailerModule\Models\Users\IUser; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\JobQueueRepository; use Remp\MailerModule\Repositories\JobsRepository; class BatchEmailGeneratorWrapper extends BatchEmailGenerator { public function __construct( JobQueueRepository $mailJobQueueRepository, Aggregator $segmentAggregator, IUser $userProvider, MailCache $mailCache, UnreadArticlesResolver $unreadArticlesGenerator, ) { parent::__construct( new NullLogger(), $mailJobQueueRepository, $segmentAggregator, $userProvider, $mailCache, $unreadArticlesGenerator, ); } // To enable public access to protected functions in tests public function insertUsersIntoJobQueue(ActiveRow $batch, &$userMap): array { return parent::insertUsersIntoJobQueue($batch, $userMap); } public function filterQueue($batch): array { return parent::filterQueue($batch); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Mails/TestMailer.php
Mailer/extensions/mailer-module/src/Tests/Feature/Mails/TestMailer.php
<?php declare(strict_types=1); namespace Tests\Feature\Mails; use Nette\Mail\Message; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\Mailer\Mailer; use Remp\MailerModule\Repositories\ConfigsRepository; class TestMailer extends Mailer { public const ALIAS = 'remp_test_mailer'; protected array $sent = []; public bool $supportsBatch = true; public function __construct( Config $config, ConfigsRepository $configsRepository, ?string $code = null, ) { parent::__construct($config, $configsRepository, $code); } public function send(Message $mail): void { $this->sent[] = $mail; } public function getSent() { return $this->sent; } public function getSentToEmails() { $emails = []; foreach ($this->sent as $sentEmail) { $emails = array_merge($emails, array_keys($sentEmail->getHeader('To'))); } return $emails; } public function clearSent() { $this->sent = []; } public function supportsBatch(): bool { return $this->supportsBatch; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Mails/MailHeaderTraitTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Mails/MailHeaderTraitTest.php
<?php declare(strict_types=1); namespace Feature\Mails; use Nette\Mail\Message; use PHPUnit\Framework\Attributes\DataProvider; use Remp\MailerModule\Models\Mailer\MailHeaderTrait; use Tests\Feature\BaseFeatureTestCase; class MailHeaderTraitTest extends BaseFeatureTestCase { use MailHeaderTrait; public static function dataProvider() { return [ 'TestRegularHeader_ShouldReturnFilename' => [ 'headerValue' => 'Content-Disposition: attachment; filename="invoice-2024-09-24.pdf"', 'parameter' => 'filename', 'result' => 'invoice-2024-09-24.pdf', ], 'TestRegularHeader_NotRealParameter' => [ 'headerValue' => 'Content-Disposition: attachment; filename="invoice-2024-09-24.pdf"', 'parameter' => 'dummy', 'result' => null, ], 'TestRegularHeader_AdditionalParameters' => [ 'headerValue' => 'Content-Disposition: attachment; filename="invoice-2024-09-24.pdf"; foo="bar"', 'parameter' => 'filename', 'result' => 'invoice-2024-09-24.pdf', ], ]; } #[DataProvider('dataProvider')] public function testMailHeaderTrait( string $headerValue, string $parameter, ?string $result, ) { $parameter = $this->getHeaderParameter($headerValue, $parameter); $this->assertSame($result, $parameter); } /** * Nette Mailer adds attachments to email as `Content-Disposition` headers with format: * * Content-Disposition: attachment; filename="invoice-2024-09-24.pdf" * * Mailgun requires attachments as API parameters, so in MailgunMailer we need to load attachment * and parse filename from header. This is handled by preg_match within `MailHeaderTrait`. * * This is simple unit test which checks: * - If regex which loads attachment's filename from mail header is correct. * - If Nette didn't change how attachments (filenames) are attached to message. * E.g. using different approach or attaching filename without quotes (allowed by specification). */ public function testMessageMimePartHeaderForContentDisposition() { $filename = 'invoice-2024-09-24.pdf'; // create attachment as Nette Mailer creates it $message = new Message(); $message->addAttachment($filename, 'dummy content', 'text/plain'); $attachments = $message->getAttachments(); $attachment = reset($attachments); // parse header created by Nette with our Trait $attachmentName = $this->getHeaderParameter($attachment->getHeader('Content-Disposition'), 'filename'); $this->assertEquals($filename, $attachmentName); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Mails/BatchEmailGeneratorTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Mails/BatchEmailGeneratorTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Mails; use Nette\Utils\DateTime; use Remp\MailerModule\Models\Beam\UnreadArticlesResolver; use Remp\MailerModule\Models\Job\MailCache; use Remp\MailerModule\Models\Segment\Aggregator; use Remp\MailerModule\Models\Users\IUser; use Tests\Feature\BaseFeatureTestCase; use Tests\Feature\TestUserProvider; class BatchEmailGeneratorTest extends BaseFeatureTestCase { private $mailCache; private $unreadArticlesGenerator; protected function setUp(): void { parent::setUp(); $this->mailCache = $this->inject(MailCache::class); $this->unreadArticlesGenerator = $this->inject(UnreadArticlesResolver::class); } private function getGenerator($aggregator, $userProvider) { return new BatchEmailGeneratorWrapper( $this->jobQueueRepository, $aggregator, $userProvider, $this->mailCache, $this->unreadArticlesGenerator, ); } private function generateUsers(int $count, int $startFromId = 1): array { $userList = []; for ($i=$startFromId; $i < $startFromId + $count; $i++) { $userList[$i] = [ 'id' => $i, 'email' => "email{$i}@example.com" ]; } return $userList; } public function testOnlyIncludeSegments() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $job = $this->createJob(includeSegments: [['code' => 's1', 'provider' => 'p'], ['code' => 's2', 'provider' => 'p']]); $batch = $this->createBatch($job, $template); $userList1 = $this->generateUsers(100); $userList2 = $this->generateUsers(50, 101); $userList = array_merge($userList1, $userList2); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, $ids); } return []; }); $aggregator = $this->createMock(Aggregator::class); $map = [ [['provider' => 'p', 'code' => 's1'], array_map(static fn($i) => $i['id'], $userList1)], [['provider' => 'p', 'code' => 's2'], array_map(static fn($i) => $i['id'], $userList2)] ]; $aggregator->method('users')->willReturnMap($map); $this->subscribeUsers($mailType, $userList); // Test generator $generator = $this->getGenerator($aggregator, $userProvider); $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); $this->assertEquals(150, $this->jobQueueCount($batch, $template)); $expectedUsers = $this->getUserEmailsByKeys($userList, array_keys($userList)); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing($expectedUsers, $actualUsers); } public function testIntersectingSegments() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $job = $this->createJob(includeSegments: [['code' => 's1', 'provider' => 'p'], ['code' => 's2', 'provider' => 'p']]); $batch = $this->createBatch($job, $template); $userList1 = $this->generateUsers(100); $userList2 = $this->generateUsers(50, 20); $userList = array_merge($userList1, $userList2); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, $ids); } return []; }); $map = [ [['provider' => 'p', 'code' => 's1'], array_map(static fn($i) => $i['id'], $userList1)], [['provider' => 'p', 'code' => 's2'], array_map(static fn($i) => $i['id'], $userList2)] ]; $aggregator = $this->createMock(Aggregator::class); $aggregator->method('users')->willReturnMap($map); $this->subscribeUsers($mailType, $userList); // Test generator $generator = $this->getGenerator($aggregator, $userProvider); $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); $this->assertEquals(100, $this->jobQueueCount($batch, $template)); $expectedUsers = $this->getUserEmailsByKeys($userList1, array_keys($userList1)); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing($expectedUsers, $actualUsers); } public function testIncludeExcludeSegments() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $job = $this->createJob( includeSegments: [['code' => 's1', 'provider' => 'p'], ['code' => 's2', 'provider' => 'p']], excludeSegments: [['code' => 's3', 'provider' => 'p'], ['code' => 's4', 'provider' => 'p']] ); $batch = $this->createBatch($job, $template); $includeUserList1 = $this->generateUsers(10); $includeUserList2 = $this->generateUsers(5, 11); $excludeUserList3 = $this->generateUsers(5); $excludeUserList4 = $this->generateUsers(4, 14); $userList = array_merge($includeUserList1, $includeUserList2); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, $ids); } return []; }); $map = [ [['provider' => 'p', 'code' => 's1'], array_map(static fn($i) => $i['id'], $includeUserList1)], [['provider' => 'p', 'code' => 's2'], array_map(static fn($i) => $i['id'], $includeUserList2)], [['provider' => 'p', 'code' => 's3'], array_map(static fn($i) => $i['id'], $excludeUserList3)], [['provider' => 'p', 'code' => 's4'], array_map(static fn($i) => $i['id'], $excludeUserList4)] ]; $aggregator = $this->createMock(Aggregator::class); $aggregator->method('users')->willReturnMap($map); $this->subscribeUsers($mailType, array_merge($includeUserList1, $includeUserList2)); // Test generator $generator = $this->getGenerator($aggregator, $userProvider); $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); $this->assertEquals(8, $this->jobQueueCount($batch, $template)); $expectedUsers = $this->getUserEmailsByIds($userList, [6,7,8,9,10,11,12,13]); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing($expectedUsers, $actualUsers); } public function testFilteringUnsubscribed() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $batch = $this->createJobAndBatch($template); $userList = $this->generateUsers(100); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, array_flip($ids)); } return []; }); $aggregator = $this->createConfiguredMock(Aggregator::class, [ 'users' => array_keys($userList) ]); $subscribedUserKeys = array_rand($userList, 6); foreach ($subscribedUserKeys as $key) { $this->subscribeUsers($mailType, [$userList[$key]]); } // Test generator $generator = $this->getGenerator($aggregator, $userProvider); $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); // keep only subscribed users $this->assertEquals(6, $this->jobQueueCount($batch, $template)); $expectedUsers = $this->getUserEmailsByKeys($userList, $subscribedUserKeys); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing($expectedUsers, $actualUsers); } public function testFilteringOtherVariants() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $mailTypeVariant1 = $this->listVariantsRepository->add($mailType, 'variant1', 'v1', 100); $mailTypeVariant2 = $this->listVariantsRepository->add($mailType, 'variant2', 'v2', 100); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $batch = $this->createJobAndBatch($template, $mailTypeVariant1); $userList = $this->generateUsers(100); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, array_flip($ids)); } return []; }); $aggregator = $this->createConfiguredMock(Aggregator::class, [ 'users' => array_keys($userList) ]); $mailVariantUserKeys = []; // Split user subscription into two variants foreach ($userList as $i => $item) { if ($i % 2) { $mailVariantUserKeys[] = $i; $variantId = $mailTypeVariant1->id; } else { $variantId = $mailTypeVariant2->id; } $this->userSubscriptionsRepository->subscribeUser( $mailType, $item['id'], $item['email'], $variantId ); } // Test generator $generator = $this->getGenerator($aggregator, $userProvider); $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); $this->assertEquals(50, $this->jobQueueCount($batch, $template)); $expectedUsers = $this->getUserEmailsByKeys($userList, $mailVariantUserKeys); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing($expectedUsers, $actualUsers); } public function testFilteringAlreadySentContext() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $context = 'context'; $batch = $this->createJobAndBatch($template, null, $context); $userList = $this->generateUsers(100); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, array_flip($ids)); } return []; }); $aggregator = $this->createConfiguredMock(Aggregator::class, [ 'users' => array_keys($userList) ]); $generator = $this->getGenerator($aggregator, $userProvider); // subscribe users $this->subscribeUsers($mailType, $userList); // Simulate some users have already received the same email (create mail_logs entries with same context) foreach (array_rand($userList, 7) as $key) { $this->mailLogsRepository->add( $userList[$key]['email'], $template->subject, $template->id, $batch->mail_job_id, $batch->id, null, null, $context ); unset($userList[$key]); } // Simulate already queued in another batch with same context $anotherBatch = $this->createBatch($batch->job, $template); $insert = []; foreach (array_rand($userList, 10) as $key) { $user = $userList[$key]; $insert[] = [ 'batch' => $anotherBatch->id, 'templateId' => $template->id, 'email' => $user['email'], 'sorting' => rand(), /** @phpstan-ignore-line */ 'context' => $anotherBatch->mail_job->context, ]; unset($userList[$key]); } $this->jobQueueRepository->multiInsert($insert); $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); $this->assertEquals(83, $this->jobQueueCount($batch, $template)); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing(array_map(fn($user) => $user['email'], $userList), $actualUsers); } public function testFilteringAlreadyQueued() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $batch = $this->createJobAndBatch($template); $userList = $this->generateUsers(100); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, array_flip($ids)); } return []; }); $aggregator = $this->createConfiguredMock(Aggregator::class, [ 'users' => array_keys($userList) ]); // subscribe users $this->subscribeUsers($mailType, $userList); $anotherBatch = $this->createBatch($batch->job, $template); $insert = []; foreach (array_rand($userList, 15) as $key) { $user = $userList[$key]; $insert[] = [ 'batch' => $anotherBatch->id, 'templateId' => $template->id, 'email' => $user['email'], 'sorting' => rand(), /** @phpstan-ignore-line */ 'context' => null, ]; unset($userList[$key]); } $this->jobQueueRepository->multiInsert($insert); // Test generator $generator = $this->getGenerator($aggregator, $userProvider); $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); $this->assertEquals(85, $this->jobQueueCount($batch, $template)); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing(array_map(fn($user) => $user['email'], $userList), $actualUsers); } public function testFilteringAlreadySent() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $batch = $this->createJobAndBatch($template); $userList = $this->generateUsers(100); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, array_flip($ids)); } return []; }); $aggregator = $this->createConfiguredMock(Aggregator::class, [ 'users' => array_keys($userList) ]); $generator = $this->getGenerator($aggregator, $userProvider); // subscribe users $this->subscribeUsers($mailType, $userList); // Simulate some users have already received the same email (create mail_logs entries) foreach (array_rand($userList, 7) as $key) { $user = $userList[$key]; $this->mailLogsRepository->add( $user['email'], $template->subject, $template->id, $batch->mail_job_id, $batch->id, ); unset($userList[$key]); } $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); $this->assertEquals(93, $this->jobQueueCount($batch, $template)); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing(array_map(fn($user) => $user['email'], $userList), $actualUsers); } public function testFilteringStripEmails() { // Prepare data $mailType = $this->createMailTypeWithCategory(); $layout = $this->createMailLayout(); $template = $this->createTemplate($layout, $mailType); $batch = $this->createJobAndBatch($template, null, null, 35); $userList = $this->generateUsers(50000); $userProvider = $this->createMock(IUser::class); $userProvider->method('list')->willReturnCallback(function ($ids, $page) use ($userList) { if ($page === 1) { return array_intersect_key($userList, array_flip($ids)); } return []; }); $aggregator = $this->createConfiguredMock(Aggregator::class, [ 'users' => array_keys($userList) ]); $generator = $this->getGenerator($aggregator, $userProvider); // subscribe users $this->subscribeUsers($mailType, $userList); $userMap = []; $generator->insertUsersIntoJobQueue($batch, $userMap); $generator->filterQueue($batch); // max emails count set on batch $this->assertEquals(35, $this->jobQueueCount($batch, $template)); } public function testFiltering2() { // TUNE-UP test size (>=220) $allUsersCount = 200; $halfUsersCount = $allUsersCount / 2; // Prepare data $allUsersList = $this->generateUsers($allUsersCount); $userProvider = new TestUserProvider($allUsersList); $users1 = array_slice($allUsersList, 0, $halfUsersCount, true); $users2 = array_slice($allUsersList, $halfUsersCount, null, true); $aggregator1 = $this->createConfiguredMock(Aggregator::class, [ 'users' => array_keys($users1) ]); $aggregator2 = $this->createConfiguredMock(Aggregator::class, [ 'users' => array_keys($users2) ]); $layout = $this->createMailLayout(); $mailType = $this->createMailTypeWithCategory(); // Test simple job with 1 batch $template1 = $this->createTemplate($layout, $mailType); $batch1 = $this->createJobAndBatch($template1, null, 'context1'); // Subscriber users $subscribedUsers1 = array_slice($users1, 0, 100); foreach ($subscribedUsers1 as $item) { $this->userSubscriptionsRepository->subscribeUser($mailType, $item['id'], $item['email']); } $generator1 = $this->getGenerator($aggregator1, $userProvider); $userMap1 = []; // Push all user emails into queue $generator1->insertUsersIntoJobQueue($batch1, $userMap1); $this->assertEquals(count($users1), $this->jobQueueCount($batch1, $template1)); // Filter those that won't be sent $generator1->filterQueue($batch1); $this->assertEquals(count($subscribedUsers1), $this->jobQueueCount($batch1, $template1)); $actualUsers = $this->jobQueueRepository->getBatchEmails($batch1)->fetchPairs(null, 'email'); $this->assertEqualsCanonicalizing(array_map(fn($user) => $user['email'], $subscribedUsers1), $actualUsers); //////////// // Now create another job with two batches //////////// $context2 = 'context2'; $template2_1 = $this->createTemplate($layout, $mailType); $template2_2 = $this->createTemplate($layout, $mailType); $job2 = $this->createJob($context2); $batch2_1_maxEmailsCount = 20; $batch2_1 = $this->createBatch($job2, $template2_1, $batch2_1_maxEmailsCount); $batch2_2 = $this->createBatch($job2, $template2_2); $subscribedUsers2 = array_slice($users2, 0, 100); foreach ($subscribedUsers2 as $item) { $this->userSubscriptionsRepository->subscribeUser($mailType, $item['id'], $item['email']); } // Simulate some users have already received the same email (create mail_logs entries with same context) $alreadyReceivedEmailUsers2 = array_slice($users2, 0, 7); foreach ($alreadyReceivedEmailUsers2 as $item) { $this->mailLogsRepository->add( $item['email'], $template2_2->subject, $template2_2->id, $batch2_2->mail_job_id, $batch2_2->id, null, null, $context2 ); } $userMap2 = []; $generator2 = $this->getGenerator($aggregator2, $userProvider); // Process first batch $generator2->insertUsersIntoJobQueue($batch2_1, $userMap2); $generator2->filterQueue($batch2_1); $this->assertEquals($batch2_1_maxEmailsCount, $this->jobQueueCount($batch2_1, $template2_1)); // Process second batch $generator2->insertUsersIntoJobQueue($batch2_2, $userMap2); $generator2->filterQueue($batch2_2); $batch2_2_expectedEmailsCount = count($subscribedUsers2) - $batch2_1_maxEmailsCount - count($alreadyReceivedEmailUsers2); $this->assertEquals($batch2_2_expectedEmailsCount, $this->jobQueueCount($batch2_2, $template2_2)); } private function jobQueueCount($batch, $template): int { return $this->jobQueueRepository->getTable()->where([ 'mail_batch_id' => $batch->id, 'mail_template_id' => $template->id, ])->count('*'); } private function subscribeUsers($mailType, $users): void { foreach (array_chunk($users, 1000, true) as $usersChunk) { $insert = []; foreach ($usersChunk as $user) { $insert[] = [ 'user_id' => $user['id'], 'user_email' => $user['email'], 'mail_type_id' => $mailType->id, 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'subscribed' => true, ]; } $this->database->query("INSERT INTO mail_user_subscriptions", $insert); } } private function getUserEmailsByKeys($users, $keys): array { $result = []; foreach ($keys as $key) { $result[] = $users[$key]['email']; } return $result; } private function getUserEmailsByIds($users, $ids): array { return array_map( static function ($user) { return $user['email']; }, array_filter($users, static function ($user) use ($ids) { return in_array($user['id'], $ids, true); }) ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/BaseApiHandlerTestCase.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/BaseApiHandlerTestCase.php
<?php declare(strict_types=1); namespace Tests\Feature\Api; use Tests\Feature\BaseFeatureTestCase; use Tomaj\NetteApi\ApiDecider; use Tomaj\NetteApi\Handlers\BaseHandler; abstract class BaseApiHandlerTestCase extends BaseFeatureTestCase { protected function getHandler(string $className): BaseHandler { $apiDecidier = $this->inject(ApiDecider::class); $apis = $apiDecidier->getApis(); foreach ($apis as $api) { $handler = $api->getHandler(); if (get_class($handler) == $className) { return $handler; } } throw new \Exception("Cannot find api handler '$className'"); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailCreateTemplateHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailCreateTemplateHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Mailers; use Nette\Utils\Random; use Remp\MailerModule\Api\v1\Handlers\Mailers\MailCreateTemplateHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class MailCreateTemplateHandlerTest extends BaseApiHandlerTestCase { /** @var MailCreateTemplateHandler */ private $handler; const ADMIN_MAIL_FROM = 'ADMIN <admin@example.com>'; const USER_MAIL_FROM = 'USER <user@example.com>'; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(MailCreateTemplateHandler::class); } public function testApiValidParamsShouldCreateNewTemplate() { $params = $this->getDefaultParams([ 'code' => 'foo', ]); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $this->assertEquals('foo', $response->getPayload()['code']); } public function testApiValidParamsWithLayoutCodeShouldCreateNewTemplate() { $params = $this->getDefaultParams([ 'mail_layout_id' => null, 'mail_layout_code' => 'layout', ]); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $template = $this->templatesRepository->findBy('code', $response->getPayload()['code']); $this->assertEquals('layout', $template->mail_layout->code); } public function testApiWithNameTooLongShouldReturnBadRequest() { $name = Random::generate(MailCreateTemplateHandler::NAME_MAX_LENGTH + 1); $params = $this->getDefaultParams([ 'name' => $name, ]); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(400, $response->getCode()); $this->assertEquals('name_too_long', $response->getPayload()['code']); } public function testApiWithoutLayoutIdOrCoudShouldReturnNotFound() { $params = $this->getDefaultParams([ 'mail_layout_id' => null, 'mail_layout_code' => 'null', ]); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(404, $response->getCode()); $this->assertEquals('mail_layout_not_found', $response->getPayload()['code']); } public function testClickTrackingNoParamShouldUseDefault() { $params = $this->getDefaultParams([ 'click_tracking' => null, ]); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $template = $this->templatesRepository->findBy('code', $response->getPayload()['code']); $this->assertNull($template->click_tracking); } public function testClickTrackingWithTruthyParamShouldStoreTrue() { $params = $this->getDefaultParams([ 'click_tracking' => 1, ]); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $template = $this->templatesRepository->findBy('code', $response->getPayload()['code']); $this->assertEquals(1, $template->click_tracking); } public function testClickTrackingWithFalsyParamShouldStoreTrue() { $params = $this->getDefaultParams([ 'click_tracking' => 'off', ]); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $template = $this->templatesRepository->findBy('code', $response->getPayload()['code']); $this->assertEquals(0, $template->click_tracking); } public function testGetMailFromMailTypeMailFrom() { $params = $this->getDefaultParams([ 'from' => null, ], self::USER_MAIL_FROM); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $template = $this->templatesRepository->findBy('code', $response->getPayload()['code']); $this->assertEquals(self::USER_MAIL_FROM, $template->from); } public function testGetMailFromEmptyInputAndNotFilledMailTypeMailFrom() { $params = $this->getDefaultParams([ 'from' => null, ]); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(400, $response->getCode()); $responsePayload = $response->getPayload(); $this->assertEquals('from_parameter_not_resolvable', $responsePayload['code']); } private function getDefaultParams($params, string $mailTypeMailFrom = null) { $mailType = $this->createMailTypeWithCategory( categoryName: "category1", typeCode: "code1", typeName: "name1", mailFrom: $mailTypeMailFrom, ); $mailLayout = $this->createMailLayout(); return array_merge([ 'name' => 'test_name', 'code' => 'test_code', 'description' => 'test_description', 'mail_layout_id' => $mailLayout->id, 'mail_type_code' => $mailType->code, 'subject' => 'Test email subject', 'template_text' => 'email content', 'template_html' => '<strong>email content</strong>', 'from' => self::ADMIN_MAIL_FROM, ], $params); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailTemplatesListingHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailTemplatesListingHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Mailers; use PHPUnit\Framework\Attributes\DataProvider; use Remp\MailerModule\Api\v1\Handlers\Mailers\MailTemplatesListingHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class MailTemplatesListingHandlerTest extends BaseApiHandlerTestCase { public function testValidPageAndLimit() { $layout = $this->createMailLayout(); $mailType = $this->createMailTypeWithCategory('test_category', 'test_mail_type'); foreach (range(1, 10) as $i) { $this->createTemplate($layout, $mailType, 'template_' . $i); } $handler = $this->getHandler(MailTemplatesListingHandler::class); // get 2 latest templates $params = ['limit' => 2, 'page' => 1]; $response = $handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(2, $response->getPayload()); $this->assertEquals('template_10', $response->getPayload()[0]['code']); $this->assertEquals('template_9', $response->getPayload()[1]['code']); $params = ['limit' => 2, 'page' => 3]; $response = $handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(2, $response->getPayload()); $this->assertEquals('template_6', $response->getPayload()[0]['code']); $this->assertEquals('template_5', $response->getPayload()[1]['code']); } #[DataProvider('badRequestDataProvider')] public function testBadRequest($params, $error) { $handler = $this->getHandler(MailTemplatesListingHandler::class); $response = $handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals($error, $response->getPayload()['code']); } public static function badRequestDataProvider() { return [ 'PageLimit_MissingPage' => [ 'params' => ['limit' => 10], 'error' => 'invalid_pagination_params', ], 'PageLimit_ZeroPage' => [ 'params' => ['limit' => 10, 'page' => 0], 'error' => 'invalid_pagination_params', ], 'PageLimit_NegativePage' => [ 'params' => ['limit' => 10, 'page' => -5], 'error' => 'invalid_pagination_params', ], 'PageLimit_StringPage' => [ 'params' => ['limit' => 10, 'page' => 'foo'], 'error' => 'invalid_pagination_params', ], ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/SendEmailHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/SendEmailHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Mailers; use Mockery; use Nette\Utils\Json; use PHPUnit\Framework\Attributes\DataProvider; use Remp\MailerModule\Api\v1\Handlers\Mailers\SendEmailHandler; use Remp\MailerModule\Repositories\LogsRepository; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\Hermes\Dispatcher; use Tomaj\Hermes\Handler\HandlerInterface; use Tomaj\NetteApi\Response\JsonApiResponse; class SendEmailHandlerTest extends BaseApiHandlerTestCase { /** @var SendEmailHandler */ private $handler; /** @var Dispatcher */ private $dispatcher; private $template; public function setUp(): void { parent::setUp(); $layout = $this->createMailLayout(); $mailType = $this->createMailTypeWithCategory('test_category', 'test_mail_type'); $this->template = $this->createTemplate($layout, $mailType, 'test_template'); $this->handler = $this->getHandler(SendEmailHandler::class); $this->dispatcher = $this->inject(Dispatcher::class); } public static function dataProvider() { return [ 'ValidParams_ShouldEmitSendEmail' => [ 'params' => [ 'email' => 'admin@example.com', 'mail_template_code' => 'test_template', 'context' => 'test_context', ], 'emitted' => 1, 'httpCode' => 202, ], 'InvalidMailTemplate_ShouldReturnNotFound' => [ 'params' => [ 'email' => 'admin@example.com', 'mail_template_code' => 'foo', 'context' => 'test_context', ], 'emitted' => 0, 'httpCode' => 404, ], 'AlreadySentContext_SameEmail_ShouldNotSendEmail' => [ 'params' => [ 'email' => 'admin@example.com', 'mail_template_code' => 'test_template', 'context' => 'test_context', ], 'emitted' => 0, 'httpCode' => 200, 'beforeTest' => function ($self) { $self->writeMailLog('admin@example.com', 'test_context'); }, ], 'AlreadySentContext_DifferentEmail_ShouldEmitSendEmail' => [ 'params' => [ 'email' => 'admin@example.com', 'mail_template_code' => 'test_template', 'context' => 'test_context', ], 'emitted' => 1, 'httpCode' => 202, 'beforeTest' => function ($self) { $self->writeMailLog('user@example.com', 'test_context'); }, ], ]; } #[DataProvider('dataProvider')] public function testSendEmailHandler(array $params, int $emitted, int $httpCode, callable $beforeTest = null) { if ($beforeTest) { $beforeTest($this); } /** @var HandlerInterface $mockListener */ $mockListener = Mockery::mock(HandlerInterface::class) ->shouldReceive('handle') ->times($emitted) ->getMock(); $this->dispatcher->registerHandler('send-email', $mockListener); $response = $this->request($params); $this->assertEquals($httpCode, $response->getCode()); $this->dispatcher->handle(); } private function request(array $params): JsonApiResponse { $response = $this->handler->handle([ 'raw' => Json::encode($params), ]); $this->assertInstanceOf(JsonApiResponse::class, $response); return $response; } private function writeMailLog($email, $context) { /** @var LogsRepository $mailLogs */ $mailLogs = $this->inject(LogsRepository::class); $mailLogs->add($email, 'test_subject', $this->template->id, null, null, null, null, $context); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailTypeUpsertHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailTypeUpsertHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Mailers; use Nette\Utils\Json; use Remp\MailerModule\Api\v1\Handlers\Mailers\MailTypeUpsertHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class MailTypeUpsertHandlerTest extends BaseApiHandlerTestCase { /** @var MailTypeUpsertHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(MailTypeUpsertHandler::class); } public function testEmptyUpsert() { $response = $this->request([]); $this->assertEquals(400, $response->getCode()); $this->assertEquals('invalid_input', $response->getPayload()['code']); } public function testNewMailType() { $layout = $this->createMailLayout(); $systemMailType = $this->createMailTypeWithCategory('system', 'system'); $testedMailType = $this->createMailTypeWithCategory('newsletters', 'editorial'); $welcomeEmail1 = $this->createTemplate($layout, $systemMailType); $welcomeEmail2 = $this->createTemplate($layout, $systemMailType); $goodbyeEmail1 = $this->createTemplate($layout, $systemMailType); $goodbyeEmail2 = $this->createTemplate($layout, $systemMailType); // assign "subscribe" email $response = $this->request([ 'code' => $testedMailType->code, 'subscribe_mail_template_code' => $welcomeEmail1->code, ]); $this->assertEquals(200, $response->getCode()); $testedMailType = $this->listsRepository->find($testedMailType->id); $this->assertEquals($welcomeEmail1->id, $testedMailType->subscribe_mail_template_id); // change "subscribe" email $response = $this->request([ 'code' => $testedMailType->code, 'subscribe_mail_template_code' => $welcomeEmail2->code, ]); $this->assertEquals(200, $response->getCode()); $testedMailType = $this->listsRepository->find($testedMailType->id); $this->assertEquals($welcomeEmail2->id, $testedMailType->subscribe_mail_template_id); // try to change "subscribe" email to nonexisting mail $response = $this->request([ 'code' => $testedMailType->code, 'subscribe_mail_template_code' => 'foo', ]); $this->assertEquals(404, $response->getCode()); $this->assertEquals('subscribe_template_not_found', $response->getPayload()['code']); // unassign subscribe email $response = $this->request([ 'code' => $testedMailType->code, 'subscribe_mail_template_code' => null, ]); $this->assertEquals(200, $response->getCode()); $testedMailType = $this->listsRepository->find($testedMailType->id); $this->assertNull($testedMailType->subscribe_mail_template_id); // assign "unsubscribe" email $response = $this->request([ 'code' => $testedMailType->code, 'unsubscribe_mail_template_code' => $goodbyeEmail1->code, ]); $this->assertEquals(200, $response->getCode()); $testedMailType = $this->listsRepository->find($testedMailType->id); $this->assertEquals($goodbyeEmail1->id, $testedMailType->unsubscribe_mail_template_id); // change "unsubscribe" email $response = $this->request([ 'code' => $testedMailType->code, 'unsubscribe_mail_template_code' => $goodbyeEmail2->code, ]); $this->assertEquals(200, $response->getCode()); $testedMailType = $this->listsRepository->find($testedMailType->id); $this->assertEquals($goodbyeEmail2->id, $testedMailType->unsubscribe_mail_template_id); // try to change "unsubscribe" email to nonexisting mail $response = $this->request([ 'code' => $testedMailType->code, 'unsubscribe_mail_template_code' => 'foo', ]); $this->assertEquals(404, $response->getCode()); $this->assertEquals('unsubscribe_template_not_found', $response->getPayload()['code']); // unassign unsubscribe email $response = $this->request([ 'code' => $testedMailType->code, 'unsubscribe_mail_template_code' => null, ]); $this->assertEquals(200, $response->getCode()); $testedMailType = $this->listsRepository->find($testedMailType->id); $this->assertNull($testedMailType->unsubscribe_mail_template_id); } public function testMailTypeSubscribeTemplateManipulation() { $layout = $this->createMailLayout(); $mailType = $this->createMailTypeWithCategory('system', 'system'); $welcomeEmail = $this->createTemplate($layout, $mailType); $response = $this->request([ 'code' => 'test_mail_type', 'mail_type_category_id' => $mailType->mail_type_category->id, 'priority' => 100, 'title' => 'TEST mail type', 'description' => 'TEST description', ]); $this->assertEquals(200, $response->getCode()); } private function request(array $params): JsonApiResponse { $response = $this->handler->handle([ 'raw' => Json::encode($params), ]); $this->assertInstanceOf(JsonApiResponse::class, $response); return $response; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailTypesListingHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailTypesListingHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Mailers; use Remp\MailerModule\Api\v1\Handlers\Mailers\MailTypesListingHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class MailTypesListingHandlerTest extends BaseApiHandlerTestCase { /** @var MailTypesListingHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(MailTypesListingHandler::class); } public function testEmptyList() { $params = []; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(0, $response->getPayload()['data']); } public function testListWithFilters() { $this->createMailTypeWithCategory("category1", "code1", "name1", true); $this->createMailTypeWithCategory("category1", "code2", "name2", false); $params = ['public_listing' => 1]; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $response->getPayload()['data']); } public function testListWithCode() { $this->createMailTypeWithCategory("category1", "code1", "name1"); $this->createMailTypeWithCategory("category1", "code2", "name2"); $params = ['code' => 'code2']; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $response->getPayload()['data']); } public function testListWithUnknownCode() { $this->createMailTypeWithCategory("category1", "code1", "name1"); $this->createMailTypeWithCategory("category1", "code2", "name2"); $params = ['code' => 'code3']; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(0, $response->getPayload()['data']); } public function testListWithVariants() { $mailType = $this->createMailTypeWithCategory("category1", "code1", "name1"); $mailTypeVariant1 = $this->createMailTypeVariant($mailType, 'test1'); $mailTypeVariant2 = $this->createMailTypeVariant($mailType, 'test2'); $params = []; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(2, $response->getPayload()['data'][0]->variants); $this->listVariantsRepository->softDelete($mailTypeVariant1); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $data = $response->getPayload()['data']; $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $data[0]->variants); $this->assertEquals([$mailTypeVariant2->id => $mailTypeVariant2->title], $data[0]->variants); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailJobCreateApiHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailJobCreateApiHandlerTest.php
<?php namespace Tests\Feature\Api\v1\Handlers\Mailers; use Remp\MailerModule\Api\v1\Handlers\Mailers\MailJobCreateApiHandler; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Repositories\ActiveRow; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class MailJobCreateApiHandlerTest extends BaseApiHandlerTestCase { /** @var MailJobCreateApiHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(MailJobCreateApiHandler::class); } public function testValidRequiredParamsShouldCreateNewJob() { $params = $this->getDefaultParams(); unset($params['context'], $params['mail_type_variant_code']); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $payload = $response->getPayload(); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $this->assertEquals('ok', $payload['status']); $this->assertIsNumeric($payload['id']); $mailJob = $this->jobsRepository->find($payload['id']); $jobSegmentsManager = new JobSegmentsManager($mailJob); $this->assertEquals($params['segment_code'], $jobSegmentsManager->getIncludeSegments()[0]['code']); $this->assertEquals($params['segment_provider'], $jobSegmentsManager->getIncludeSegments()[0]['provider']); $this->assertNull($mailJob->context); $this->assertNull($mailJob->mail_type_variant_id); } public function testValidAllParamsShouldCreateNewJob() { $params = $this->getDefaultParams(); $tomorrow = new \DateTime('tomorrow 15:00'); $params['start_at'] = $tomorrow->format(DATE_RFC3339); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $payload = $response->getPayload(); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $this->assertEquals('ok', $payload['status']); $this->assertIsNumeric($payload['id']); /** @var ActiveRow $mailJob */ $mailJob = $this->jobsRepository->find($payload['id']); $jobSegmentsManager = new JobSegmentsManager($mailJob); $this->assertEquals($params['segment_code'], $jobSegmentsManager->getIncludeSegments()[0]['code']); $this->assertEquals($params['segment_provider'], $jobSegmentsManager->getIncludeSegments()[0]['provider']); $this->assertEquals($params['context'], $mailJob->context); $this->assertEquals($params['mail_type_variant_code'], $mailJob->mail_type_variant->code); $mailJobBatch = $mailJob->related('mail_job_batch')->fetch(); $this->assertEquals($tomorrow, $mailJobBatch->start_at); } public function testInvalidTemplate() { $params = $this->getDefaultParams(); $params['template_id']++; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(404, $response->getCode()); $this->assertEquals('error', $response->getPayload()['status']); } public function testInvalidSegmentCode() { $params = $this->getDefaultParams(); $params['segment_code'] = 'invalid_segment'; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(404, $response->getCode()); $this->assertEquals('error', $response->getPayload()['status']); } public function testInvalidSegmentProvider() { $params = $this->getDefaultParams(); $params['segment_provider'] = 'invalid_segment'; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(404, $response->getCode()); $this->assertEquals('error', $response->getPayload()['status']); } public function testInvalidMailTypeVariant() { $params = $this->getDefaultParams(); $params['mail_type_variant_code'] = 'invalid-variant'; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(404, $response->getCode()); $this->assertEquals('error', $response->getPayload()['status']); } public function testDeletedMailTypeVariant() { $params = $this->getDefaultParams(); $mailTypeVariantCode = $params['mail_type_variant_code']; $mailTypeVariant = $this->listVariantsRepository->findByCode($mailTypeVariantCode); $this->listVariantsRepository->softDelete($mailTypeVariant); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(404, $response->getCode()); $this->assertEquals('error', $response->getPayload()['status']); } private function getDefaultParams() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $mailLayout = $this->createMailLayout(); $mailTemplate = $this->createTemplate($mailLayout, $mailType); $mailTypeVariant = $this->createMailTypeVariant($mailType); return [ 'segment_code' => 'dummy-segment', 'segment_provider' => 'dummy-segment', 'template_id' => $mailTemplate->id, 'mail_type_variant_code' => $mailTypeVariant->code, 'context' => 'context' ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailTypeVariantCreateApiHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Mailers/MailTypeVariantCreateApiHandlerTest.php
<?php namespace Tests\Feature\Api\v1\Handlers\Mailers; use Nette\Utils\Json; use Remp\MailerModule\Api\v1\Handlers\Mailers\MailTypeVariantCreateApiHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class MailTypeVariantCreateApiHandlerTest extends BaseApiHandlerTestCase { /** @var MailTypeVariantCreateApiHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(MailTypeVariantCreateApiHandler::class); } public function testValidParamsShouldCreateNewMailTypeVariant() { $params = $this->getDefaultParams(); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $payload = $response->getPayload(); $params = Json::decode($params['raw']); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $this->assertEquals('ok', $payload['status']); $this->assertIsNumeric($payload['id']); $this->assertEquals($params->mail_type_code, $payload['mail_type_code']); $this->assertEquals($params->title, $payload['title']); $this->assertEquals($params->code, $payload['code']); $this->assertEquals($params->sorting, $payload['sorting']); $mailTypeVariant = $this->listVariantsRepository->find($payload['id']); $this->assertEquals($params->mail_type_code, $mailTypeVariant->mail_type->code); $this->assertEquals($params->title, $mailTypeVariant->title); $this->assertEquals($params->code, $mailTypeVariant->code); $this->assertEquals($params->sorting, $mailTypeVariant->sorting); } public function testValidOnlyRequiredParamsShouldCreateNewMailTypeVariant() { $params = $this->getDefaultParams(sorting: null); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $payload = $response->getPayload(); $params = Json::decode($params['raw']); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(200, $response->getCode()); $this->assertEquals('ok', $payload['status']); $this->assertIsNumeric($payload['id']); $this->assertEquals($params->mail_type_code, $payload['mail_type_code']); $this->assertEquals($params->title, $payload['title']); $this->assertEquals($params->code, $payload['code']); $this->assertIsNumeric($payload['sorting']); $mailTypeVariant = $this->listVariantsRepository->find($payload['id']); $this->assertEquals($params->mail_type_code, $mailTypeVariant->mail_type->code); $this->assertEquals($params->title, $mailTypeVariant->title); $this->assertEquals($params->code, $mailTypeVariant->code); $this->assertIsNumeric($mailTypeVariant->sorting); } public function testInvalidMailTypeCode() { $params = $this->getDefaultParams('invalid-code'); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $payload = $response->getPayload(); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(404, $response->getCode()); $this->assertEquals('error', $payload['status']); } public function testMailTypeVariantAlreadyExists() { $params = $this->getDefaultParams(); // creates mail type variant $this->handler->handle($params); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $payload = $response->getPayload(); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(400, $response->getCode()); $this->assertEquals('error', $payload['status']); } private function getDefaultParams($mailTypeCode = null, $sorting = 100) { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $payload = [ 'mail_type_code' => $mailTypeCode ?? $mailType->code, 'title' => 'Title', 'code' => 'code', ]; if (isset($sorting)) { $payload['sorting'] = $sorting; } return [ 'raw' => Json::encode($payload) ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/SubscribeHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/SubscribeHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Users; use Nette\Http\IResponse; use Nette\Utils\Json; use PHPUnit\Framework\Attributes\DataProvider; use Remp\MailerModule\Api\v1\Handlers\Users\SubscribeHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class SubscribeHandlerTest extends BaseApiHandlerTestCase { /** @var SubscribeHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(SubscribeHandler::class); } public function testSuccessfulSubscribeWithID() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_id' => $mailType->id, ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $isSubscribed = (bool) $this->userSubscriptionsRepository->getTable()->where([ 'user_id' => 123, 'user_email' => 'example@example.com', 'mail_type_id' => $mailType->id, 'subscribed' => 1, ])->count('*'); $this->assertTrue($isSubscribed); } public function testSuccessfulSubscribeWithCode() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $isSubscribed = (bool) $this->userSubscriptionsRepository->getTable()->where([ 'user_id' => 123, 'user_email' => 'example@example.com', 'mail_type_id' => $mailType->id, 'subscribed' => 1, ])->count('*'); $this->assertTrue($isSubscribed); } public function testSuccessfulSubscribeHavingMultipleVariants() { $mailType = $this->createMailTypeWithCategory(isMultiVariant: true); $variant1 = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $variant2 = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); /** @var JsonApiResponse $response */ $response = $this->handler->handle([ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, ]) ]); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $payload = $response->getPayload(); $this->assertEquals('ok', $payload['status']); $this->assertEqualsCanonicalizing([ (object) [ 'id' => $variant1->id, 'title' => $variant1->title, 'code' => $variant1->code, 'sorting' => $variant1->sorting, ], (object) [ 'id' => $variant2->id, 'title' => $variant2->title, 'code' => $variant2->code, 'sorting' => $variant2->sorting, ] ], $payload['subscribed_variants']); } public function testSuccessfulSubscribeHavingMultipleVariantsWithDefaultVariant() { $mailType = $this->createMailTypeWithCategory(isMultiVariant: true); $variant1 = $this->createMailTypeVariant($mailType, 'Foo', 'foo', isDefaultVariant: true); $variant2 = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); /** @var JsonApiResponse $response */ $response = $this->handler->handle([ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, ]) ]); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $payload = $response->getPayload(); $this->assertEquals('ok', $payload['status']); $this->assertEqualsCanonicalizing([ (object) [ 'id' => $variant1->id, 'title' => $variant1->title, 'code' => $variant1->code, 'sorting' => $variant1->sorting, ] ], $payload['subscribed_variants']); } public function testSuccessfulSubscribeWithVariantId() { $mailType = $this->createMailTypeWithCategory(isMultiVariant: true); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $variantNotSubscribed = $this->createMailTypeVariant($mailType, 'Foo2', 'foo2'); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_id' => $variant->id, ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $isSubscribed = (bool) $this->userSubscriptionVariantsRepository->getTable()->where([ 'mail_user_subscription.user_id' => 123, 'mail_user_subscription.user_email' => 'example@example.com', 'mail_user_subscription.subscribed' => 1, 'mail_type_variant_id' => $variant->id, ])->count('*'); $this->assertTrue($isSubscribed); $payload = $response->getPayload(); $this->assertEquals('ok', $payload['status']); $this->assertEqualsCanonicalizing([ (object) [ 'id' => $variant->id, 'title' => $variant->title, 'code' => $variant->code, 'sorting' => $variant->sorting, ] ], $payload['subscribed_variants']); } public function testSuccessfulSubscribeWithVariantCode() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_code' => $variant->code, ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $isSubscribed = (bool) $this->userSubscriptionVariantsRepository->getTable()->where([ 'mail_user_subscription.user_id' => 123, 'mail_user_subscription.user_email' => 'example@example.com', 'mail_user_subscription.subscribed' => 1, 'mail_type_variant_id' => $variant->id, ])->count('*'); $this->assertTrue($isSubscribed); } public function testSuccessfulSubscribeWithRtmParams() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'rtm_params' => [ 'rtm_source' => 'test', 'rtm_medium' => 'engine', 'rtm_campaign' => 'cmp', 'rtm_content' => 'code', ] ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $isSubscribed = (bool) $this->userSubscriptionsRepository->getTable()->where([ 'user_id' => 123, 'user_email' => 'example@example.com', 'mail_type_id' => $mailType->id, 'subscribed' => 1, 'rtm_source' => 'test', 'rtm_medium' => 'engine', 'rtm_campaign' => 'cmp', 'rtm_content' => 'code', ])->count('*'); $this->assertTrue($isSubscribed); } public function testFailingSubscribeWithInvalidVariantCode() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_code' => 'code_wrong', ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S404_NotFound, $response->getCode()); $isSubscribed = (bool) $this->userSubscriptionVariantsRepository->getTable()->where([ 'mail_user_subscription.user_id' => 123, 'mail_user_subscription.user_email' => 'example@example.com', 'mail_user_subscription.subscribed' => 1, 'mail_type_variant_id' => $variant->id, ])->count('*'); $this->assertFalse($isSubscribed); } #[DataProvider('forceNoVariantSubscriptionDataProvider')] public function testUseOfForceNoVariantSubscriptionFlag(bool $multi, bool $default) { $mailType = $this->createMailTypeWithCategory( categoryName: "category1", typeCode: "code1", typeName: "name1", isMultiVariant: $multi, ); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); if ($default) { $defaultVariant = $this->createMailTypeVariant($mailType, 'Bar', 'bar'); $this->listsRepository->update($mailType, [ 'default_variant_id' => $defaultVariant->id, ]); } $payload = [ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_code' => $variant->code, 'force_no_variant_subscription' => true, ]; $params = [ 'raw' => Json::encode($payload) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $userSubscription = $this->userSubscriptionsRepository->getUserSubscription( mailType: $mailType, userId: $payload['user_id'], email: $payload['email'] ); $this->assertTrue((bool) $userSubscription->subscribed); $isVariantSubscribed = (bool) $this->userSubscriptionVariantsRepository->getTable()->where([ 'mail_user_subscription.user_id' => $payload['user_id'], 'mail_user_subscription.user_email' => $payload['email'], ])->count('*'); $this->assertFalse($isVariantSubscribed); } public static function forceNoVariantSubscriptionDataProvider() { return [ 'NoMultiVariant_NoDefaultVariant' => [ 'multi' => false, 'default' => false, ], 'WithMultiVariant_NoDefaultVariant' => [ 'multi' => true, 'default' => false, ], 'NoMultiVariant_WithDefaultVariant' => [ 'multi' => false, 'default' => true, ], 'WithMultiVariant_WithDefaultVariant' => [ 'multi' => true, 'default' => true, ], ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/UnsubscribeHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/UnsubscribeHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Users; use Nette\Http\IResponse; use Nette\Utils\Json; use Remp\MailerModule\Api\v1\Handlers\Users\UnSubscribeHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class UnsubscribeHandlerTest extends BaseApiHandlerTestCase { /** @var UnSubscribeHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(UnSubscribeHandler::class); } public function testSuccessfulUnsubscribeWithID() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_id' => $mailType->id, ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $isNotSubscribed = (bool) $this->userSubscriptionsRepository->getTable()->where([ 'user_id' => 123, 'user_email' => 'example@example.com', 'mail_type_id' => $mailType->id, 'subscribed' => 0, ])->count('*'); $this->assertTrue($isNotSubscribed); } public function testSuccessfulUnsubscribeWithCode() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $this->createMailUserSubscription($mailType, 123, 'example@example.com'); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $isNotSubscribed = (bool) $this->userSubscriptionsRepository->getTable()->where([ 'user_id' => 123, 'user_email' => 'example@example.com', 'mail_type_id' => $mailType->id, 'subscribed' => 0, ])->count('*'); $this->assertTrue($isNotSubscribed); } public function testSuccessfulUnsubscribeWithVariantId() { $mailType = $this->createMailTypeWithCategory("category1", "code1", "name1"); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $this->createMailUserSubscription($mailType, 123, 'example@example.com', $variant->id); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_id' => $variant->id, ]) ]; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $this->assertNull($this->userSubscriptionVariantsRepository->getTable()->where([ 'mail_user_subscription.user_id' => 123, 'mail_user_subscription.user_email' => 'example@example.com', 'mail_type_variant_id' => $variant->id, ])->fetch()); $this->assertTrue($this->userSubscriptionsRepository->isUserUnsubscribed(123, $mailType->id)); } public function testSuccessfulUnsubscribeWithVariantIdButKeepMailType() { $mailType = $this->createMailTypeWithCategory("category1", "code1", "name1"); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $this->createMailUserSubscription($mailType, 123, 'example@example.com', $variant->id); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_id' => $variant->id, 'keep_list_subscription' => true, ]) ]; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $this->assertNull($this->userSubscriptionVariantsRepository->getTable()->where([ 'mail_user_subscription.user_id' => 123, 'mail_user_subscription.user_email' => 'example@example.com', 'mail_type_variant_id' => $variant->id, ])->fetch()); // user should still be kept in mail type subscription $this->assertFalse($this->userSubscriptionsRepository->isUserUnsubscribed(123, $mailType->id)); } public function testSuccessfulUnsubscribeWithVariantCode() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $this->createMailUserSubscription($mailType, 123, 'example@example.com', $variant->id); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_code' => $variant->code, ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $variantSubscription = $this->userSubscriptionVariantsRepository->getTable()->where([ 'mail_user_subscription.user_id' => 123, 'mail_user_subscription.user_email' => 'example@example.com', 'mail_type_variant_id' => $variant->id, ])->fetch(); $this->assertNull($variantSubscription); } public function testSuccessfulUnsubscribeWithRtmParams() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $this->createMailUserSubscription($mailType, 123, 'example@example.com', $variant->id); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_code' => $variant->code, 'rtm_params' => [ 'rtm_source' => 'test', 'rtm_medium' => 'engine', 'rtm_campaign' => 'cmp', 'rtm_content' => 'code', ] ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $isNotSubscribed = (bool) $this->userSubscriptionsRepository->getTable()->where([ 'user_id' => 123, 'user_email' => 'example@example.com', 'mail_type_id' => $mailType->id, 'subscribed' => 0, 'rtm_source' => 'test', 'rtm_medium' => 'engine', 'rtm_campaign' => 'cmp', 'rtm_content' => 'code', ])->count('*'); $this->assertTrue($isNotSubscribed); } public function testFailingSubscribeWithInvalidVariantCode() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $variant = $this->createMailTypeVariant($mailType, 'Foo', 'foo'); $this->createMailUserSubscription($mailType, 123, 'example@example.com', $variant->id); $params = [ 'raw' => Json::encode([ 'user_id' => 123, 'email' => 'example@example.com', 'list_code' => $mailType->code, 'variant_code' => 'code_wrong', ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S404_NotFound, $response->getCode()); $isSubscribed = (bool) $this->userSubscriptionVariantsRepository->getTable()->where([ 'mail_user_subscription.user_id' => 123, 'mail_user_subscription.user_email' => 'example@example.com', 'mail_user_subscription.subscribed' => 1, 'mail_type_variant_id' => $variant->id, ])->count('*'); $this->assertTrue($isSubscribed); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/UserDeleteApiHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/UserDeleteApiHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Users; use Nette\Database\Table\ActiveRow; use Nette\Http\IResponse; use Nette\Utils\DateTime; use Nette\Utils\Json; use Remp\MailerModule\Api\v1\Handlers\Users\UserDeleteApiHandler; use Remp\MailerModule\Models\Auth\TokenGenerator; use Remp\MailerModule\Repositories\JobQueueRepository; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; use Tomaj\NetteApi\Response\TextApiResponse; class UserDeleteApiHandlerTest extends BaseApiHandlerTestCase { /** @var UserDeleteApiHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(UserDeleteApiHandler::class); } public function testNoUserDataToDeleteError() { $email = 'example@example.com'; $params = [ 'raw' => Json::encode([ 'email' => $email, ]) ]; /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $payload = $response->getPayload(); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S404_NotFound, $response->getCode()); $this->assertEquals('error', $payload['status']); $this->assertStringStartsWith('No user data found for email', $payload['message']); $this->assertStringContainsString($email, $payload['message']); } public function testUserDataDeletedSuccess() { [ 'template' => $mailTemplate, 'mail_type_variant' => $mailTypeVariant, 'batch' => $batch, ] = $this->prepareMailData(); $email = 'example@example.com'; $this->seedUserData($email, $mailTemplate, $mailTypeVariant, $batch); // create two more users with data to check if only one user's data were removed $this->seedUserData('other-user@example.com', $mailTemplate, $mailTypeVariant, $batch); $this->seedUserData('otter-animal@example.com', $mailTemplate, $mailTypeVariant, $batch); // check seed; 1 count of user's data; 3 together with two more users $this->assertEquals(3, $this->autoLoginTokensRepository->totalCount()); $this->assertEquals(1, $this->autoLoginTokensRepository->getTable()->where('email', $email)->count('*')); $this->assertEquals(3, $this->jobQueueRepository->totalCount()); $this->assertEquals(1, $this->jobQueueRepository->getTable()->where('email', $email)->count('*')); $this->assertEquals(3, $this->mailLogsRepository->totalCount()); $this->assertEquals(1, $this->mailLogsRepository->getTable()->where('email', $email)->count('*')); $this->assertEquals(3, $this->mailLogConversionsRepository->totalCount()); $this->assertEquals(1, $this->mailLogConversionsRepository->getTable()->where('mail_log.email', $email)->count('*')); $this->assertEquals(3, $this->userSubscriptionsRepository->totalCount()); $this->assertEquals(1, $this->userSubscriptionsRepository->getTable()->where('user_email', $email)->count('*')); $this->assertEquals(3, $this->userSubscriptionVariantsRepository->totalCount()); $this->assertEquals(1, $this->userSubscriptionVariantsRepository->getTable()->where('mail_user_subscription.user_email', $email)->count('*')); $params = [ 'raw' => Json::encode([ 'email' => $email, ]) ]; /** @var TextApiResponse $response */ $response = $this->handler->handle($params); $this->assertInstanceOf(TextApiResponse::class, $response); $this->assertEquals(IResponse::S204_NoContent, $response->getCode()); // check user data after removal; check if correct user was removed (has zero data); other two users should be untouched $this->assertEquals(2, $this->autoLoginTokensRepository->totalCount()); $this->assertEquals(0, $this->autoLoginTokensRepository->getTable()->where('email', $email)->count('*')); $this->assertEquals(2, $this->jobQueueRepository->totalCount()); $this->assertEquals(0, $this->jobQueueRepository->getTable()->where('email', $email)->count('*')); $this->assertEquals(2, $this->mailLogsRepository->totalCount()); $this->assertEquals(0, $this->mailLogsRepository->getTable()->where('email', $email)->count('*')); $this->assertEquals(2, $this->mailLogConversionsRepository->totalCount()); $this->assertEquals(0, $this->mailLogConversionsRepository->getTable()->where('mail_log.email', $email)->count('*')); $this->assertEquals(2, $this->userSubscriptionsRepository->totalCount()); $this->assertEquals(0, $this->userSubscriptionsRepository->getTable()->where('user_email', $email)->count('*')); $this->assertEquals(2, $this->userSubscriptionVariantsRepository->totalCount()); $this->assertEquals(0, $this->userSubscriptionVariantsRepository->getTable()->where('mail_user_subscription.user_email', $email)->count('*')); } /** MAIL DATA helper */ private function prepareMailData() { $mailType = $this->createMailTypeWithCategory( "category1", "code1", "name1" ); $mailLayout = $this->createMailLayout(); $mailTemplate = $this->createTemplate($mailLayout, $mailType, 'mail_template_code_1'); $mailTypeVariant = $this->createMailTypeVariant($mailTemplate->mail_type); $batch = $this->createJobAndBatch($mailTemplate, $mailTypeVariant); return [ 'template' => $mailTemplate, 'mail_type_variant' => $mailTypeVariant, 'batch' => $batch, ]; } /** USER DATA helpers */ private function seedUserData(string $email, ActiveRow $mailTemplate, ActiveRow $mailTypeVariant, ActiveRow $batch) { $mailLog = $this->createMailLog($email, $mailTemplate); $this->createMailLogConversion($mailLog); $this->createAutologinToken($email); $this->createJobQueue($email, $mailTemplate, $batch); $this->subscribeUserToVariant($email, $mailTypeVariant); } private function createMailLog(string $email, ActiveRow $mailTemplate): ActiveRow { return $this->mailLogsRepository->add( $email, 'subject', $mailTemplate->id ); } private function createMailLogConversion(ActiveRow $mailLog): void { $this->mailLogConversionsRepository->upsert($mailLog, new DateTime()); } private function createAutologinToken(string $email): ActiveRow { return $this->autoLoginTokensRepository->insert($this->autoLoginTokensRepository->getInsertData( TokenGenerator::generate(), $email, new DateTime(), new DateTime(), )); } private function createJobQueue(string $email, ActiveRow $mailTemplate, ActiveRow $batch): ActiveRow { return $this->jobQueueRepository->insert([ 'mail_batch_id' => $batch->id, 'mail_template_id' => $mailTemplate->id, 'status' => JobQueueRepository::STATUS_NEW, 'email' => $email, ]); } private function subscribeUserToVariant(string $email, ActiveRow $variant) { $this->userSubscriptionsRepository->subscribeUser($variant->mail_type, 1, $email, $variant->id); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/IsSubscribedHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/IsSubscribedHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Users; use Nette\Http\IResponse; use Nette\Utils\Json; use PHPUnit\Framework\Attributes\DataProvider; use Remp\MailerModule\Api\v1\Handlers\Users\IsSubscribedHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class IsSubscribedHandlerTest extends BaseApiHandlerTestCase { #[DataProvider('dataProvider')] public function testIsSubscribed($testParams, $isSubscribed) { // Prepare data $userId = 123; $email = 'example@example.com'; $mailType1 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code1'); $mailType2 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code2'); $mailType3 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code3'); $mailType4 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code4'); $variant1_1 = $this->createMailTypeVariant(mailType: $mailType1, code: 'variant1_1'); $variant1_2 = $this->createMailTypeVariant(mailType: $mailType1, code: 'variant1_2'); $this->createMailUserSubscription(mailType: $mailType1, userID: $userId, email: $email, variantID: $variant1_1->id); $this->createMailUserSubscription(mailType: $mailType2, userID: $userId, email: $email); $this->createMailUserSubscription(mailType: $mailType3, userID: $userId, email: $email); $this->userSubscriptionsRepository->unsubscribeUser($mailType3, $userId, $email); // Prepare params - data provider doesn't know IDs directly, get from code $variantsIds = [ $variant1_1->code => $variant1_1->id, $variant1_2->code => $variant1_2->id, ]; $mailTypesIds = [ $mailType1->code => $mailType1->id, $mailType2->code => $mailType2->id, $mailType3->code => $mailType3->id, $mailType4->code => $mailType4->id, ]; $params = array_filter([ "list_id" => $mailTypesIds[$testParams['list_code']], "variant_id" => isset($testParams['variant_code']) ? $variantsIds[$testParams['variant_code']] : null, "user_id" => $userId, "email" => $email, ]); // Test /** @var IsSubscribedHandler $handler */ $handler = $this->getHandler(IsSubscribedHandler::class); $response = $handler->handle(['raw' => Json::encode($params)]); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $payload = $response->getPayload(); $this->assertEquals($isSubscribed, $payload['is_subscribed']); } public static function dataProvider(): array { return [ [ 'testParams' => ['list_code' => 'code1', 'variant_code' => 'variant1_1'], 'isSubscribed' => true, ], [ 'testParams' => ['list_code' => 'code1'], 'isSubscribed' => true, ], [ 'testParams' => ['list_code' => 'code1', 'variant_code' => 'variant1_2'], 'isSubscribed' => false, ], [ 'testParams' => ['list_code' => 'code2'], 'isSubscribed' => true, ], [ 'testParams' => ['list_code' => 'code3'], 'isSubscribed' => false, ], [ 'testParams' => ['list_code' => 'code4'], 'isSubscribed' => false, ], ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/IsUnsubscribedHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/IsUnsubscribedHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v1\Handlers\Users; use Nette\Http\IResponse; use Nette\Utils\Json; use PHPUnit\Framework\Attributes\DataProvider; use Remp\MailerModule\Api\v1\Handlers\Users\IsUnsubscribedHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class IsUnsubscribedHandlerTest extends BaseApiHandlerTestCase { #[DataProvider('dataProvider')] public function testIsUnsubscribed($testParams, $isUnsubscribed) { // Prepare data $userId = 123; $email = 'example@example.com'; $mailType1 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code1'); $mailType2 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code2'); $mailType3 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code3'); $this->createMailUserSubscription(mailType: $mailType1, userID: $userId, email: $email); $this->createMailUserSubscription(mailType: $mailType2, userID: $userId, email: $email); $this->userSubscriptionsRepository->unsubscribeUser($mailType2, $userId, $email); // Prepare params - data provider doesn't know IDs directly, get from code $mailTypesIds = [ $mailType1->code => $mailType1->id, $mailType2->code => $mailType2->id, $mailType3->code => $mailType3->id, ]; $params = array_filter([ "list_id" => $mailTypesIds[$testParams['list_code']], "user_id" => $userId, "email" => $email, ]); // Test /** @var IsUnsubscribedHandler $handler */ $handler = $this->getHandler(IsUnsubscribedHandler::class); $response = $handler->handle(['raw' => Json::encode($params)]); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $payload = $response->getPayload(); $this->assertEquals($isUnsubscribed, $payload['is_unsubscribed']); } public static function dataProvider(): array { return [ [ 'testParams' => ['list_code' => 'code1'], 'isUnsubscribed' => false, ], [ 'testParams' => ['list_code' => 'code2'], 'isUnsubscribed' => true, ], // if no record is present in mail_user_subscriptions, return 'false' (user is not explicitly unsubscribed) [ 'testParams' => ['list_code' => 'code3'], 'isUnsubscribed' => false, ], ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/EmailChangedHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v1/Handlers/Users/EmailChangedHandlerTest.php
<?php declare(strict_types=1); namespace Feature\Api\v1\Handlers\Users; use League\Event\EventDispatcher; use Mockery; use Nette\Http\IResponse; use Remp\MailerModule\Api\v1\Handlers\Users\EmailChangedHandler; use Remp\MailerModule\Events\BeforeUserEmailChangeEvent; use Remp\MailerModule\Events\UserEmailChangedEvent; use Remp\MailerModule\Repositories\ActiveRow; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class EmailChangedHandlerTest extends BaseApiHandlerTestCase { public function testEmailChanged() { $userId = 123; $email = 'user@example.com'; $mailType1 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code1'); $mailType2 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code2'); $mailType3 = $this->createMailTypeWithCategory(categoryName: "category1", typeCode: 'code3'); $this->createMailUserSubscription(mailType: $mailType1, userID: $userId, email: $email); $this->createMailUserSubscription(mailType: $mailType2, userID: $userId, email: $email); $this->createMailUserSubscription(mailType: $mailType3, userID: $userId, email: $email); $this->userSubscriptionsRepository->unsubscribeUser($mailType3, $userId, $email); $beforeUserEmailChangeEventHandled = false; $userEmailChangedEventHandled = false; $beforeHandler = function (BeforeUserEmailChangeEvent $event) use (&$beforeUserEmailChangeEventHandled) { $this->assertSame('user@example.com', $event->originalEmail); $this->assertSame('shiny@example.com', $event->newEmail); $beforeUserEmailChangeEventHandled = true; }; $afterHandler = function (UserEmailChangedEvent $event) use (&$userEmailChangedEventHandled) { $this->assertSame('user@example.com', $event->originalEmail); $this->assertSame('shiny@example.com', $event->newEmail); $userEmailChangedEventHandled = true; }; /** @var EventDispatcher $dispatcher */ $dispatcher = $this->inject(EventDispatcher::class); $dispatcher->subscribeTo(BeforeUserEmailChangeEvent::class, $beforeHandler); $dispatcher->subscribeTo(UserEmailChangedEvent::class, $afterHandler); /** @var EmailChangedHandler $handler */ $handler = $this->getHandler(EmailChangedHandler::class); $response = $handler->handle([ 'original_email' => 'user@example.com', 'new_email' => 'shiny@example.com' ]); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S200_OK, $response->getCode()); $this->assertFalse($this->isSubscribed('user@example.com', $mailType1)); $this->assertFalse($this->isSubscribed('user@example.com', $mailType2)); $this->assertFalse($this->isSubscribed('user@example.com', $mailType3)); $this->assertTrue($this->isSubscribed('shiny@example.com', $mailType1)); $this->assertTrue($this->isSubscribed('shiny@example.com', $mailType2)); $this->assertFalse($this->isSubscribed('shiny@example.com', $mailType3)); $this->assertTrue($beforeUserEmailChangeEventHandled); $this->assertTrue($userEmailChangedEventHandled); } public function testNoEmailData() { $beforeUserEmailChangeEventHandled = false; $userEmailChangedEventHandled = false; $beforeHandler = function (BeforeUserEmailChangeEvent $event) use (&$beforeUserEmailChangeEventHandled) { $this->assertSame('user@example.com', $event->originalEmail); $this->assertSame('shiny@example.com', $event->newEmail); $beforeUserEmailChangeEventHandled = true; }; $afterHandler = function (UserEmailChangedEvent $event) use (&$userEmailChangedEventHandled) { $this->assertSame('user@example.com', $event->originalEmail); $this->assertSame('shiny@example.com', $event->newEmail); $userEmailChangedEventHandled = true; }; /** @var EventDispatcher $dispatcher */ $dispatcher = $this->inject(EventDispatcher::class); $dispatcher->subscribeTo(BeforeUserEmailChangeEvent::class, $beforeHandler); $dispatcher->subscribeTo(UserEmailChangedEvent::class, $afterHandler); /** @var EmailChangedHandler $handler */ $handler = $this->getHandler(EmailChangedHandler::class); $response = $handler->handle([ 'original_email' => 'user@example.com', 'new_email' => 'shiny@example.com' ]); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertEquals(IResponse::S404_NotFound, $response->getCode()); $payload = $response->getPayload(); $this->assertSame('no_subscription_found', $payload['code']); $this->assertTrue($beforeUserEmailChangeEventHandled); $this->assertFalse($userEmailChangedEventHandled); } private function isSubscribed(string $email, ActiveRow $mailType): bool { $subscription = $this->userSubscriptionsRepository->getEmailSubscription($mailType, $email); if (!$subscription) { return false; } return (bool) $subscription->subscribed; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v2/Mailers/MailTypesListingHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v2/Mailers/MailTypesListingHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v2\Mailers; use Remp\MailerModule\Api\v2\Handlers\Mailers\MailTypesListingHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class MailTypesListingHandlerTest extends BaseApiHandlerTestCase { /** @var MailTypesListingHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(MailTypesListingHandler::class); } public function testEmptyList() { $params = []; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(0, $response->getPayload()['data']); } public function testListPublic() { $this->createMailTypes(); $params = ['public_listing' => 1]; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $response->getPayload()['data']); } public function testListByCode() { $this->createMailTypes(); $params = ['code' => 'code2']; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $response->getPayload()['data']); } public function testListByUnknownCode() { $this->createMailTypes(); $params = ['code' => 'codeZ']; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(0, $response->getPayload()['data']); } public function testListByCategoryCode() { $this->createMailTypes(); $params = ['mail_type_category_code' => 'category2']; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $response->getPayload()['data']); } public function testListPublicByCategoryCode() { $this->createMailTypes(); $params = ['mail_type_category_code' => 'category2', 'public_listing' => 1]; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(0, $response->getPayload()['data']); } public function testListWithVariants() { $mailType = $this->createMailTypeWithCategory("category1", "code1", "name1"); $mailTypeVariant1 = $this->createMailTypeVariant($mailType, 'test1'); $mailTypeVariant2 = $this->createMailTypeVariant($mailType, 'test2'); $params = []; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(2, $response->getPayload()['data'][0]->variants); $this->listVariantsRepository->softDelete($mailTypeVariant1); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $data = $response->getPayload()['data']; $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $data[0]->variants); $this->assertEquals([$mailTypeVariant2->id => $mailTypeVariant2->title], $data[0]->variants); } private function createMailTypes() { $this->createMailTypeWithCategory("category1", "code1", "name1", true); $this->createMailTypeWithCategory("category1", "code2", "name2", false); $this->createMailTypeWithCategory("category2", "code3", "name3", false); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Api/v3/Mailers/MailTypesListingHandlerTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Api/v3/Mailers/MailTypesListingHandlerTest.php
<?php declare(strict_types=1); namespace Tests\Feature\Api\v3\Mailers; use Remp\MailerModule\Api\v3\Handlers\Mailers\MailTypesListingHandler; use Tests\Feature\Api\BaseApiHandlerTestCase; use Tomaj\NetteApi\Response\JsonApiResponse; class MailTypesListingHandlerTest extends BaseApiHandlerTestCase { /** @var MailTypesListingHandler */ private $handler; public function setUp(): void { parent::setUp(); $this->handler = $this->getHandler(MailTypesListingHandler::class); } public function testEmptyList() { $params = []; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(0, $response->getPayload()['data']); } public function testListPublic() { $this->createMailTypes(); $params = ['public_listing' => 1]; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $response->getPayload()['data']); } public function testListByCode() { $this->createMailTypes(); $params = ['code' => 'code2']; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $response->getPayload()['data']); } public function testListByUnknownCode() { $this->createMailTypes(); $params = ['code' => 'codeZ']; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(0, $response->getPayload()['data']); } public function testListByCategoryCode() { $this->createMailTypes(); $params = ['mail_type_category_code' => 'category2']; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $response->getPayload()['data']); } public function testListPublicByCategoryCode() { $this->createMailTypes(); $params = ['mail_type_category_code' => 'category2', 'public_listing' => 1]; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(0, $response->getPayload()['data']); } public function testListWithVariants() { $mailType = $this->createMailTypeWithCategory("category1", "code1", "name1"); $mailTypeVariant1 = $this->createMailTypeVariant($mailType, 'test1'); $mailTypeVariant2 = $this->createMailTypeVariant($mailType, 'test2'); $params = []; $response = $this->handler->handle($params); $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(2, $response->getPayload()['data'][0]->variants); $this->listVariantsRepository->softDelete($mailTypeVariant1); /** @var JsonApiResponse $response */ $response = $this->handler->handle($params); $data = $response->getPayload()['data']; $this->assertInstanceOf(JsonApiResponse::class, $response); $this->assertCount(1, $data[0]->variants); $this->assertEquals($mailTypeVariant2->title, $data[0]->variants[$mailTypeVariant2->id]->title); $this->assertEquals($mailTypeVariant2->code, $data[0]->variants[$mailTypeVariant2->id]->code); } private function createMailTypes() { $this->createMailTypeWithCategory("category1", "code1", "name1", true); $this->createMailTypeWithCategory("category1", "code2", "name2", false); $this->createMailTypeWithCategory("category2", "code3", "name3", false); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Feature/Commands/UnsubscribeInactiveUsersCommandTest.php
Mailer/extensions/mailer-module/src/Tests/Feature/Commands/UnsubscribeInactiveUsersCommandTest.php
<?php namespace Tests\Feature\Commands; use Nette\Database\Table\ActiveRow; use Nette\Utils\DateTime; use PHPUnit\Framework\Attributes\DataProvider; use Remp\MailerModule\Commands\UnsubscribeInactiveUsersCommand; use Remp\MailerModule\Models\RedisClientFactory; use Remp\MailerModule\Models\RedisClientTrait; use Remp\MailerModule\Models\Segment\Aggregator; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\NullOutput; use Tests\Feature\BaseFeatureTestCase; use Tests\Feature\TestSegmentProvider; class UnsubscribeInactiveUsersCommandTest extends BaseFeatureTestCase { use RedisClientTrait; protected TestSegmentProvider $testSegmentProvider; protected Aggregator $segmentAggregator; protected UnsubscribeInactiveUsersCommand $unsubscribeInactiveUsersCommand; protected ActiveRow $mailLayout; protected RedisClientFactory $redisClientFactory; private array $user = [ 'id' => 1, 'email' => 'user1@example.com', ]; private array $mailTypes = [ [ 'code' => 'system', 'name' => 'System', ], [ 'code' => 'test', 'name' => 'Test', ], [ 'code' => 'test-omit', 'name' => 'Test OMIT' ] ]; private ActiveRow $listCategory; public function setUp(): void { parent::setUp(); $this->testSegmentProvider = $this->inject(TestSegmentProvider::class); $this->testSegmentProvider->testUsers = [$this->user['id']]; $this->segmentAggregator = $this->inject(Aggregator::class); $this->segmentAggregator->register($this->testSegmentProvider); $this->redisClientFactory = $this->inject(RedisClientFactory::class); // remove email from `APPLE_BOT_EMAILS` redis key before every test $this->redis()->srem(UnsubscribeInactiveUsersCommand::APPLE_BOT_EMAILS, $this->user['email']); $this->unsubscribeInactiveUsersCommand = $this->inject(UnsubscribeInactiveUsersCommand::class); $this->mailLayout = $this->createMailLayout(); $this->listCategory = $this->listCategoriesRepository->add('Test lists category', 'test-lists-category', 1); foreach ($this->mailTypes as $mailType) { $list = $this->listsRepository->add( $this->listCategory->id, 1, $mailType['code'], $mailType['name'], 1, false, false, '' ); $this->templatesRepository->add($mailType['name'], $mailType['code'], '', 'test@example.com', '', '', '', $this->mailLayout->id, $list->id); } } public static function dataProvider() { return [ 'TooLittleDeliveredEmails_ShouldNotUnsubscribe' => [ 'subscribe' => ['system', 'test'], 'logs' => [ ['delivered' => '-11 days', 'opened' => null, 'clicked' => null], ['delivered' => '-10 days', 'opened' => null, 'clicked' => null], ['delivered' => '-9 days', 'opened' => null, 'clicked' => null], ], 'isAppleBotOpenedEmail' => false, 'result' => [ 'system' => true, 'test' => true, ], ], 'TooManyNotOpenedEmails_ShouldUnsubscribe' => [ 'subscribe' => ['system', 'test', 'test-omit'], 'logs' => [ ['delivered' => '-11 days', 'opened' => null, 'clicked' => null], ['delivered' => '-10 days', 'opened' => null, 'clicked' => null], ['delivered' => '-9 days', 'opened' => null, 'clicked' => null], ['delivered' => '-8 days', 'opened' => null, 'clicked' => null], ['delivered' => '-7 days', 'opened' => null, 'clicked' => null], ['delivered' => '-6 days', 'opened' => null, 'clicked' => null], ], 'isAppleBotOpenedEmail' => false, 'result' => [ 'system' => true, 'test' => false, 'test-omit' => false, ], ], 'TooManyNotOpenedEmails_WithOmit_ShouldUnsubscribe' => [ 'subscribe' => ['system', 'test', 'test-omit'], 'logs' => [ ['delivered' => '-11 days', 'opened' => null, 'clicked' => null], ['delivered' => '-10 days', 'opened' => null, 'clicked' => null], ['delivered' => '-9 days', 'opened' => null, 'clicked' => null], ['delivered' => '-8 days', 'opened' => null, 'clicked' => null], ['delivered' => '-7 days', 'opened' => null, 'clicked' => null], ['delivered' => '-6 days', 'opened' => null, 'clicked' => null], ], 'isAppleBotOpenedEmail' => false, 'result' => [ 'system' => true, 'test' => false, 'test-omit' => true, ], 'omit' => ['test-omit'], ], 'TooManyNotOpenedEmails_DryRun_ShouldNotUnsubscribe' => [ 'subscribe' => ['system', 'test'], 'logs' => [ ['delivered' => '-11 days', 'opened' => null, 'clicked' => null], ['delivered' => '-10 days', 'opened' => null, 'clicked' => null], ['delivered' => '-9 days', 'opened' => null, 'clicked' => null], ['delivered' => '-8 days', 'opened' => null, 'clicked' => null], ['delivered' => '-7 days', 'opened' => null, 'clicked' => null], ['delivered' => '-6 days', 'opened' => null, 'clicked' => null], ], 'isAppleBotOpenedEmail' => false, 'result' => [ 'system' => true, 'test' => true, ], 'omit' => [], 'dryRun' => true, ], 'SomeOpenedDeliveries_ShouldNotUnsubscribe' => [ 'subscribe' => ['system', 'test'], 'logs' => [ ['delivered' => '-11 days', 'opened' => null, 'clicked' => null], ['delivered' => '-10 days', 'opened' => null, 'clicked' => null], ['delivered' => '-9 days', 'opened' => null, 'clicked' => null], ['delivered' => '-8 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-7 days', 'opened' => null, 'clicked' => null], ['delivered' => '-6 days', 'opened' => null, 'clicked' => null], ], 'isAppleBotOpenedEmail' => false, 'result' => [ 'system' => true, 'test' => true, ], ], 'SomeClickedNotOpenedDeliveries_ShouldNotUnsubscribe' => [ 'subscribe' => ['system', 'test'], 'logs' => [ ['delivered' => '-11 days', 'opened' => null, 'clicked' => null], ['delivered' => '-10 days', 'opened' => null, 'clicked' => null], ['delivered' => '-9 days', 'opened' => null, 'clicked' => '-5 days'], ['delivered' => '-8 days', 'opened' => null, 'clicked' => null], ['delivered' => '-7 days', 'opened' => null, 'clicked' => null], ['delivered' => '-6 days', 'opened' => null, 'clicked' => null], ], 'isAppleBotOpenedEmail' => false, 'result' => [ 'system' => true, 'test' => true, ], ], 'AppleBotOpenedClickedDeliveries_ShouldNotUnsubscribe' => [ 'subscribe' => ['system', 'test'], 'logs' => [ ['delivered' => '-11 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-10 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-9 days', 'opened' => '-5 days', 'clicked' => '-5 days'], ['delivered' => '-8 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-7 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-6 days', 'opened' => '-5 days', 'clicked' => null], ], 'isAppleBotOpenedEmail' => true, 'result' => [ 'system' => true, 'test' => true, ], ], 'AppleBotOpenedNotClickedDeliveries_ShouldUnsubscribe' => [ 'subscribe' => ['system', 'test'], 'logs' => [ ['delivered' => '-11 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-10 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-9 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-8 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-7 days', 'opened' => '-5 days', 'clicked' => null], ['delivered' => '-6 days', 'opened' => '-5 days', 'clicked' => null], ], 'isAppleBotOpenedEmail' => true, 'result' => [ 'system' => true, 'test' => false, ], ], 'NotMatchedDeliveryThresholdWithinSelectedPeriod_ShouldNotUnsubscribe' => [ 'subscribe' => ['system', 'test', 'test-omit'], 'logs' => [ ['delivered' => '-11 days', 'opened' => null, 'clicked' => null], ['delivered' => '-10 days', 'opened' => null, 'clicked' => null], ['delivered' => '-9 days', 'opened' => null, 'clicked' => null], ['delivered' => '-8 days', 'opened' => null, 'clicked' => null], ['delivered' => '-7 days', 'opened' => null, 'clicked' => null], ['delivered' => '-6 days', 'opened' => null, 'clicked' => null], ], 'isAppleBotOpenedEmail' => false, 'result' => [ 'system' => true, 'test' => true, 'test-omit' => true, ], 'omit' => [], 'dryRun' => false, 'days' => 9, ], ]; } #[DataProvider('dataProvider')] public function testUnsubscribeInactive(array $subscribe, array $logs, bool $isAppleBotOpenedEmail, array $result, array $omit = [], bool $dryRun = false, int $days = null) { foreach ($subscribe as $mailTypeCode) { $this->susbcribeUser($this->user, $mailTypeCode); } foreach ($logs as $log) { $template = $this->templatesRepository->findBy('code', 'test'); $delivered = DateTime::from($log['delivered']); $opened = $log['opened'] ? DateTime::from($log['opened']) : null; $clicked = $log['clicked'] ? DateTime::from($log['clicked']) : null; $this->addMailLog($this->user, $template, $delivered, $opened, $clicked); } if ($isAppleBotOpenedEmail) { $this->redis()->sadd(UnsubscribeInactiveUsersCommand::APPLE_BOT_EMAILS, [$this->user['email']]); } $input = '--segment-provider ' . TestSegmentProvider::PROVIDER_ALIAS; if ($dryRun) { $input .= ' --dry-run'; } foreach ($omit as $mailTypeCode) { $input .= " --omit-mail-type-code {$mailTypeCode}"; } if ($days) { $input .= " --days {$days}"; } $stringInput = new StringInput($input); $this->unsubscribeInactiveUsersCommand->run($stringInput, new NullOutput()); foreach ($result as $mailTypeCode => $shouldBeSubscribed) { $mailType = $this->listsRepository->findByCode($mailTypeCode)->fetch(); $isSubscribed = $this->userSubscriptionsRepository->isUserSubscribed($this->user['id'], $mailType->id); $this->assertEquals($shouldBeSubscribed, $isSubscribed); } } private function susbcribeUser(array $user, string $mailTypeCode) { $list = $this->listsRepository->findByCode($mailTypeCode)->fetch(); $this->userSubscriptionsRepository->subscribeUser($list, $user['id'], $user['email']); } private function addMailLog(array $user, ActiveRow $template, DateTime $deliveredAt, ?DateTime $openedAt = null, ?DateTime $clickedAt = null) { $mailLog = $this->mailLogsRepository->add( email: $user['email'], subject: 'subject', templateId: $template->id, userId: $user['id'], ); $this->mailLogsRepository->update($mailLog, [ 'delivered_at' => $deliveredAt, 'opened_at' => $openedAt, 'clicked_at' => $clickedAt, ]); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Unit/RedisDriverTest.php
Mailer/extensions/mailer-module/src/Tests/Unit/RedisDriverTest.php
<?php declare(strict_types=1); namespace Tests\Unit; use Nette\DI\Container; use PHPUnit\Framework\TestCase; use Remp\MailerModule\Hermes\HermesTasksQueue; use Remp\MailerModule\Hermes\RedisDriver; use Remp\MailerModule\Repositories\HermesTasksRepository; use Tomaj\Hermes\Message; use Tomaj\Hermes\MessageSerializer; class RedisDriverTest extends TestCase { private $driver; private $mockQueue; public function setUp(): void { /** @var Container $container */ $container = $GLOBALS['container']; $this->mockQueue = $this->createMock(HermesTasksQueue::class); $this->driver = new RedisDriver( $container->getByType(HermesTasksRepository::class), $this->mockQueue ); $this->driver->setupSleepTime(0); $this->driver->setupPriorityQueue('default', 100); $this->driver->setupPriorityQueue('priority', 200); } public function testSendSingleMessage(): void { $message = new Message('message_1', ['a' => 'b']); $matcher = $this->exactly(2); $this->mockQueue->expects($matcher)->method('getTask') ->willReturnCallback(function (string $queueKey) use ($matcher, $message) { switch ($matcher->numberOfInvocations()) { case 1: $this->assertEquals($queueKey, 'priority'); return null; case 2: $this->assertEquals($queueKey, 'default'); return [(new MessageSerializer)->serialize($message)]; default: throw new \Exception('unhandled getTask() invocation'); } }); $processed = []; $this->driver->setMaxProcessItems(1); $this->driver->wait(function ($message) use (&$processed) { $processed[] = $message; }); $this->assertCount(1, $processed); $this->assertEquals($message->getId(), $processed[0]->getId()); } public function testSendMultiplePriorityMessage(): void { $messages = [ 1 => new Message('message_1', ['a' => 'b']), 2 => new Message('message_2', ['a' => 'b']), 3 => new Message('message_3', ['a' => 'b']), ]; $matcher = $this->exactly(4); $this->mockQueue->expects($matcher)->method('getTask') ->willReturnCallback(function (string $queueKey) use ($matcher, $messages) { switch ($matcher->numberOfInvocations()) { case 1: $this->assertEquals($queueKey, 'priority'); return [(new MessageSerializer)->serialize($messages[2])]; // 2 tasks in priority queue; case 2: $this->assertEquals($queueKey, 'priority'); return [(new MessageSerializer)->serialize($messages[3])]; // 1 tasks in priority queue case 3: $this->assertEquals($queueKey, 'priority'); return null; // 0 tasks in priority queue, moving on case 4: $this->assertEquals($queueKey, 'default'); return [(new MessageSerializer)->serialize($messages[1])]; // 1 task in default queue default: throw new \Exception('unhandled getTask() invocation'); } }); $processed = []; $this->driver->setMaxProcessItems(3); $this->driver->wait(function ($message) use (&$processed) { $processed[] = $message; }); $this->assertCount(3, $processed); $this->assertEquals($messages[2]->getId(), $processed[0]->getId()); $this->assertEquals($messages[3]->getId(), $processed[1]->getId()); $this->assertEquals($messages[1]->getId(), $processed[2]->getId()); } public function testNewPriorityTaskDuringRun(): void { $messages = [ 1 => new Message('message_1', ['a' => 'b']), 2 => new Message('message_2', ['a' => 'b']), 3 => new Message('message_3', ['a' => 'b']), ]; $matcher = $this->exactly(6); $this->mockQueue->expects($matcher)->method('getTask') ->willReturnCallback(function (string $queueKey) use ($matcher, $messages) { switch ($matcher->numberOfInvocations()) { case 1: $this->assertEquals($queueKey, 'priority'); return null; // 0 tasks in priority queue, moving on case 2: $this->assertEquals($queueKey, 'default'); return [(new MessageSerializer)->serialize($messages[1])]; // 1 task in default queue case 3: $this->assertEquals($queueKey, 'priority'); return [(new MessageSerializer)->serialize($messages[2])]; // 1 task in priority queue case 4: $this->assertEquals($queueKey, 'priority'); return null; // priority check again, 0 tasks in queue, moving on case 5: $this->assertEquals($queueKey, 'default'); return null; // 0 tasks in default queue, moving on case 6: $this->assertEquals($queueKey, 'priority'); return [(new MessageSerializer)->serialize($messages[3])]; // 1 task in default queue default: throw new \Exception('unhandled getTask() invocation'); } }); $processed = []; $this->driver->setMaxProcessItems(3); $this->driver->wait(function ($message) use (&$processed) { $processed[] = $message; }); $this->assertCount(3, $processed); $this->assertEquals($messages[1]->getId(), $processed[0]->getId()); $this->assertEquals($messages[2]->getId(), $processed[1]->getId()); $this->assertEquals($messages[3]->getId(), $processed[2]->getId()); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Unit/EmailAllowListTest.php
Mailer/extensions/mailer-module/src/Tests/Unit/EmailAllowListTest.php
<?php declare(strict_types=1); namespace Tests\Unit; use Nette\DI\Container; use PHPUnit\Framework\TestCase; use Remp\MailerModule\Models\Mailer\EmailAllowList; class EmailAllowListTest extends TestCase { protected EmailAllowList $emailAllowList; public function setUp(): void { /** @var Container $container */ $container = $GLOBALS['container']; $this->emailAllowList = $container->getByType(EmailAllowList::class); $this->emailAllowList->reset(); } public function testEmailAllowListEmptyShouldAllowAllEmailAddresses() { $this->assertTrue($this->emailAllowList->isAllowed('example1@example.com')); $this->assertTrue($this->emailAllowList->isAllowed('example2@example.com')); $this->assertTrue($this->emailAllowList->isAllowed('example3@example.com')); } public function testEmailAllowOnlySpecifiedEmails() { $this->emailAllowList->allow('example1@example.com'); $this->emailAllowList->allow('example2@example.com'); $this->assertTrue($this->emailAllowList->isAllowed('example1@example.com')); $this->assertTrue($this->emailAllowList->isAllowed('example2@example.com')); $this->assertFalse($this->emailAllowList->isAllowed('example2@example.sk')); } public function testEmailAllowAllEmailAddressesFromDomain() { $this->emailAllowList->allow('@example.com'); $this->assertTrue($this->emailAllowList->isAllowed('example1@example.com')); $this->assertTrue($this->emailAllowList->isAllowed('example2@example.com')); $this->assertFalse($this->emailAllowList->isAllowed('example2@example.sk')); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Unit/ContentGenerator/Replace/RtmClickReplaceTest.php
Mailer/extensions/mailer-module/src/Tests/Unit/ContentGenerator/Replace/RtmClickReplaceTest.php
<?php namespace Unit\ContentGenerator\Replace; use Nette\DI\Container; use PHPUnit\Framework\TestCase; use Remp\MailerModule\Models\ContentGenerator\Replace\AnchorRtmClickReplace; use Remp\MailerModule\Models\ContentGenerator\Replace\RtmClickReplace; class RtmClickReplaceTest extends TestCase { protected AnchorRtmClickReplace $rtmClickReplace; public function setUp(): void { /** @var Container $container */ $container = $GLOBALS['container']; $this->rtmClickReplace = $container->getByType(AnchorRtmClickReplace::class); } public function testRemoveQueryParams() { $url = $this->rtmClickReplace->removeQueryParams('https://expresso.pt/html/que-nao-entrou-em-acao'); $this->assertEquals( 'https://expresso.pt/html/que-nao-entrou-em-acao', $url ); $url = $this->rtmClickReplace->removeQueryParams('https://expresso.pt/html/que-nao-entrou-em-acao?rtm_click=1234'); $this->assertEquals( 'https://expresso.pt/html/que-nao-entrou-em-acao', $url ); $url = $this->rtmClickReplace->removeQueryParams('https://expresso.pt/html/que-nao-entrou-em-acao?rtm_click=1234&amp;rtm_content='); $this->assertEquals( 'https://expresso.pt/html/que-nao-entrou-em-acao', $url ); $url = $this->rtmClickReplace->removeQueryParams('https://expresso.pt/html/que-nao-entrou-em-acao?%recipeint.autologin%&amp;rtm_content='); $this->assertEquals( 'https://expresso.pt/html/que-nao-entrou-em-acao', $url ); } public function testSetRtmClickHashInUrl() { $url = $this->rtmClickReplace->setRtmClickHashInUrl('https://expresso.pt/html/que-nao-entrou-em-acao', '1234'); $this->assertEquals( sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?%s=1234', RtmClickReplace::HASH_PARAM), $url ); $url = $this->rtmClickReplace->setRtmClickHashInUrl(sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?%s=1234', RtmClickReplace::HASH_PARAM), '9876'); $this->assertEquals( sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?%s=9876', RtmClickReplace::HASH_PARAM), $url ); $url = $this->rtmClickReplace->setRtmClickHashInUrl('https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=123&rtm_source=', '9876'); $this->assertEquals( sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=123&rtm_source=&%s=9876', RtmClickReplace::HASH_PARAM), $url ); $url = $this->rtmClickReplace->setRtmClickHashInUrl(sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?%s=1234&rtm_content=123&rtm_source=', RtmClickReplace::HASH_PARAM), '9876'); $this->assertEquals( sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=123&rtm_source=&%s=9876', RtmClickReplace::HASH_PARAM), $url ); $url = $this->rtmClickReplace->setRtmClickHashInUrl('https://expresso.pt/html/que-nao-entrou-em-acao?%recipient.autologin%', '9876'); $this->assertEquals( sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?%%recipient.autologin%%&%s=9876', RtmClickReplace::HASH_PARAM), $url ); } public function testGetRtmClickHash() { $hash = $this->rtmClickReplace->getRtmClickHashFromUrl('https://expresso.pt/html/que-nao-entrou-em-acao'); $this->assertEquals( null, $hash ); $hash = $this->rtmClickReplace->getRtmClickHashFromUrl(sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?%s=1234', RtmClickReplace::HASH_PARAM)); $this->assertEquals( '1234', $hash ); $hash = $this->rtmClickReplace->getRtmClickHashFromUrl(sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?%s=1234&amp;rtm_content=qwert', RtmClickReplace::HASH_PARAM)); $this->assertEquals( '1234', $hash ); $hash = $this->rtmClickReplace->getRtmClickHashFromUrl(sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?%%recipient.autologin%%&%s=1234&amp;rtm_content=qwert', RtmClickReplace::HASH_PARAM)); $this->assertEquals( '1234', $hash ); $hash = $this->rtmClickReplace->getRtmClickHashFromUrl(sprintf('https://expresso.pt/html/que-nao-entrou-em-acao?rtm_source=&amp;%s=1234', RtmClickReplace::HASH_PARAM)); $this->assertEquals( null, $hash ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Unit/ContentGenerator/Replace/RtmReplaceTest.php
Mailer/extensions/mailer-module/src/Tests/Unit/ContentGenerator/Replace/RtmReplaceTest.php
<?php declare(strict_types=1); namespace Tests\Unit\ContentGenerator\Replace; use Nette\DI\Container; use PHPUnit\Framework\TestCase; use Remp\MailerModule\Models\ContentGenerator\GeneratorInput; use Remp\MailerModule\Models\ContentGenerator\GeneratorInputFactory; use Remp\MailerModule\Models\ContentGenerator\Replace\AnchorRtmReplace; use Remp\MailerModule\Repositories\ActiveRowFactory; class RtmReplaceTest extends TestCase { protected AnchorRtmReplace $rtmReplace; protected ActiveRowFactory $activeRowFactory; protected GeneratorInput $generatorInput; public function setUp(): void { /** @var Container $container */ $container = $GLOBALS['container']; $this->rtmReplace = $container->getByType(AnchorRtmReplace::class); $this->activeRowFactory = $container->getByType(ActiveRowFactory::class); $mailType = $this->activeRowFactory->create([ 'id' => 1, 'name' => 'type', 'code' => 'demo-weekly-newsletter' ]); $mailLayout = $this->activeRowFactory->create([ 'id' => 1, 'name' => "layout1", ]); $mailTemplate = $this->activeRowFactory->create([ 'name' => 'Tesst', 'code' => 'impresa_mail_20190903103350', 'description' => '', 'from' => 'from', 'autologin' => true, 'subject' => 'subject', 'mail_body_text' => 'textt', 'mail_body_html' => 'html', 'mail_layout_id' => $mailLayout->id, 'mail_layout' => $mailLayout, 'mail_type_id' => $mailType->id, 'mail_type' => $mailType ]); $generatorInputFactory = $container->getByType(GeneratorInputFactory::class); $this->generatorInput = $generatorInputFactory->create($mailTemplate); } public function testAddUtmParametersWhenTheUrlDoesNotContainAnyRtm() { $content = $this->rtmReplace->replace('<a href="https://expresso.pt/html/que-nao-entrou-em-acao" target="blank"/>', $this->generatorInput); $this->assertEquals( '<a href="https://expresso.pt/html/que-nao-entrou-em-acao?rtm_source=demo-weekly-newsletter&rtm_medium=email&rtm_campaign=impresa_mail_20190903103350&rtm_content=" target="blank"/>', $content ); } public function testReplaceExistingRtmParametersWhenTheUrlAlreadyContainsTheseUtm() { $content = $this->rtmReplace->replace('<a href="https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=apple&feira=terca&modelo=1?a=1&b=2" target="blank"/>', $this->generatorInput); $this->assertEquals( '<a href="https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=&feira=terca&modelo=1?a=1&b=2&rtm_source=demo-weekly-newsletter&rtm_medium=email&rtm_campaign=impresa_mail_20190903103350" target="blank"/>', $content ); } public function testFixHTMLEntitiesFromURL() { $content = $this->rtmReplace->replace('<a href="https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=apple&amp;feira=terca&modelo=1%3Fa%3D1&b=2" target="blank"/>', $this->generatorInput); $this->assertEquals( '<a href="https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=&amp;feira=terca&modelo=1%3Fa%3D1&b=2&rtm_source=demo-weekly-newsletter&rtm_medium=email&rtm_campaign=impresa_mail_20190903103350" target="blank"/>', $content ); } public function testPreserveTheParametersThatIsNotRtm() { $content = $this->rtmReplace->replace('<a href="https://expresso.pt/html/que-nao-entrou-em-acao?feira=terca&modelo=1&a=1&b=2" target="blank"/>', $this->generatorInput); $this->assertEquals( '<a href="https://expresso.pt/html/que-nao-entrou-em-acao?feira=terca&modelo=1&a=1&b=2&rtm_source=demo-weekly-newsletter&rtm_medium=email&rtm_campaign=impresa_mail_20190903103350&rtm_content=" target="blank"/>', $content ); } public function testPreserveAdditionalAnchorAttributes() { $content = $this->rtmReplace->replace('<a style="color: red" data-foo="bar" href="https://expresso.pt/" target="blank"/>', $this->generatorInput); $this->assertEquals( '<a style="color: red" data-foo="bar" href="https://expresso.pt/?rtm_source=demo-weekly-newsletter&rtm_medium=email&rtm_campaign=impresa_mail_20190903103350&rtm_content=" target="blank"/>', $content ); } public function testPreserveMailtoLinks() { $content = $this->rtmReplace->replace('<a href="mailto:admin@example.com"/>', $this->generatorInput); $this->assertEquals( '<a href="mailto:admin@example.com"/>', $content ); } public function testPreserveMailgunVariablesInUrl() { $url = $this->rtmReplace->replaceUrl('https://predplatne.dennikn.sk/email-settings', $this->generatorInput); $this->assertEquals('https://predplatne.dennikn.sk/email-settings?rtm_source=demo-weekly-newsletter&rtm_medium=email&rtm_campaign=impresa_mail_20190903103350&rtm_content=', $url); $url = $this->rtmReplace->replaceUrl('https://predplatne.dennikn.sk/email-settings?%recipient.autologin%', $this->generatorInput); $this->assertEquals('https://predplatne.dennikn.sk/email-settings?%recipient.autologin%&rtm_source=demo-weekly-newsletter&rtm_medium=email&rtm_campaign=impresa_mail_20190903103350&rtm_content=', $url); } public function testMultilineAnchorDefinition(): void { $content = $this->rtmReplace->replace( ' <a href="https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=apple&amp;feira=terca&modelo=1%3Fa%3D1&b=2" target="blank" style="color:#ffffff; display:inline-block;" />', $this->generatorInput ); $this->assertEquals( ' <a href="https://expresso.pt/html/que-nao-entrou-em-acao?rtm_content=&amp;feira=terca&modelo=1%3Fa%3D1&b=2&rtm_source=demo-weekly-newsletter&rtm_medium=email&rtm_campaign=impresa_mail_20190903103350" target="blank" style="color:#ffffff; display:inline-block;" />', $content ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Tests/Unit/Generator/GenericBestPerformingArticlesGeneratorTest.php
Mailer/extensions/mailer-module/src/Tests/Unit/Generator/GenericBestPerformingArticlesGeneratorTest.php
<?php declare(strict_types=1); namespace Tests\Unit\Generator; use PHPUnit\Framework\TestCase; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\Generators\GenericBestPerformingArticlesGenerator; use Remp\MailerModule\Models\PageMeta\Content\GenericPageContent; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Nette\Database\Table\Selection; class GenericBestPerformingArticlesGeneratorTest extends TestCase { private $sourceTemplateRepository; private $engineFactory; protected function setUp(): void { $htmlContent = <<<TEMPLATE <table> {% for url,item in items %} <tr> <td>{{ item.title }}</td> <td>{{ item.description }}</td> <td><img src="{{ item.image }}"></td> <td>{{ url }}</td> </tr> {% endfor %} </table> TEMPLATE; $textContent = <<<TEMPLATE {% for url,item in items %} {{ item.title }} {{ item.description }} {{ url}} {% endfor %} TEMPLATE; $mailSourceTemplate = [ "content_html" => $htmlContent, "content_text" => $textContent ]; $this->sourceTemplateRepository = $this->createConfiguredMock(SourceTemplatesRepository::class, [ 'find' => new ActiveRow( $mailSourceTemplate, $this->createMock(Selection::class) ) ]); $this->engineFactory = $GLOBALS['container']->getByType(EngineFactory::class); } public function testProcess() { $transport = new class() implements TransportInterface { public function getContent(string $url): ?string { return <<<HTML <!DOCTYPE html> <html lang="sk"> <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# video: http://ogp.me/ns/video#"> <meta charset="utf-8"> <meta property="og:title" content="here_is_title"> <meta property="og:description" content="here_is_description"> <meta property="og:something" content="THIS_META_WONT_BE_IN_EMAIL"> <meta property="og:url" content="https://www.tyzden.sk/nazory/48501/zachrani-vas-zachranka-bez-lekara/"> <meta name="author" content="Andrej Bán"> <meta property="og:image" content="https://page.com/someimage.jpg"> </head> <body> <header>header</header> <div>THIS_TEXT_WONT_BE_IN_EMAIL</div> <footer>footer</footer> </body></html> HTML; } }; $generator = new GenericBestPerformingArticlesGenerator( $this->sourceTemplateRepository, new GenericPageContent($transport), $this->engineFactory ); $testObj = []; $testObj['source_template_id'] = 1; $testObj['articles'] = "http://someurl.com"; $output = $generator->process($testObj); $htmlOutput = $output['htmlContent']; $textOutput = $output['textContent']; self::assertStringContainsString("here_is_title", $htmlOutput); self::assertStringContainsString("here_is_title", $textOutput); self::assertStringContainsString("here_is_description", $htmlOutput); self::assertStringContainsString("here_is_description", $textOutput); self::assertStringContainsString('https://page.com/someimage.jpg', $htmlOutput); self::assertStringNotContainsString('https://page.com/someimage.jpg', $textOutput); self::assertStringNotContainsString('THIS_TEXT_WONT_BE_IN_EMAIL', $htmlOutput); self::assertStringNotContainsString('THIS_TEXT_WONT_BE_IN_EMAIL', $textOutput); self::assertStringNotContainsString('THIS_META_WONT_BE_IN_EMAIL', $htmlOutput); self::assertStringNotContainsString('THIS_META_WONT_BE_IN_EMAIL', $textOutput); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/RedisClientTrait.php
Mailer/extensions/mailer-module/src/Models/RedisClientTrait.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; use Predis\Client; trait RedisClientTrait { protected RedisClientFactory $redisClientFactory; private Client $redis; private ?int $redisDatabase = null; private bool $redisUseKeysPrefix = false; public function setRedisDatabase($redisDatabase): void { $this->redisDatabase = $redisDatabase; } public function useRedisKeysPrefix(bool $usePrefix = true): void { $this->redisUseKeysPrefix = $usePrefix; } protected function redis(): Client { if (!isset($this->redisClientFactory) || !($this->redisClientFactory instanceof RedisClientFactory)) { throw new RedisClientTraitException('In order to use `RedisClientTrait`, you need to initialize `RedisClientFactory $redisClientFactory` in your service'); } if (!isset($this->redis)) { $this->redis = $this->redisClientFactory->getClient($this->redisDatabase, $this->redisUseKeysPrefix); } return $this->redis; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/DataRetentionTrait.php
Mailer/extensions/mailer-module/src/Models/DataRetentionTrait.php
<?php namespace Remp\MailerModule\Models; trait DataRetentionTrait { private string $retentionThreshold = '2 months'; private string $retentionRemovingField = 'created_at'; private bool $retentionForever = false; public function getRetentionRemovingField(): string { return $this->retentionRemovingField; } public function setRetentionThreshold(string $threshold): void { $this->retentionThreshold = $threshold; } public function setRetentionRemovingField(string $removingField): void { $this->retentionRemovingField = $removingField; } public function setRetentionForever(): void { $this->retentionForever = true; } public function getRetentionThreshold(): string { return $this->retentionThreshold; } public function removeData(): ?int { if ($this->retentionForever) { return null; } $batchLimit = 5000; $totalDeletedRows = 0; $threshold = (new \DateTime())->modify('-' . $this->retentionThreshold); do { $deletedRows = $this->getTable() ->where("{$this->getRetentionRemovingField()} < ?", $threshold) ->limit($batchLimit) ->delete(); $totalDeletedRows += $deletedRows; } while ($deletedRows === $batchLimit); return $totalDeletedRows; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/MailLayout.php
Mailer/extensions/mailer-module/src/Models/MailLayout.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; class MailLayout { private string $text; private string $html; public function __construct(string $text, string $html) { $this->text = $text; $this->html = $html; } public function getText(): string { return $this->text; } public function getHtml(): string { return $this->html; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/MailTemplate.php
Mailer/extensions/mailer-module/src/Models/MailTemplate.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; class MailTemplate { private string $from; private string $subject; private string $textBody; private string $htmlBody; public function __construct( string $from, string $subject, string $textBody, string $htmlBody ) { $this->from = $from; $this->subject = $subject; $this->textBody = $textBody; $this->htmlBody = $htmlBody; } public function getFrom(): string { return $this->from; } public function getSubject(): string { return $this->subject; } public function getTextBody(): string { return $this->textBody; } public function getHtmlBody(): string { return $this->htmlBody; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/DataRetentionInterface.php
Mailer/extensions/mailer-module/src/Models/DataRetentionInterface.php
<?php namespace Remp\MailerModule\Models; interface DataRetentionInterface { public function removeData(): ?int; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ChartTrait.php
Mailer/extensions/mailer-module/src/Models/ChartTrait.php
<?php namespace Remp\MailerModule\Models; trait ChartTrait { protected function getChartSuggestedMin($groupedData): ?int { $globalMax = PHP_INT_MIN; $globalMin = PHP_INT_MAX; foreach ($groupedData as $xData => $yDataArray) { if (($localMin = min($yDataArray)) < $globalMin) { $globalMin = $localMin; } if (($localMax = max($yDataArray)) > $globalMax) { $globalMax = $localMax; } } // If the difference between chart extremes is greater than 30%, the chart should be readable without // any further manipulation. if ($globalMin < $globalMax * 0.7) { return null; } $viewWindowMin = floor($globalMin * 0.90); return max($viewWindowMin, 0); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/RedisClientTraitException.php
Mailer/extensions/mailer-module/src/Models/RedisClientTraitException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; class RedisClientTraitException extends \Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/EnvironmentConfig.php
Mailer/extensions/mailer-module/src/Models/EnvironmentConfig.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; class EnvironmentConfig { public function get(string $key): ?string { if (!isset($_ENV[$key])) { return null; } $val = $_ENV[$key]; if ($val === false || $val === '') { return null; } return $val; } public function getInt(string $key): ?int { $val = $this->get($key); if ($val === null) { return $val; } return (int)$val; } public function getDsn(): string { $port = $this->get('DB_PORT'); if (!$port) { $port = 3306; } return $this->get('DB_ADAPTER') . ':host=' . $this->get('DB_HOST') . ';dbname=' . $this->get('DB_NAME') . ';port=' . $port; } public function getBool(string $key): ?bool { $value = $this->get($key); if ($value === null) { return null; } return filter_var($value, FILTER_VALIDATE_BOOLEAN); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/RouterFactory.php
Mailer/extensions/mailer-module/src/Models/RouterFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; use Nette; use Nette\Application\Routers\Route; use Nette\Application\Routers\RouteList; class RouterFactory { use Nette\StaticClass; public static function createRouter(): RouteList { $router = new RouteList; $router[] = new Route('/api/v<version>/<package>[/<apiAction>][/<params>]', 'Api:Api:default'); $router[] = new Route('<module>/<presenter>/<action>[/<id>]', [ 'module' => 'Mailer', 'presenter' => 'Dashboard', 'action' => 'default', 'id' => null, ]); return $router; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/MailTranslator.php
Mailer/extensions/mailer-module/src/Models/MailTranslator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; use Nette\Database\Table\ActiveRow; use Remp\MailerModule\Models\Config\LocalizationConfig; use Remp\MailerModule\Repositories\ActiveRowFactory; use Remp\MailerModule\Repositories\SnippetsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class MailTranslator { private TemplatesRepository $templatesRepository; private SnippetsRepository $snippetsRepository; private LocalizationConfig $localizationConfig; public function __construct( TemplatesRepository $templatesRepository, SnippetsRepository $snippetsRepository, LocalizationConfig $localizationConfig ) { $this->templatesRepository = $templatesRepository; $this->snippetsRepository = $snippetsRepository; $this->localizationConfig = $localizationConfig; } public function translateTemplate(ActiveRow $templateRow, string $locale = null): MailTemplate { if ($templateRow->getTable()->getName() === ActiveRowFactory::TABLE_NAME_DATAROW || !$this->localizationConfig->isTranslatable($locale)) { return new MailTemplate($templateRow->from, $templateRow->subject, $templateRow->mail_body_text, $templateRow->mail_body_html); } $templateRow = $this->templatesRepository->getByCode($templateRow->code); $translatedTemplate = $templateRow->related('mail_template_translations', 'mail_template_id') ->where('locale', $locale) ->fetch(); if ($translatedTemplate) { return new MailTemplate($translatedTemplate->from, $translatedTemplate->subject, $translatedTemplate->mail_body_text, $translatedTemplate->mail_body_html); } return new MailTemplate($templateRow->from, $templateRow->subject, $templateRow->mail_body_text, $templateRow->mail_body_html); } public function translateLayout(ActiveRow $layoutRow, string $locale = null): MailLayout { if (!$this->localizationConfig->isTranslatable($locale)) { return new MailLayout($layoutRow->layout_text, $layoutRow->layout_html); } $translatedLayout = $layoutRow->related('mail_layout_translations', 'mail_layout_id') ->where('locale', $locale) ->fetch(); if ($translatedLayout) { return new MailLayout($translatedLayout->layout_text, $translatedLayout->layout_html); } return new MailLayout($layoutRow->layout_text, $layoutRow->layout_html); } public function translateSnippets(array $snippetsToTranslate, string $locale = null): array { if (!$this->localizationConfig->isTranslatable($locale)) { return $snippetsToTranslate; } $snippets = $this->snippetsRepository->getTable() ->where('code IN (?)', array_keys($snippetsToTranslate)) ->fetchAll(); $result = []; foreach ($snippets as $snippet) { $translatedSnippet = $snippet->related('mail_snippet_translations', 'mail_snippet_id') ->where('locale', $locale) ->fetch(); $result[$snippet->code] = $translatedSnippet->html ?? $snippet->html; } return $result; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/PhinxRegistrator.php
Mailer/extensions/mailer-module/src/Models/PhinxRegistrator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; use Phinx\Config\Config; use Symfony\Component\Console\Application; use Phinx\Console\Command\Test; use Phinx\Console\Command\Status; use Phinx\Console\Command\Rollback; use Phinx\Console\Command\Migrate; use Phinx\Console\Command\Create; use Phinx\Console\Command\Init; class PhinxRegistrator { /** @var EnvironmentConfig */ private $environmentConfig; /** @var array Define phinx commands with aliases */ private $command = [ Init::class => 'migrate:init', Create::class => 'migrate:create', Migrate::class => 'migrate:migrate', Rollback::class => 'migrate:rollback', Status::class => 'migrate:status', Test::class => 'migrate:test' ]; private $appRootDir; /** * @param Application $application * @param EnvironmentConfig $environmentConfig * @param string|null $appRootDir */ public function __construct( Application $application, EnvironmentConfig $environmentConfig, string $appRootDir = null ) { if (is_null($appRootDir)) { // TODO: [refactoring] try to solve this with some ENV / config variable? or change appRootDir to required? // working with assumption callers will be in placed in default mailer-skeleton directories: // - <path-to-project>/bin/command.php // - <path-to-project>/app/bootstrap.php $appRootDir = realpath(dirname($_SERVER["SCRIPT_FILENAME"]) . '/../'); } $this->appRootDir = $appRootDir; $this->environmentConfig = $environmentConfig; $config = new Config($this->buildConfig(), __FILE__); foreach ($this->command as $class => $commandName) { $command = new $class; $command->setName($commandName); if (is_callable([$command, 'setConfig'])) { $command->setConfig($config); } $application->add($command); } } /** * Build phinx config from config.local.neon * @return array */ private function buildConfig(): array { $env = $_ENV['ENV']; $configData = [ 'feature_flags' => [ 'unsigned_primary_keys' => false, ], 'paths' => [ 'migrations' => [ $this->appRootDir . '/app/migrations', // currently the only extensions module $this->appRootDir . '/vendor/remp/mailer-module/src/migrations', ] ], 'environments' => [ 'default_migration_table' => 'phinxlog', 'default_environment' => $env, ], ]; $configData['environments'][$env] = [ 'adapter' => $this->environmentConfig->get('DB_ADAPTER'), 'host' => $this->environmentConfig->get('DB_HOST'), 'name' => $this->environmentConfig->get('DB_NAME'), 'user' => $this->environmentConfig->get('DB_USER'), 'pass' => $this->environmentConfig->get('DB_PASS'), 'port' => $this->environmentConfig->get('DB_PORT'), 'charset' => 'utf8' ]; return $configData; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/HealthChecker.php
Mailer/extensions/mailer-module/src/Models/HealthChecker.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; class HealthChecker { use RedisClientTrait; private const REDIS_KEY = 'mailer-healthcheck-'; public function __construct(RedisClientFactory $redisClientFactory) { $this->redisClientFactory = $redisClientFactory; } public function ping(string $processId, int $ttlSeconds = 300): bool { return (bool) $this->redis()->set( self::REDIS_KEY . $processId, '1', 'EX', // EX - Set the specified expire time, in seconds. $ttlSeconds ); } public function isHealthy(string $processId): bool { return $this->redis()->get(self::REDIS_KEY . $processId) !== null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/RedisClientFactory.php
Mailer/extensions/mailer-module/src/Models/RedisClientFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; use Predis\Client; class RedisClientFactory { private $host; private $port; private $password; private $database; private $keysPrefix; // replica-related parameters private $enableReplication = false; private $service; private $sentinels; public function __construct( string $host = '127.0.0.1', int $port = 6379, int $database = 0, ?string $password = null, ?string $keysPrefix = null ) { $this->host = $host; $this->port = $port; $this->database = $database; $this->password = $password; $this->keysPrefix = $keysPrefix; } public function configureSentinel($service, $sentinels) { $this->enableReplication = true; $this->service = $service; $this->sentinels = $sentinels; } public function getClient($database = null, $prefixRedisKeys = false): Client { $options = []; if ($prefixRedisKeys) { $options['prefix'] = $this->keysPrefix; } $options['parameters']['database'] = $database ?? $this->database; if ($this->password) { $options['parameters']['password'] = $this->password; } if ($this->enableReplication) { $options['replication'] = 'sentinel'; $options['service'] = $this->service; return new Client($this->sentinels, $options); } return new Client([ 'scheme' => 'tcp', 'host' => $this->host, 'port' => $this->port ], $options); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Sender.php
Mailer/extensions/mailer-module/src/Models/Sender.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models; use Nette\Database\Table\ActiveRow; use Nette\Mail\Message; use Nette\Utils\AssertionException; use Nette\Utils\Json; use Psr\Log\LoggerInterface; use Remp\MailerModule\Models\Auth\AutoLogin; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\Config\ConfigNotExistsException; use Remp\MailerModule\Models\ContentGenerator\ContentGenerator; use Remp\MailerModule\Models\ContentGenerator\GeneratorInputFactory; use Remp\MailerModule\Models\Mailer\EmailAllowList; use Remp\MailerModule\Models\Mailer\Mailer; use Remp\MailerModule\Models\Sender\MailerBatchException; use Remp\MailerModule\Models\Sender\MailerFactory; use Remp\MailerModule\Models\Sender\MailerNotExistsException; use Remp\MailerModule\Models\Sender\MailerRuntimeException; use Remp\MailerModule\Models\ServiceParams\ServiceParamsProviderInterface; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Tracy\Debugger; use Tracy\ILogger; class Sender { private array $recipients = []; private ActiveRow $template; private ?int $jobId = null; private ?int $batchId = null; private array $params = []; private array $attachments = []; private ?string $context = null; private ?string $locale = null; public function __construct( private MailerFactory $mailerFactory, private AutoLogin $autoLogin, private UserSubscriptionsRepository $userSubscriptionsRepository, private LogsRepository $logsRepository, private ContentGenerator $contentGenerator, private GeneratorInputFactory $generatorInputFactory, private ServiceParamsProviderInterface $serviceParamsProvider, private EmailAllowList $emailAllowList, private Config $config ) { } public function addRecipient(string $email, string $name = null, array $params = []): self { $this->recipients[] = [ 'email' => $email, 'name' => $name, 'params' => $params ]; return $this; } public function addAttachment(string $name, $content = null): self { $this->attachments[$name] = $content; return $this; } public function setTemplate(ActiveRow $template): self { $this->template = $template; return $this; } public function setJobId(int $jobId): self { $this->jobId = $jobId; return $this; } public function setBatchId(int $batchId): self { $this->batchId = $batchId; return $this; } public function setParams(array $params): self { $this->params = $params; return $this; } public function setContext(string $context): self { $this->context = $context; return $this; } public function setLocale(string $locale = null): self { $this->locale = $locale; return $this; } public function send(bool $checkEmailSubscribed = true): int { if (count($this->recipients) > 1) { throw new MailerBatchException(sprintf("attempted to send batch via send() method: please use single recipient: %s", Json::encode($this->recipients))); } $recipient = reset($this->recipients); $subscription = $this->userSubscriptionsRepository->getEmailSubscription($this->template->mail_type, $recipient['email']); if ($checkEmailSubscribed && (!$subscription || !$subscription->subscribed)) { return 0; } if (!$this->emailAllowList->isAllowed($recipient['email'])) { return 0; } $tokens = $this->autoLogin->createTokens([$recipient['email']]); $this->params['email'] = $recipient['email']; $this->params['autologin'] = "?token={$tokens[$recipient['email']]}"; $this->params = array_merge($this->params, $recipient['params'] ?? []); $serviceParams = $this->serviceParamsProvider->provide( $this->template, $recipient['email'], $this->batchId, $this->params['autologin'], ); $this->params = array_merge($this->params, $serviceParams); $mailer = $this->getMailer(); $message = new Message(); $message->addTo($recipient['email'], $recipient['name']); $generatorInput = $this->generatorInputFactory->create( $this->template, $this->params, $this->batchId, $this->locale ); $contentGeneratorContext = ['status' => 'sending']; $mailContent = $this->contentGenerator->render($generatorInput, $contentGeneratorContext); $message->setSubject($mailContent->subject()); $message->setFrom($mailContent->from()); if (!empty($mailContent->text())) { $message->setBody($mailContent->text()); } if (!empty($mailContent->html())) { $message->setHtmlBody($mailContent->html()); } $attachmentSize = $this->setMessageAttachments($message); $senderId = $this->getSenderId($recipient['email']); $this->setMessageHeaders($message, $senderId, [$recipient['email'] => $this->params]); if (isset($this->context)) { $alreadySent = $this->logsRepository->alreadySentContext($recipient['email'], $this->context); if ($alreadySent) { return 0; } } $this->logsRepository->add( $recipient['email'], $message->getSubject(), $this->template->id, $this->jobId, $this->batchId, $senderId, $attachmentSize, $this->context, $subscription->user_id ?? null ); try { $mailer->send($message); } catch (MailerRuntimeException $exception) { $this->logsRepository->getTable()->where([ 'mail_sender_id' => $senderId, 'email' => $recipient['email'], 'context' => $this->context, ])->delete(); throw new MailerRuntimeException($exception->getMessage()); } $this->reset(); return 1; } public function sendBatch(LoggerInterface $logger = null): int { $mailer = $this->getMailer(); if (!$mailer->supportsBatch()) { throw new MailerBatchException( sprintf('attempted to send batch via %s mailer: not supported', $mailer->getMailerAlias()) ); } $templateParams = []; $message = new Message(); $subscribedEmails = []; foreach ($this->recipients as $recipient) { $subscribedEmails[] = $recipient['email']; } if ($logger !== null) { $logger->info("Sender - sending batch {$this->batchId}", [ 'recipients_count' => count($subscribedEmails) ]); } $subscribedEmails = $this->userSubscriptionsRepository->filterSubscribedEmailsAndIds($subscribedEmails, $this->template->mail_type_id); if ($logger !== null) { $logger->info("Sender - subscribers filtering before sending {$this->batchId}", [ 'recipients_count_after_filtering' => count($subscribedEmails) ]); } $autologinTokens = $this->autoLogin->createTokens(array_keys($subscribedEmails)); $transformedParams = []; foreach ($this->recipients as $recipient) { if (!isset($subscribedEmails[$recipient['email']]) || !$subscribedEmails[$recipient['email']]) { continue; } if (!$this->emailAllowList->isAllowed($recipient['email'])) { continue; } try { $message->addTo($recipient['email'], $recipient['name']); } catch (AssertionException $e) { // we do nothing; it's invalid email and we want to skip it ASAP if ($logger !== null) { $logger->warning("Sender - invalid email for {$this->batchId}", [ 'error' => $e->getMessage(), 'email' => $recipient['email'], ]); } } $p = array_merge($this->params, $recipient['params'] ?? []); $p['mail_sender_id'] = $this->getSenderId($recipient['email']); $p['autologin'] = "?token={$autologinTokens[$recipient['email']]}"; $p['email'] = $recipient['email']; $serviceParams = $this->serviceParamsProvider->provide( $this->template, $recipient['email'], $this->batchId, $p['autologin'], ); $p = array_merge($p, $serviceParams); [$transformedParams, $p] = $mailer->transformTemplateParams($p); $templateParams[$recipient['email']] = $p; } if ($logger !== null) { $logger->info("Sender - template params transformed for {$this->batchId}", [ 'transformedParams' => $transformedParams ]); } $generatorInput = $this->generatorInputFactory->create( $this->template, $transformedParams, $this->batchId ); $contentGeneratorContext = ['status' => 'sending', 'sendingMode' => 'batch']; foreach ($templateParams as $email => $params) { $templateParams[$email] = $this->contentGenerator->getEmailParams( $generatorInput, $params, $contentGeneratorContext ); } if ($logger !== null) { $logger->info("Sender - email params generated for {$this->batchId}"); } $mailContent = $this->contentGenerator->render($generatorInput, $contentGeneratorContext); $message->setFrom($mailContent->from()); $message->setSubject($mailContent->subject()); if ($this->template->mail_body_text) { $message->setBody($mailContent->text()); } if ($logger !== null) { $logger->info("Sender - text content generated for {$this->batchId}"); } if ($this->template->mail_body_html) { $message->setHtmlBody($mailContent->html()); } if ($logger !== null) { $logger->info("Sender - html content generated for {$this->batchId}"); } $attachmentSize = $this->setMessageAttachments($message); $this->setMessageHeaders($message, '%recipient.mail_sender_id%', $templateParams, true); $insertLogsData = []; foreach ($templateParams as $email => $params) { $insertLogsData[] = $this->logsRepository->getInsertData( (string) $email, $this->template->subject, $this->template->id, $this->jobId, $this->batchId, $params['mail_sender_id'], $attachmentSize, $this->context, (int) $subscribedEmails[$email] ); } $logsTableName = $this->logsRepository->getTable()->getName(); $this->logsRepository->getDatabase()->query("INSERT INTO $logsTableName", $insertLogsData); if ($logger !== null) { $logger->info("Sender - mail logs stored for {$this->batchId}"); } try { $mailer->send($message); } catch (MailerRuntimeException $exception) { $deleteLogsData = array_map(function ($item) { return [$item['email'], $item['mail_sender_id']]; }, $insertLogsData); $this->logsRepository->getDatabase()->query("DELETE FROM $logsTableName WHERE (email, mail_sender_id) IN ?", $deleteLogsData); throw new MailerRuntimeException($exception->getMessage()); } $this->reset(); return count($subscribedEmails); } private function setMessageAttachments(Message $message): ?int { $attachmentSize = null; foreach ($this->attachments as $name => $content) { $message->addAttachment($name, $content); $attachmentSize += strlen($content); } return $attachmentSize; } private function setMessageHeaders(Message $message, $mailSenderId, ?array $templateParams, bool $isBatch = false): void { $enableOneClickUnsubscribing = $this->config->get('one_click_unsubscribe'); if (!$this->template->mail_type->locked) { if ($isBatch) { $message->setHeader('List-Unsubscribe', '%recipient.list_unsubscribe%'); if ($enableOneClickUnsubscribing) { $message->setHeader('List-Unsubscribe-Post', '%recipient.list_unsubscribe_post%'); } foreach ($templateParams as $email => $variables) { if (isset($variables['unsubscribe'])) { $templateParams[$email]['list_unsubscribe'] = "<{$variables['unsubscribe']}>"; if ($enableOneClickUnsubscribing) { $templateParams[$email]['list_unsubscribe_post'] = 'List-Unsubscribe=One-Click'; } } } } else { foreach ($templateParams as $email => $variables) { if (isset($variables['unsubscribe'])) { $message->setHeader('List-Unsubscribe', "<{$variables['unsubscribe']}>"); if ($enableOneClickUnsubscribing) { $message->setHeader('List-Unsubscribe-Post', 'List-Unsubscribe=One-Click'); } } } } } if ($this->locale !== null) { $message->setHeader('Content-Language', str_replace('_', '-', $this->locale)); } $message->setHeader('X-Mailer-Variables', Json::encode([ 'template' => $this->template->code, 'job_id' => $this->jobId, 'batch_id' => $this->batchId, 'mail_sender_id' => $mailSenderId, 'context' => $this->context, ])); $message->setHeader('X-Mailer-Tag', $this->template->code); $message->setHeader('X-Mailer-Template-Params', Json::encode($templateParams)); // intentional string type-case, integer would be ignored $message->setHeader('X-Mailer-Click-Tracking', (string) $this->template->click_tracking); } /** * @param null|string $alias - If $alias is null, default mailer is returned. * @return Mailer * @throws MailerNotExistsException * @throws ConfigNotExistsException */ public function getMailer($alias = null): Mailer { if ($alias === null && $this->template !== null) { return $this->getMailerByTemplate($this->template); } return $this->mailerFactory->getMailer($alias); } public function getMailerByTemplate($template) { $alias = $template->mail_type->mailer_alias; return $this->mailerFactory->getMailer($alias); } public function reset(): self { $this->recipients = []; unset($this->template); $this->jobId = null; $this->batchId = null; $this->params = []; $this->attachments = []; $this->context = null; $this->locale = null; return $this; } public function supportsBatch() { return $this->getMailer()->supportsBatch(); } private function getSenderId(string $email): string { $time = microtime(true); return hash("crc32c", $email . $time) . (int) $time; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/GeneratorInput.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/GeneratorInput.php
<?php namespace Remp\MailerModule\Models\ContentGenerator; use Nette\Database\Table\ActiveRow; use Nette\Utils\Json; use Remp\MailerModule\Repositories\SnippetsRepository; class GeneratorInput { public function __construct( private SnippetsRepository $snippetsRepository, private ActiveRow $mailTemplate, private array $params = [], private ?int $batchId = null, private ?string $locale = null ) { } public function template(): ActiveRow { return $this->mailTemplate; } public function layout(): ActiveRow { return $this->mailTemplate->mail_layout; } public function batchId(): ?int // what about returning 0? { return $this->batchId; } public function params(): array { $additionalParams = [ 'snippets' => $this->snippetsRepository ->getSnippetsForMailType($this->mailTemplate->mail_type_id)->fetchPairs('code', 'html'), 'snippets_text' => $this->snippetsRepository ->getSnippetsForMailType($this->mailTemplate->mail_type_id)->fetchPairs('code', 'text'), ]; if ($this->mailTemplate->params) { $additionalParams['template_params'] = Json::decode($this->mailTemplate->params, Json::FORCE_ARRAY); } return array_merge($this->params, $additionalParams); } public function locale(): ?string { return $this->locale; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/MailContent.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/MailContent.php
<?php namespace Remp\MailerModule\Models\ContentGenerator; class MailContent { private string $html; private string $text; private string $subject; private string $from; public function __construct(string $html, string $text, string $subject, string $from) { $this->html = $html; $this->text = $text; $this->subject = $subject; $this->from = $from; } public function html(): string { return $this->html; } public function text(): string { return $this->text; } public function subject(): string { return $this->subject; } public function from(): string { return $this->from; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/AllowedDomainManager.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/AllowedDomainManager.php
<?php namespace Remp\MailerModule\Models\ContentGenerator; use Nette\Utils\Strings; class AllowedDomainManager { private array $allowedDomains = []; public function addDomain(string $domain): void { $this->allowedDomains[] = $domain; } public function isAllowed(string $domain): bool { foreach ($this->allowedDomains as $allowedDomain) { if (Strings::endsWith($domain, $allowedDomain)) { return true; } } return false; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/GeneratorInputFactory.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/GeneratorInputFactory.php
<?php namespace Remp\MailerModule\Models\ContentGenerator; use Nette\Database\Table\ActiveRow; use Remp\MailerModule\Repositories\SnippetsRepository; class GeneratorInputFactory { private SnippetsRepository $snippetsRepository; public function __construct(SnippetsRepository $snippetsRepository) { $this->snippetsRepository = $snippetsRepository; } public function create( ActiveRow $mailTemplate, array $params = [], ?int $batchId = null, string $locale = null ): GeneratorInput { return new GeneratorInput( $this->snippetsRepository, $mailTemplate, $params, $batchId, $locale ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/ContentGenerator.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/ContentGenerator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\ContentGenerator; use Nette\Utils\DateTime; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\ContentGenerator\Replace\IReplace; use Remp\MailerModule\Models\MailTranslator; class ContentGenerator { /** @var IReplace[] */ private array $replaceList = []; public function __construct( private readonly EngineFactory $engineFactory, private readonly MailTranslator $mailTranslator, ) { } public function register(IReplace $replace): void { $this->replaceList[] = $replace; } public function render(GeneratorInput $generatorInput, array $context = null): MailContent { $params = $generatorInput->params(); $template = $this->mailTranslator->translateTemplate($generatorInput->template(), $generatorInput->locale()); $layout = $this->mailTranslator->translateLayout($generatorInput->layout(), $generatorInput->locale()); if (isset($params['snippets'])) { $params['snippets'] = $this->mailTranslator->translateSnippets($params['snippets'], $generatorInput->locale()); } $htmlBody = $this->generate($template->getHtmlBody(), $params); $html = $this->wrapLayout($template->getSubject(), $htmlBody, $layout->getHtml(), $params); // replace HTML snippets with their text versions if (isset($params['snippets']) && isset($params['snippets_text'])) { $params['snippets'] = $this->mailTranslator->translateSnippets($params['snippets_text'], $generatorInput->locale()); } $textBody = $this->generate($template->getTextBody(), $params); $text = $this->wrapLayout($template->getSubject(), $textBody, $layout->getText(), $params); $subject = $this->generate($template->getSubject(), $params); foreach ($this->replaceList as $replace) { $html = $replace->replace($html, $generatorInput, $context); $text = $replace->replace($text, $generatorInput, $context); } return new MailContent($html, $text, $subject, $template->getFrom()); } public function getEmailParams(GeneratorInput $generatorInput, array $emailParams, array $context = null): array { $outputParams = []; foreach ($emailParams as $name => $value) { if (!is_string($value)) { $outputParams[$name] = $value; continue; } foreach ($this->replaceList as $replace) { $value = $replace->replace($value, $generatorInput, $context); } $outputParams[$name] = $value; } return $outputParams; } private function generate(string $content, array $params): string { $params['time'] = new DateTime(); return $this->engineFactory->engine()->render($content, $params); } private function wrapLayout(string $subject, string $renderedTemplateContent, string $layoutContent, array $params): string { if (!$layoutContent) { return $renderedTemplateContent; } $layoutParams = [ 'title' => $subject, 'content' => $renderedTemplateContent, 'time' => new DateTime(), ]; $params = array_merge($layoutParams, $params); return $this->engineFactory->engine()->render($layoutContent, $params); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/TextUrlRtmReplace.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/TextUrlRtmReplace.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Replace; use Nette\Http\Url; use Nette\InvalidArgumentException; use Remp\MailerModule\Models\ContentGenerator\AllowedDomainManager; use Remp\MailerModule\Models\ContentGenerator\GeneratorInput; class TextUrlRtmReplace implements IReplace { use RtmReplaceTrait; private AllowedDomainManager $allowedDomainManager; public function __construct(AllowedDomainManager $allowedDomainManager) { $this->allowedDomainManager = $allowedDomainManager; } public function replace(string $content, GeneratorInput $generatorInput, array $context = null): string { if ($content !== strip_tags($content)) { // This replacer is intended to be used only for text emails. HTML is handled by AnchorRtmReplace. return $content; } $matches = []; preg_match_all('/(https?:\/\/.+?)(\s)/i', $content, $matches); if (count($matches) > 0) { foreach ($matches[1] as $idx => $hrefUrl) { // parse URL try { $url = new Url($hrefUrl); } catch (InvalidArgumentException $e) { continue; } // check if the host is whitelisted if (!$this->allowedDomainManager->isAllowed($url->getHost())) { continue; } $finalUrl = $this->replaceUrl($hrefUrl, $generatorInput) . $matches[2][$idx]; $content = str_replace($matches[0][$idx], $finalUrl, $content); } } return $content; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/RtmClickReplace.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/RtmClickReplace.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Replace; use Nette\Caching\Storage; use Nette\Database\Table\ActiveRow; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Repositories\MailTemplateLinksRepository; abstract class RtmClickReplace implements IReplace { public const HASH_PARAM = 'rtm_click'; public const CONFIG_NAME = 'mail_click_tracker'; public function __construct( protected MailTemplateLinksRepository $mailTemplateLinksRepository, protected Config $config, protected Storage $storage ) { } protected function isEnabled(ActiveRow $template): bool { return $this->config->get(self::CONFIG_NAME) && ($template->click_tracking === null || $template->click_tracking); } protected function computeUrlHash(string $url, string $additionalInfo = ''): string { return hash('crc32c', $url . $additionalInfo); } public function removeQueryParams(string $url): string { return explode('?', $url)[0]; } public function setRtmClickHashInUrl(string $url, string $hash): string { $url = self::removeRtmClickHash($url); $hashQueryParam = self::HASH_PARAM . '=' . $hash; // url already has query params if (isset(explode('?', $url)[1])) { return "{$url}&{$hashQueryParam}"; } return "{$url}?{$hashQueryParam}"; } public static function getRtmClickHashFromUrl(string $url): ?string { $matches = []; // Extracts RTM click hash value from URL query params preg_match('/^[^?]*\??.*[?&]' . self::HASH_PARAM . '=([^?&\s]*).*$/m', $url, $matches); return empty($matches[1]) ? null : $matches[1]; } public static function removeRtmClickHash(string $url): string { $matches = []; // Split URL between path and params (before and after '?') preg_match('/^([^?]*)\??(.*)$/', $url, $matches); $path = $matches[1]; $params = explode('&', $matches[2] ?? ''); $finalParams = []; foreach ($params as $param) { if (empty($param)) { continue; } $items = explode('=', $param, 2); if (strcasecmp($items[0], self::HASH_PARAM) === 0) { continue; } $finalParams[] = $param; } if (empty($finalParams)) { return $path; } return $path . '?' . implode('&', $finalParams); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/RtmReplaceTrait.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/RtmReplaceTrait.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\ContentGenerator\Replace; use Remp\MailerModule\Models\ContentGenerator\GeneratorInput; trait RtmReplaceTrait { /** * Put RTM parameters into URL parameters * Function also respects MailGun Variables (e.g. %recipient.autologin%) * * @param string $hrefUrl * * @param GeneratorInput $generatorInput * @return string */ public function replaceUrl(string $hrefUrl, GeneratorInput $generatorInput): string { $utmSource = $generatorInput->template()->mail_type->code; // !! could be maybe performance issue? $utmMedium = 'email'; $utmCampaign = $generatorInput->template()->code; $utmContent = $generatorInput->batchId(); $matches = []; // Split URL between path and params (before and after '?') preg_match('/^([^?]*)\??(.*)$/', $hrefUrl, $matches); $path = $matches[1]; $params = explode('&', $matches[2] ?? ''); $finalParams = []; $rtmSourceAdded = $rtmMediumAdded = $rtmCampaignAdded = $rtmContentAdded = false; foreach ($params as $param) { if (empty($param)) { continue; } $items = explode('=', $param, 2); if (isset($items[1])) { $key = $items[0]; $value = $items[1]; if (strcasecmp($key, 'rtm_source') === 0) { $finalParams[] = "$key={$utmSource}"; $rtmSourceAdded = true; } elseif (strcasecmp($key, 'rtm_medium') === 0) { $finalParams[] = "$key={$utmMedium}"; $rtmMediumAdded = true; } elseif (strcasecmp($key, 'rtm_campaign') === 0) { $finalParams[] = "$key={$utmCampaign}"; $rtmCampaignAdded = true; } elseif (strcasecmp($key, 'rtm_content') === 0) { $finalParams[] = "$key={$utmContent}"; $rtmContentAdded = true; } else { $finalParams[] = "$key=" . $value; } } else { $finalParams[] = $param; } } if (!$rtmSourceAdded) { $finalParams[] = "rtm_source={$utmSource}"; } if (!$rtmMediumAdded) { $finalParams[] = "rtm_medium={$utmMedium}"; } if (!$rtmCampaignAdded) { $finalParams[] = "rtm_campaign={$utmCampaign}"; } if (!$rtmContentAdded) { $finalParams[] = "rtm_content={$utmContent}"; } return $path . '?' . implode('&', $finalParams); } public function replace(string $content, GeneratorInput $generatorInput, array $context = null): string { $matches = []; preg_match_all('/<a(.*?)href="([^"]*?)"(.*?)>/i', $content, $matches); if (count($matches) > 0) { foreach ($matches[2] as $idx => $hrefUrl) { if (strpos($hrefUrl, 'http') === false) { continue; } $href = sprintf( '<a%shref="%s"%s>', $matches[1][$idx], $this->replaceUrl($hrefUrl, $generatorInput), $matches[3][$idx], ); $content = str_replace($matches[0][$idx], $href, $content); } } return $content; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/AnchorRtmReplace.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/AnchorRtmReplace.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Replace; use Nette\Http\Url; use Nette\InvalidArgumentException; use Remp\MailerModule\Models\ContentGenerator\AllowedDomainManager; use Remp\MailerModule\Models\ContentGenerator\GeneratorInput; class AnchorRtmReplace implements IReplace { use RtmReplaceTrait; private AllowedDomainManager $allowedDomainManager; public function __construct(AllowedDomainManager $allowedDomainManager) { $this->allowedDomainManager = $allowedDomainManager; } public function replace(string $content, GeneratorInput $generatorInput, array $context = null): string { $matches = []; preg_match_all('/<a(.*?)href="([^"]*?)"(.*?)>/is', $content, $matches); if (count($matches) > 0) { foreach ($matches[2] as $idx => $hrefUrl) { // parse URL try { $url = new Url($hrefUrl); } catch (InvalidArgumentException $e) { continue; } // check if the host is whitelisted if (!$this->allowedDomainManager->isAllowed($url->getHost())) { continue; } $href = sprintf('<a%shref="%s"%s>', $matches[1][$idx], $this->replaceUrl($hrefUrl, $generatorInput), $matches[3][$idx]); $content = str_replace($matches[0][$idx], $href, $content); } } return $content; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/UrlRtmClickReplace.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/UrlRtmClickReplace.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Replace; use Remp\MailerModule\Models\ContentGenerator\GeneratorInput; class UrlRtmClickReplace extends RtmClickReplace { public function replace(string $content, GeneratorInput $generatorInput, array $context = null): string { $template = $generatorInput->template(); if (!$this->isEnabled($template)) { return $content; } // fast check to avoid unnecessary parsing if (!str_starts_with($content, 'http')) { return $content; } $urlEmptyParams = $this->removeQueryParams($content); $hash = $this->computeUrlHash($urlEmptyParams, $template->code); $finalUrl = $this->setRtmClickHashInUrl($content, $hash); if (isset($context['status']) && $context['status'] === 'sending') { $this->mailTemplateLinksRepository->upsert($template->id, $urlEmptyParams, $hash); } return $finalUrl; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/IReplace.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/IReplace.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Replace; use Remp\MailerModule\Models\ContentGenerator\GeneratorInput; interface IReplace { /** * @param string $content * @param GeneratorInput $generatorInput * @param array|null $context random array with additional information for replacers * @return string */ public function replace(string $content, GeneratorInput $generatorInput, array $context = null): string; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/UrlRtmReplace.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/UrlRtmReplace.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Replace; use Nette\Http\Url; use Nette\InvalidArgumentException; use Remp\MailerModule\Models\ContentGenerator\AllowedDomainManager; use Remp\MailerModule\Models\ContentGenerator\GeneratorInput; /** * UrlRtmReplace replaces (adds) RTM (REMP UTM) parameters if content contains only URL and nothing else. * This is handy if you need to work with RTM parameters in your email params and not just the content itself. */ class UrlRtmReplace implements IReplace { use RtmReplaceTrait; private AllowedDomainManager $allowedDomainManager; public function __construct(AllowedDomainManager $allowedDomainManager) { $this->allowedDomainManager = $allowedDomainManager; } public function replace(string $content, GeneratorInput $generatorInput, array $context = null): string { // fast check to avoid unnecessary parsing if (strpos($content, 'http') !== 0) { return $content; } // parse URL try { $url = new Url($content); } catch (InvalidArgumentException $e) { return $content; } // check if the host is whitelisted if (!$this->allowedDomainManager->isAllowed($url->getHost())) { return $content; } return $this->replaceUrl($content, $generatorInput); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/AnchorRtmClickReplace.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Replace/AnchorRtmClickReplace.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Replace; use Nette\Caching\Cache; use Remp\MailerModule\Models\ContentGenerator\GeneratorInput; class AnchorRtmClickReplace extends RtmClickReplace { public function replace(string $content, GeneratorInput $generatorInput, array $context = null): string { $template = $generatorInput->template(); if (!$this->isEnabled($template)) { return $content; } // check if HTML if ($content === strip_tags($content)) { return $content; } if (isset($context['sendingMode']) && $context['sendingMode'] === 'batch') { [$mailContent, $urls] = $this->hashLinkWithCache($content, $template); } else { [$mailContent, $urls] = $this->hashLinks($content, $template->code); } if (isset($context['status']) && $context['status'] === 'sending') { foreach ($urls as $hash => $url) { $this->mailTemplateLinksRepository->upsert($template->id, $url, $hash); } } return $mailContent; } private function hashLinkWithCache($mailContent, $template): array { $cacheKey = 'rtmclick_anchor_' . $template->code . '_' . (isset($template->updated_at) ? $template->updated_at->format('U') : time()); [$hashedContent, $urls] = $this->storage->read($cacheKey); if (isset($hashedContent, $urls)) { return [$hashedContent, $urls]; } [$hashedContent, $urls] = $this->hashLinks($mailContent, $template->code); $this->storage->write($cacheKey, [$hashedContent, $urls], [Cache::Expire => 60]); return [$hashedContent, $urls]; } private function hashLinks(string $mailContent, string $templateCode): array { $matches = []; $links = []; $matched = preg_match_all('/<a(\s[^>]*)href\s*=\s*([\"\']??)(http[^\"\'>]*?)\2([^>]*)>/iU', $mailContent, $matches); if (!$matched) { return [$mailContent, $links]; } foreach ($matches[3] as $idx => $hrefUrl) { $urlEmptyParams = $this->removeQueryParams($hrefUrl); $hash = $this->computeUrlHash($urlEmptyParams, $idx . $templateCode); $finalUrl = $this->setRtmClickHashInUrl($hrefUrl, $hash); $links[$hash] = $urlEmptyParams; $href = sprintf('<a%shref="%s"%s>', $matches[1][$idx], $finalUrl, $matches[4][$idx]); $mailContent = preg_replace('/' . preg_quote($matches[0][$idx], '/') . '/i', $href, $mailContent, 1); } return [$mailContent, $links]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Engine/IEngine.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Engine/IEngine.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Engine; interface IEngine { public function render(string $content, array $params = []): string; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Engine/EngineFactory.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Engine/EngineFactory.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Engine; use Exception; final class EngineFactory { /** @var string */ private $default; private $engines = []; public function register(string $key, IEngine $engine): void { $this->engines[$key] = $engine; } public function engine(?string $key = null): IEngine { if ($key !== null) { if (!isset($this->engines[$key])) { throw new Exception("Cannot find template engine '{$key}'"); } return $this->engines[$key]; } if ($this->default) { return $this->engines[$this->default]; } throw new Exception("Unable to provide engine. No specific engine was requested and no default was configured."); } public function defaultEngine(string $type): void { if (!isset($this->engines[$type])) { throw new Exception("Unknown template engine '{$type}'"); } $this->default = $type; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ContentGenerator/Engine/TwigEngine.php
Mailer/extensions/mailer-module/src/Models/ContentGenerator/Engine/TwigEngine.php
<?php namespace Remp\MailerModule\Models\ContentGenerator\Engine; use Twig\Environment; use Twig\Extra\Intl\IntlExtension; use Twig\Loader\ArrayLoader; class TwigEngine implements IEngine { public function render(string $content, array $params = []): string { $templates = $params['snippets'] ?? []; $templates['index.html'] = $content; $loader = new ArrayLoader($templates); $twig = new Environment($loader); $twig->addExtension(new IntlExtension()); return $twig->render('index.html', $params); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Sso/SsoExpiredException.php
Mailer/extensions/mailer-module/src/Models/Sso/SsoExpiredException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Sso; class SsoExpiredException extends \Exception { public $redirect; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Sso/Client.php
Mailer/extensions/mailer-module/src/Models/Sso/Client.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Sso; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Exception\ClientException; use Nette\Http\IRequest; use Nette\Utils\Json; class Client { const ENDPOINT_INTROSPECT = 'api/auth/introspect'; const ENDPOINT_REFRESH = 'api/auth/refresh'; const ENDPOINT_CHECK_TOKEN = 'api/auth/check-token'; private $request; private $client; public function __construct($ssoAddr, IRequest $request) { $this->client = new GuzzleClient([ 'base_uri' => $ssoAddr, ]); $this->request = $request; } /** * introspect attempts to obtain user data based on the provided SSO $token. */ public function introspect(?string $token): array { try { $response = $this->client->request('GET', self::ENDPOINT_INTROSPECT, [ 'headers' => [ 'Authorization' => 'Bearer '.$token, ] ]); } catch (ClientException $e) { $response = $e->getResponse(); $contents = $response->getBody()->getContents(); $body = Json::decode($contents); switch ($response->getStatusCode()) { case 400: case 401: $e = new SsoExpiredException(); $e->redirect = $body->redirect; throw $e; default: throw new \Nette\Security\AuthenticationException($contents); } } $user = Json::decode($response->getBody()->getContents(), Json::FORCE_ARRAY); return $user; } /** * Return true if token is valid, otherwise return false */ public function validToken(string $token): bool { try { $response = $this->client->request('GET', self::ENDPOINT_CHECK_TOKEN, [ 'headers' => [ 'Authorization' => 'Bearer '.$token, ] ]); } catch (ClientException $e) { $response = $e->getResponse(); $contents = $response->getBody()->getContents(); if ($response->getStatusCode() === 404) { return false; } throw new SsoException($contents); } return $response->getStatusCode() === 200; } public function refresh(string $token): array { try { $response = $this->client->request('POST', self::ENDPOINT_REFRESH, [ 'headers' => [ 'Authorization' => 'Bearer '.$token, ] ]); } catch (ClientException $e) { $response = $e->getResponse(); $contents = $response->getBody()->getContents(); $body = Json::decode($contents); switch ($response->getStatusCode()) { case 400: case 401: $e = new SsoExpiredException(); $e->redirect = $body->redirect; throw $e; default: throw new \Nette\Security\AuthenticationException($contents); } } $tokenResponse = Json::decode($response->getBody()->getContents(), Json::FORCE_ARRAY); return $tokenResponse; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Sso/Authenticator.php
Mailer/extensions/mailer-module/src/Models/Sso/Authenticator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Sso; use Nette\Http\Url; use Nette\Http\IRequest; use Nette\Http\IResponse; use Nette\Security\IIdentity; use Nette\Security\Identity; class Authenticator implements \Nette\Security\Authenticator { private $client; private $request; private $response; private $errorUrl; public function __construct($errorUrl, Client $client, IRequest $request, IResponse $response) { $this->client = $client; $this->request = $request; $this->response = $response; $this->errorUrl = $errorUrl; } /** * @param string $user * @param string $password * * @return IIdentity * @throws \Nette\Security\AuthenticationException */ public function authenticate(string $user, string $password): IIdentity { $token = $this->request->getQuery('token'); try { $result = $this->client->introspect($token); } catch (SsoExpiredException $e) { $redirectUrl = new Url($e->redirect); $redirectUrl->setQueryParameter('successUrl', $this->request->getUrl()->getAbsoluteUrl()); $redirectUrl->setQueryParameter('errorUrl', $this->errorUrl); $this->response->redirect($redirectUrl->getAbsoluteUrl()); exit; } return new Identity( $result['id'], $result['scopes'], [ 'email' => $result['email'], 'name' => $result['name'], 'token' => $token, ] ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Sso/SsoException.php
Mailer/extensions/mailer-module/src/Models/Sso/SsoException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Sso; class SsoException extends \Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Users/UserException.php
Mailer/extensions/mailer-module/src/Models/Users/UserException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Users; use Exception; class UserException extends Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Users/IUser.php
Mailer/extensions/mailer-module/src/Models/Users/IUser.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Users; interface IUser { /** * List provides list of information about users. * * @param array $userIds List of userIDs to check. Empty array means all users. * @param int $page Page to obtain. Numbering starts with 1. * @return array */ public function list(array $userIds, int $page, bool $includeDeactivated = false): array; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Users/UserManager.php
Mailer/extensions/mailer-module/src/Models/Users/UserManager.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Users; use League\Event\EventDispatcher; use Nette\Database\Explorer; use Remp\MailerModule\Events\BeforeUserEmailChangeEvent; use Remp\MailerModule\Events\BeforeUsersDeleteEvent; use Remp\MailerModule\Events\UserEmailChangedEvent; use Remp\MailerModule\Events\UsersDeletedEvent; use Remp\MailerModule\Repositories\AutoLoginTokensRepository; use Remp\MailerModule\Repositories\JobQueueRepository; use Remp\MailerModule\Repositories\LogConversionsRepository; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; class UserManager { public function __construct( private Explorer $database, private AutoLoginTokensRepository $autoLoginTokensRepository, private JobQueueRepository $jobQueueRepository, private LogConversionsRepository $logConversionsRepository, private LogsRepository $logsRepository, private UserSubscriptionsRepository $userSubscriptionsRepository, private EventDispatcher $eventDispatcher, ) { } public function changeEmail(string $originalEmail, string $newEmail): bool { $this->eventDispatcher->dispatch(new BeforeUserEmailChangeEvent($originalEmail, $newEmail)); $subscriptions = $this->userSubscriptionsRepository->findByEmail($originalEmail); if (!count($subscriptions)) { return false; } foreach ($subscriptions as $subscription) { $this->userSubscriptionsRepository->update($subscription, ['user_email' => $newEmail]); } $this->eventDispatcher->dispatch(new UserEmailChangedEvent($originalEmail, $newEmail)); return true; } /** * @param array<string> $emails * @throws \Exception */ public function deleteUsers(array $emails): bool { foreach ($emails as $email) { if (strlen(trim($email)) === 0) { throw new \Exception('Email cannot be empty string.'); } } $this->database->beginTransaction(); try { $this->eventDispatcher->dispatch(new BeforeUsersDeleteEvent($emails)); $deletedAutologinTokens = $this->autoLoginTokensRepository->deleteAllForEmails($emails); $deletedJobQueues = $this->jobQueueRepository->deleteAllByEmails($emails); // log conversions are internal marker; doesn't contain user data but has to be removed before mail logs $mailLogIds = $this->logsRepository->allForEmails($emails)->fetchPairs(null, 'id'); $this->logConversionsRepository->deleteForMailLogs($mailLogIds); $deletedMailLogs = $this->logsRepository->deleteAllForEmails($emails); $deletedUserSubscriptions = $this->userSubscriptionsRepository->deleteAllForEmails($emails); $this->database->commit(); } catch (\Exception $e) { $this->database->rollBack(); throw $e; } $this->eventDispatcher->dispatch(new UsersDeletedEvent($emails)); // nothing was removed if ($deletedAutologinTokens === 0 && $deletedJobQueues === 0 && $deletedMailLogs === 0 && $deletedUserSubscriptions === 0) { return false; } return true; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Users/Dummy.php
Mailer/extensions/mailer-module/src/Models/Users/Dummy.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Users; class Dummy implements IUser { public function list(array $userIds, int $page, bool $includeDeactivated = false): array { if ($page > 1) { return []; } $users = [ 1 => ['id' => 1, 'email' => 'foo@example.com'], 2 => ['id' => 2, 'email' => 'bar@example.com'], ]; if ($includeDeactivated) { $users[3] = ['id' => 3, 'email' => 'deactivated@example.com']; } return $users; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Users/Crm.php
Mailer/extensions/mailer-module/src/Models/Users/Crm.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Users; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Psr7\StreamWrapper; use JsonMachine\Items; use Nette\Utils\Json; use Tracy\Debugger; class Crm implements IUser { const ENDPOINT_LIST = 'api/v1/users/list'; private $client; public function __construct(string $baseUrl, string $token) { $this->client = new Client([ 'base_uri' => $baseUrl, 'headers' => [ 'Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/x-www-form-urlencoded', ] ]); } public function list(array $userIds, int $page, bool $includeDeactivated = false): array { try { $response = $this->client->post(self::ENDPOINT_LIST, [ 'form_params' => [ 'user_ids' => Json::encode($userIds), 'page' => $page, 'include_deactivated' => $includeDeactivated, ], ]); $stream = StreamWrapper::getResource($response->getBody()); try { $users = []; foreach (Items::fromStream($stream, ['pointer' => '/users']) as $user) { $users[$user->id] = [ 'id' => $user->id, 'email' => $user->email, ]; } } finally { fclose($stream); } } catch (ConnectException $e) { throw new UserException("could not connect CRM user base: {$e->getMessage()}"); } catch (ClientException $e) { Debugger::log("unable to get list of CRM users: " . $e->getResponse()->getBody()->getContents(), Debugger::WARNING); return []; } return $users; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/ProcessException.php
Mailer/extensions/mailer-module/src/Models/Generators/ProcessException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Exception; class ProcessException extends Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/PreprocessException.php
Mailer/extensions/mailer-module/src/Models/Generators/PreprocessException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Exception; class PreprocessException extends Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/ShopUrlParserGenerator.php
Mailer/extensions/mailer-module/src/Models/Generators/ShopUrlParserGenerator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Nette\Application\UI\Form; use Nette\Utils\ArrayHash; use Remp\Mailer\Components\GeneratorWidgets\Widgets\ArticleUrlParserWidget\ArticleUrlParserWidget; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; use Remp\MailerModule\Models\PageMeta\Content\ShopContentInterface; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Tomaj\NetteApi\Params\PostInputParam; class ShopUrlParserGenerator implements IGenerator { protected $sourceTemplatesRepository; protected $shopContent; public $onSubmit; private $engineFactory; public function __construct( SourceTemplatesRepository $sourceTemplatesRepository, ShopContentInterface $shopContent, EngineFactory $engineFactory ) { $this->sourceTemplatesRepository = $sourceTemplatesRepository; $this->shopContent = $shopContent; $this->engineFactory = $engineFactory; } public function generateForm(Form $form): void { $form->addTextArea('intro', 'Intro text') ->setHtmlAttribute('rows', 4) ->getControlPrototype() ->setHtmlAttribute('class', 'form-control html-editor'); $form->addTextArea('products', 'Product') ->setHtmlAttribute('rows', 7) ->setOption('description', 'Paste products URLs (books and e-books). Each on separate line.') ->setRequired(true) ->getControlPrototype() ->setHtmlAttribute('class', 'form-control html-editor'); $form->addTextArea('footer', 'Footer text') ->setHtmlAttribute('rows', 6) ->getControlPrototype() ->setHtmlAttribute('class', 'form-control html-editor'); $form->onSuccess[] = [$this, 'formSucceeded']; } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } public function formSucceeded(Form $form, ArrayHash $values): void { try { $output = $this->process((array)$values); $this->onSubmit->__invoke($output['htmlContent'], $output['textContent']); } catch (InvalidUrlException $e) { $form->addError($e->getMessage()); } } public function apiParams(): array { return [ (new PostInputParam('products'))->setRequired(), (new PostInputParam('footer'))->setRequired(), (new PostInputParam('intro'))->setRequired(), ]; } public function process(array $values): array { $sourceTemplate = $this->sourceTemplatesRepository->find($values['source_template_id']); $items = []; $errors = []; $urls = explode("\n", trim($values['products'])); foreach ($urls as $url) { $url = trim($url); if (empty($url)) { // people sometimes enter blank lines continue; } try { $meta = $this->shopContent->fetchUrlMeta($url); if ($meta) { $items[$url] = $meta; } else { $errors[] = $url; } } catch (InvalidUrlException $e) { $errors[] = $url; } } $params = [ 'intro' => $values['intro'], 'footer' => $values['footer'], 'items' => $items, ]; $engine = $this->engineFactory->engine(); return [ 'htmlContent' => $engine->render($sourceTemplate->content_html, $params), 'textContent' => strip_tags($engine->render($sourceTemplate->content_text, $params)), 'errors' => $errors, ]; } public function getWidgets(): array { return [ArticleUrlParserWidget::class]; } public function preprocessParameters($data): ?ArrayHash { return null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/InvalidUrlException.php
Mailer/extensions/mailer-module/src/Models/Generators/InvalidUrlException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; class InvalidUrlException extends \Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/ArticleLockerInterface.php
Mailer/extensions/mailer-module/src/Models/Generators/ArticleLockerInterface.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; interface ArticleLockerInterface { /** * getLockedPost determines where the content of post should be cut of and returns trimmed version of the post. */ public function getLockedPost(string $post): string; /** * injectLockedMessage adds a "lock" message to the determined place in the $post - e.g. at the end, or by replacing * existing placeholder within the $post content. */ public function injectLockedMessage(string $post): string; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/EmptyGenerator.php
Mailer/extensions/mailer-module/src/Models/Generators/EmptyGenerator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Nette\Application\UI\Form; use Nette\Utils\ArrayHash; class EmptyGenerator implements IGenerator { public $onSubmit; public function generateForm(Form $form): void { $form->onSuccess[] = [$this, 'formSucceeded']; } public function formSucceeded(Form $form, ArrayHash $values): void { } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } public function getWidgets(): array { return []; } public function apiParams(): array { return []; } public function process(array $input): array { return []; } public function preprocessParameters($data): ?ArrayHash { return null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/EmbedParser.php
Mailer/extensions/mailer-module/src/Models/Generators/EmbedParser.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Embed\Embed; use Embed\Http\Crawler; use Embed\Http\CurlClient; use Tracy\Debugger; class EmbedParser { protected ?string $videoLinkText; protected array $curlSettings = []; public function setVideoLinkText(?string $videoLinkText = null): void { $this->videoLinkText = $videoLinkText; } public function setCurlSettings(array $settings) { $this->curlSettings = $settings; } private function fetch(string $url): ?array { $curlSettings = [ // Twitter may generate infinite redirect (2024/03), // fix according to https://github.com/oscarotero/Embed/issues/520#issue-1782756560 'follow_location' => !$this->isTwitterLink($url), ...$this->curlSettings, ]; $curlClient = new CurlClient(); $curlClient->setSettings($curlSettings); $embed = new Embed(new Crawler($curlClient)); $embed = $embed->get($url); $oEmbed = $embed->getOEmbed(); $type = $oEmbed->get('type'); $image = null; if ($embed->image) { $image = $embed->image->__toString(); } return ($embed->url === null) ? null : [ 'link' => $embed->url->__toString(), 'title' => $embed->title ?? '', 'image' => $image, 'isVideo' => $type === 'video', ]; } private function isTwitterLink($link) { return str_contains($link, 'twitt') || str_contains($link, 'x.com'); } public function parse(string $link): ?string { $link = trim($link); if (preg_match('/^(?:(?:https?:)?\/\/)?(?:www\.)?facebook\.com\/[a-zA-Z0-9.]+\/videos\/(?:[a-zA-Z0-9.]+\/)?([0-9]+)/', $link) || str_contains($link, 'youtu') || $this->isTwitterLink($link) ) { try { if ($data = $this->fetch($link)) { return $this->createEmbedMarkup($data['link'], $data['title'], $data['image'], $data['isVideo']); } } catch (\Embed\Http\NetworkException $exception) { Debugger::log("Network error while retrieving embedded link [$link], reason: " . $exception->getMessage(), Debugger::EXCEPTION); return $this->createEmbedMarkup($link); } } return null; } public function createEmbedMarkup(string $link, ?string $title = null, ?string $image = null, bool $isVideo = false): string { $html = "<br>"; if ($isVideo && isset($this->videoLinkText)) { $html .= "<p style='text-align: center; font-weight: normal;'><i>{$this->videoLinkText}</i></p><br>"; } $html .= "<a href='{$link}' target='_blank' style='color:#181818;padding:0;margin:0;line-height:1.3;text-decoration:none;text-align: center; display: block;'>"; if (!is_null($image) && !is_null($title)) { $html .= "<img src='{$image}' alt='{$title}' style='outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:auto;max-width:100%;clear:both;display:inline;' width='660'>"; } else { $html .= "<span style='text-decoration: underline; color: #1F3F83;'>" . $link . "</span>"; } return $html . "</a>" . PHP_EOL; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/IGenerator.php
Mailer/extensions/mailer-module/src/Models/Generators/IGenerator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Nette\Application\UI\Form; use Nette\Utils\ArrayHash; use Tomaj\NetteApi\Params\InputParam; interface IGenerator { /** * generates additional form elements based on the Generator type. If generator adds custom submit element, * it should return array of tabs in format [linkToTab => label]. * * @param Form $form */ public function generateForm(Form $form): void; /** * @param callable $onSubmit * @return void */ public function onSubmit(callable $onSubmit): void; /** * Return widget classes * @return string[] */ public function getWidgets(): array; /** * Returns available parameters that generator needs * * @return InputParam[] */ public function apiParams(): array; /** * Generates output data from input values object * Used by both Form POST and API call * * @param array $values * @return array */ public function process(array $values): array; /** * Generates parameters for generator from arbitrary object (e.g. WP article dump) * Each generator can define its own rules * * @param \stdClass $data * @return ?ArrayHash */ public function preprocessParameters($data): ?ArrayHash; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/ArticleUrlParserGenerator.php
Mailer/extensions/mailer-module/src/Models/Generators/ArticleUrlParserGenerator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Nette\Application\UI\Form; use Nette\Http\Url; use Nette\Utils\ArrayHash; use Remp\Mailer\Components\GeneratorWidgets\Widgets\ArticleUrlParserWidget\ArticleUrlParserWidget; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Tomaj\NetteApi\Params\PostInputParam; class ArticleUrlParserGenerator implements IGenerator { public $onSubmit; private array $contentProcessors = []; public function __construct( protected SourceTemplatesRepository $sourceTemplatesRepository, protected ContentInterface $content, protected readonly EngineFactory $engineFactory, ) { } public function setContentProcessor(string $domain, $contentProcessor) { $this->contentProcessors[$domain] = $contentProcessor; } public function generateForm(Form $form): void { $form->addTextArea('intro', 'Intro text') ->setHtmlAttribute('rows', 4) ->setHtmlAttribute('class', 'form-control wysiwyg-editor') ->getControlPrototype(); $form->addTextArea('articles', 'Articles') ->setHtmlAttribute('rows', 7) ->setHtmlAttribute('class', 'form-control') ->setOption('description', 'Paste article URLs. Each on separate line.') ->setRequired(true) ->getControlPrototype(); $form->addTextArea('external_intro', 'External intro text') ->setHtmlAttribute('rows', 4) ->setHtmlAttribute('class', 'form-control wysiwyg-editor') ->getControlPrototype(); $form->addTextArea('external_articles', 'External articles') ->setHtmlAttribute('rows', 7) ->setHtmlAttribute('class', 'form-control') ->setOption('description', 'Paste article URLs from external website supported by the generator. Each on separate line.') ->getControlPrototype(); $form->addTextArea('footer', 'Footer text') ->setHtmlAttribute('rows', 6) ->setHtmlAttribute('class', 'form-control wysiwyg-editor') ->getControlPrototype(); $form->onSuccess[] = [$this, 'formSucceeded']; } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } public function formSucceeded(Form $form, ArrayHash $values): void { try { $output = $this->process((array)$values); $addonParams = [ 'render' => true, 'errors' => $output['errors'], ]; $this->onSubmit->__invoke($output['htmlContent'], $output['textContent'], $addonParams); } catch (InvalidUrlException $e) { $form->addError($e->getMessage()); } } public function apiParams(): array { return [ (new PostInputParam('articles'))->setRequired(), (new PostInputParam('footer'))->setRequired(), (new PostInputParam('utm_campaign'))->setRequired(), (new PostInputParam('intro'))->setRequired(), (new PostInputParam('external_intro')), (new PostInputParam('external_articles')), ]; } public function process(array $values): array { $sourceTemplate = $this->sourceTemplatesRepository->find($values['source_template_id']); if (!$sourceTemplate) { throw new \RuntimeException("Unable to find source template with ID [{$values['source_template_id']}]"); } $errors = []; $urls = explode("\n", trim($values['articles'])); $items = $this->readArticlesMetadata($urls, $errors); $externalUrls = explode("\n", trim($values['external_articles'])); $externalItems = $this->readArticlesMetadata($externalUrls, $errors); $params = [ 'intro' => $values['intro'], 'external_intro' => $values['external_intro'], 'footer' => $values['footer'], 'items' => $items, 'external_items' => $externalItems, ]; $engine = $this->engineFactory->engine(); return [ 'htmlContent' => $engine->render($sourceTemplate->content_html, $params), 'textContent' => strip_tags($engine->render($sourceTemplate->content_text, $params)), 'errors' => $errors, ]; } public function getWidgets(): array { return [ArticleUrlParserWidget::class]; } public function preprocessParameters($data): ?ArrayHash { return null; } private function readArticlesMetadata(array $urls, &$errors): array { $items = []; foreach ($urls as $url) { $url = trim($url); if (empty($url)) { // people sometimes enter blank lines continue; } try { $parsedUrl = new Url($url); if (isset($this->contentProcessors[$parsedUrl->getDomain()])) { $processor = $this->contentProcessors[$parsedUrl->getDomain()]; $meta = $processor->fetchUrlMeta($url); } else { $meta = $this->content->fetchUrlMeta($url); } if ($meta) { $items[$url] = $meta; } else { $errors[] = $url; } } catch (InvalidUrlException $e) { $errors[] = $url; } } return $items; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/GenericBestPerformingArticlesGenerator.php
Mailer/extensions/mailer-module/src/Models/Generators/GenericBestPerformingArticlesGenerator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Nette\Application\UI\Form; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Tomaj\NetteApi\Params\InputParam; use Tomaj\NetteApi\Params\PostInputParam; class GenericBestPerformingArticlesGenerator implements IGenerator { protected $sourceTemplatesRepository; protected $content; private $engineFactory; public $onSubmit; public function __construct( SourceTemplatesRepository $sourceTemplatesRepository, ContentInterface $content, EngineFactory $engineFactory ) { $this->sourceTemplatesRepository = $sourceTemplatesRepository; $this->content = $content; $this->engineFactory = $engineFactory; } public function generateForm(Form $form): void { $form->addTextArea('articles', 'List of articles') ->setHtmlAttribute('rows', 4) ->setHtmlAttribute('class', 'form-control html-editor') ->setOption('description', 'Insert Url of every article - each on separate line'); $form->onSuccess[] = [$this, 'formSucceeded']; } public function formSucceeded(Form $form, ArrayHash $values): void { $output = $this->process((array) $values); $this->onSubmit->__invoke($output['htmlContent'], $output['textContent']); } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } public function getWidgets(): array { return []; } public function apiParams(): array { return [ new PostInputParam('dynamic'), new PostInputParam('articles'), new PostInputParam('articles_count'), ]; } public function process(array $values): array { $sourceTemplate = $this->sourceTemplatesRepository->find($values['source_template_id']); $dynamic = filter_var($values['dynamic'] ?? null, FILTER_VALIDATE_BOOLEAN); $items = []; if ($dynamic) { if (!isset($values['articles_count'])) { throw new ProcessException("Dynamic email requires 'articles_count' parameter"); } $articlesCount = (int) $values['articles_count']; for ($i = 1; $i <= $articlesCount; $i++) { // Insert Twig variables that will be replaced later $meta = new \stdClass(); $meta->title = "{{article_{$i}_title}}"; $meta->image = "{{article_{$i}_image}}"; $meta->description = "{{article_{$i}_description}}"; $items["{{article_{$i}_url}}"] = $meta; } } else { if (!isset($values['articles'])) { throw new ProcessException("Missing 'articles' parameter"); } $urls = explode("\n", trim($values['articles'])); foreach ($urls as $url) { $meta = $this->content->fetchUrlMeta($url); if ($meta) { $items[$url] = $meta; } } } $params = [ 'items' => $items, ]; $engine = $this->engineFactory->engine(); return [ 'htmlContent' => $engine->render($sourceTemplate->content_html, $params), 'textContent' => strip_tags($engine->render($sourceTemplate->content_text, $params)), ]; } public function preprocessParameters($data): ?ArrayHash { return null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/HtmlArticleLocker.php
Mailer/extensions/mailer-module/src/Models/Generators/HtmlArticleLocker.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; class HtmlArticleLocker implements ArticleLockerInterface { private $placeholder = '<!--[LOCKED_TEXT_PLACEHOLDER]-->'; private $linkText; private $linkUrl; private $text; public function getLockedPost(string $post): string { if (stripos($post, '[lock newsletter]') !== false) { $lock = '[lock newsletter]'; } elseif (stripos($post, '[lock]') !== false) { $lock = '[lock]'; } else { // no lock, no placeholder return $post; } $parts = explode($lock, $post); return $parts[0] . $this->placeholder; } public function injectLockedMessage(string $post): string { $lockedHtml = <<< HTML <h2 style="color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;font-weight:bold;text-align:left;margin-bottom:30px;Margin-bottom:30px;font-size:24px;">{$this->text}</h2> <table class="button primary large" style="border-spacing:0;border-collapse:collapse;vertical-align:top;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;text-align:left;font-family:'Helvetica Neue', Helvetica, Arial;width:auto;margin:0 0 16px 0;Margin:0 0 16px 0;text-align: left;"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left;"> <td style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;border-collapse:collapse !important;"> <table class="button primary large" style="border-spacing:0;border-collapse:collapse;vertical-align:top;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;text-align:left;font-family:'Helvetica Neue', Helvetica, Arial;width:auto;margin:0 0 16px 0;Margin:0 0 16px 0;text-align: left;"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left;"> <td style="padding:0;vertical-align:top;font-size:18px;line-height:1.6;text-align:left;color:#ffffff;background:#00A251;border:1px solid #00A251;border-collapse:collapse !important;"> <a href="{$this->linkUrl}" title="{$this->linkText}" style="color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;color:#00A251;padding:10px 20px 10px 20px;font-size:20px;font-size:13px;font-weight:normal;color:#ffffff;text-decoration:none;display:inline-block;padding:14px 12px 14px 12px;border:0 solid #00A251;border-radius:3px;"> <!--[if gte mso 15]>&nbsp;<![endif]--> {$this->linkText}</a> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> HTML; return str_replace($this->placeholder, $lockedHtml, $post); } public function setupLockLink(string $linkText, string $linkUrl): self { $this->linkText = $linkText; $this->linkUrl = $linkUrl; return $this; } public function setLockText(string $text): self { $this->text = $text; return $this; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/WordpressHelpers.php
Mailer/extensions/mailer-module/src/Models/Generators/WordpressHelpers.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; class WordpressHelpers { private $content; public function __construct(ContentInterface $content) { $this->content = $content; } public function wpautop(string $pee, bool $br = false): string { $pre_tags = array(); if (trim($pee) === '') { return ''; } // Just to make things a little easier, pad the end. $pee = $pee . "\n"; /* * Pre tags shouldn't be touched by autop. * Replace pre tags with placeholders and bring them back after autop. */ if (strpos($pee, '<pre') !== false) { $pee_parts = explode('</pre>', $pee); $last_pee = array_pop($pee_parts); $pee = ''; $i = 0; foreach ($pee_parts as $pee_part) { $start = strpos($pee_part, '<pre'); // Malformed html? if ($start === false) { $pee .= $pee_part; continue; } $name = "<pre wp-pre-tag-$i></pre>"; $pre_tags[$name] = substr($pee_part, $start) . '</pre>'; $pee .= substr($pee_part, 0, $start) . $name; $i++; } $pee .= $last_pee; } // Change multiple <br>s into two line breaks, which will turn into paragraphs. $pee = preg_replace('|<br\s*/?>\s*<br\s*/?>|', "\n\n", $pee); $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; // Add a double line break above block-level opening tags. $pee = preg_replace('!(<' . $allblocks . '[\s/>])!', "\n\n$1", $pee); // Add a double line break below block-level closing tags. $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee); // Standardize newline characters to "\n". $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // Find newlines in all elements and add placeholders. $pee = $this->wpReplaceInHTMLTags($pee, array("\n" => " <!-- wpnl --> ")); // Collapse line breaks before and after <option> elements so they don't get autop'd. if (strpos($pee, '<option') !== false) { $pee = preg_replace('|\s*<option|', '<option', $pee); $pee = preg_replace('|</option>\s*|', '</option>', $pee); } /* * Collapse line breaks inside <object> elements, before <param> and <embed> elements * so they don't get autop'd. */ if (strpos($pee, '</object>') !== false) { $pee = preg_replace('|(<object[^>]*>)\s*|', '$1', $pee); $pee = preg_replace('|\s*</object>|', '</object>', $pee); $pee = preg_replace('%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee); } /* * Collapse line breaks inside <audio> and <video> elements, * before and after <source> and <track> elements. */ if (strpos($pee, '<source') !== false || strpos($pee, '<track') !== false) { $pee = preg_replace('%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee); $pee = preg_replace('%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee); $pee = preg_replace('%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee); } // Collapse line breaks before and after <figcaption> elements. if (strpos($pee, '<figcaption') !== false) { $pee = preg_replace('|\s*(<figcaption[^>]*>)|', '$1', $pee); $pee = preg_replace('|</figcaption>\s*|', '</figcaption>', $pee); } // Remove more than two contiguous line breaks. $pee = preg_replace("/\n\n+/", "\n\n", $pee); // Split up the contents into an array of strings, separated by double line breaks. $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY); // Reset $pee prior to rebuilding. $pee = ''; // Rebuild the content as a string, wrapping every bit with a <p>. foreach ($pees as $tinkle) { $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n"; } // Under certain strange conditions it could create a P of entirely whitespace. $pee = preg_replace('|<p>\s*</p>|', '', $pee); // Add a closing <p> inside <div>, <address>, or <form> tag if missing. $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee); // If an opening or closing block element tag is wrapped in a <p>, unwrap it. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // In some cases <li> may get wrapped in <p>, fix them. $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>. $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee); $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee); // If an opening or closing block element tag is preceded by an opening <p> tag, remove it. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee); // If an opening or closing block element tag is followed by a closing <p> tag, remove it. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // Optionally insert line breaks. if ($br) { // Replace newlines that shouldn't be touched with a placeholder. $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', function ($matches) { return str_replace("\n", "<WPPreserveNewline />", $matches[0]); }, $pee); // Normalize <br> $pee = str_replace(array('<br>', '<br/>'), '<br />', $pee); // Replace any new line characters that aren't preceded by a <br /> with a <br />. $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // Replace newline placeholders with newlines. $pee = str_replace('<WPPreserveNewline />', "\n", $pee); } // If a <br /> tag is after an opening or closing block tag, remove it. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee); // If a <br /> tag is before a subset of opening or closing block tags, remove it. $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee); $pee = preg_replace("|\n</p>$|", '</p>', $pee); // Replace placeholder <pre> tags with their original content. if (!empty($pre_tags)) { $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee); } // Restore newlines in all elements. if (false !== strpos($pee, '<!-- wpnl -->')) { $pee = str_replace(array(' <!-- wpnl --> ', '<!-- wpnl -->'), "\n", $pee); } return $pee; } public function wpReplaceInHTMLTags(string $haystack, array $replace_pairs): string { // Find all elements. $textarr = $this->wpHTMLSplit($haystack); $changed = false; // Optimize when searching for one item. if (1 === count($replace_pairs)) { // Extract $needle and $replace. foreach ($replace_pairs as $needle => $replace) { // Loop through delimiters (elements) only. for ($i = 1, $c = count($textarr); $i < $c; $i += 2) { if (false !== strpos($textarr[$i], $needle)) { $textarr[$i] = str_replace($needle, $replace, $textarr[$i]); $changed = true; } } } } else { // Extract all $needles. $needles = array_keys($replace_pairs); // Loop through delimiters (elements) only. for ($i = 1, $c = count($textarr); $i < $c; $i += 2) { foreach ($needles as $needle) { if (false !== strpos($textarr[$i], $needle)) { $textarr[$i] = strtr($textarr[$i], $replace_pairs); $changed = true; // After one strtr() break out of the foreach loop and look at next element. break; } } } } if ($changed) { $haystack = implode($textarr); } return $haystack; } public function wpHTMLSplit(string $input): array { return preg_split($this->getHTMLSplitRegex(), $input, -1, PREG_SPLIT_DELIM_CAPTURE); } public function getHTMLSplitRegex(): string { static $regex; if (!isset($regex)) { $comments = '!' // Start of comment, after the <. . '(?:' // Unroll the loop: Consume everything until --> is found. . '-(?!->)' // Dash not followed by end of comment. . '[^\-]*+' // Consume non-dashes. . ')*+' // Loop possessively. . '(?:-->)?'; // End of comment. If not found, match all input. $cdata = '!\[CDATA\[' // Start of comment, after the <. . '[^\]]*+' // Consume non-]. . '(?:' // Unroll the loop: Consume everything until ]]> is found. . '](?!]>)' // One ] not followed by end of comment. . '[^\]]*+' // Consume non-]. . ')*+' // Loop possessively. . '(?:]]>)?'; // End of comment. If not found, match all input. $escaped = '(?=' // Is the element escaped? . '!--' . '|' . '!\[CDATA\[' . ')' . '(?(?=!-)' // If yes, which type? . $comments . '|' . $cdata . ')'; $regex = '/(' // Capture the entire match. . '<' // Find start of element. . '(?' // Conditional expression follows. . $escaped // Find end of escaped element. . '|' // ... else ... . '[^>]*>?' // Find end of normal element. . ')' . ')/'; } return $regex; } public function wpParseArticleLinks(string $post, string $host, callable $callback, ?array &$errors = null) { return preg_replace_callback('/\[articlelink.*?id="?(\d+)"?.*?\]/is', function ($matches) use ($host, $callback, &$errors) { $url = $host . $matches[1]; try { $meta = $this->content->fetchUrlMeta($url); } catch (InvalidUrlException $e) { if (isset($errors)) { $errors[$matches[1]] = "Unable to fetch metadata for [articlelink id={$matches[1]}], the article doesn't exist"; } return null; } return $callback($meta->getTitle(), $url, $meta->getImage()); }, $post); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/GeneratorFactory.php
Mailer/extensions/mailer-module/src/Models/Generators/GeneratorFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Nette\DI\Container; use Remp\MailerModule\Components\GeneratorWidgets\GeneratorWidgetsManager; class GeneratorFactory { /** @var IGenerator[] */ private $generators = []; private $pairs = []; private $generatorWidgetsManager; private $container; public function __construct( Container $container, GeneratorWidgetsManager $generatorWidgetsManager ) { $this->generatorWidgetsManager = $generatorWidgetsManager; $this->container = $container; } public function registerGenerator(string $type, string $label, IGenerator $generator): void { $this->generators[$type] = $generator; $this->pairs[$type] = $label; $widgetClasses = $generator->getWidgets(); foreach ($widgetClasses as $class) { $widget = $this->container->getByType($class); $this->generatorWidgetsManager->registerWidget($type, $widget); } } /** * @param string $type * @return IGenerator * @throws \Exception */ public function get(string $type): IGenerator { if (isset($this->generators[$type])) { return $this->generators[$type]; } throw new \Exception("Unknown generator type: {$type}"); } public function keys(): array { return array_keys($this->generators); } public function pairs(): array { return $this->pairs; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Generators/SnippetArticleLocker.php
Mailer/extensions/mailer-module/src/Models/Generators/SnippetArticleLocker.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Generators; use Remp\MailerModule\Repositories\SnippetsRepository; use Tracy\Debugger; use Tracy\ILogger; class SnippetArticleLocker implements ArticleLockerInterface { private string $lockSnippetCode; public function __construct(private readonly SnippetsRepository $snippetsRepository) { } public const LOCKED_TEXT_PLACEHOLDER = '<!--[LOCKED_TEXT_PLACEHOLDER]-->'; public function getLockedPost(string $post): string { if (stripos($post, '[lock newsletter]') !== false) { $lock = '[lock newsletter]'; } elseif (stripos($post, '[lock]') !== false) { $lock = '[lock]'; } else { // no lock, no placeholder return $post; } $parts = explode($lock, $post); return $parts[0] . self::LOCKED_TEXT_PLACEHOLDER; } public function injectLockedMessage(string $post): string { if (!isset($this->lockSnippetCode)) { Debugger::log("Unable to inject lock message to the generated email, snippet for SnippetArticleLocker was not configured.", ILogger::ERROR); return str_replace(self::LOCKED_TEXT_PLACEHOLDER, '', $post); } $lockSnippet = $this->snippetsRepository->findByCodeAndMailType($this->lockSnippetCode, null); if (!$lockSnippet) { Debugger::log("Unable to inject lock message to the generated email, snippet '{$this->lockSnippetCode}' doesn't exist.", ILogger::ERROR); return str_replace(self::LOCKED_TEXT_PLACEHOLDER, '', $post); } return str_replace(self::LOCKED_TEXT_PLACEHOLDER, $lockSnippet->html, $post); } public function setLockSnippetCode(string $lockSnippetCode): void { $this->lockSnippetCode = $lockSnippetCode; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Formatters/DateFormatterFactory.php
Mailer/extensions/mailer-module/src/Models/Formatters/DateFormatterFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Formatters; use IntlDateFormatter; class DateFormatterFactory { private $locale; private $timezone; public function __construct(string $locale, $timezone) { $this->locale = $locale; $this->timezone = $timezone; } public function getInstance(int $datetype, int $timetype): IntlDateFormatter { return new IntlDateFormatter( $this->locale, $datetype, $timetype, $this->timezone ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Traits/SlugTrait.php
Mailer/extensions/mailer-module/src/Models/Traits/SlugTrait.php
<?php namespace Remp\MailerModule\Models\Traits; use Nette\Utils\Strings; use Remp\MailerModule\Repositories\InvalidSlugException; trait SlugTrait { public static function isValidSlug($value): bool { $slug = Strings::webalize($value); return $slug === $value; } public function assertSlug($value): void { if (!$this->isValidSlug($value)) { throw new InvalidSlugException("Provided string [{$value}] is not URL friendly slug."); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Job/JobSegmentsManager.php
Mailer/extensions/mailer-module/src/Models/Job/JobSegmentsManager.php
<?php namespace Remp\MailerModule\Models\Job; use Exception; use Nette\Utils\Json; class JobSegmentsManager { private array $includeSegments = []; private array $excludeSegments = []; public function __construct($job = null) { if (isset($job)) { $segments = $this->getJobSegments($job); $this->includeSegments = $segments['include']; $this->excludeSegments = $segments['exclude']; } } public function includeSegment($segmentCode, $segmentProvider): self { $this->includeSegments[] = ['code' => $segmentCode, 'provider' => $segmentProvider]; return $this; } public function excludeSegment($segmentCode, $segmentProvider): self { $this->excludeSegments[] = ['code' => $segmentCode, 'provider' => $segmentProvider]; return $this; } public function getIncludeSegments(): array { return $this->includeSegments; } public function getExcludeSegments(): array { return $this->excludeSegments; } private function getJobSegments($job): array { return Json::decode($job->segments, Json::FORCE_ARRAY); } public function toJson() { if (empty($this->includeSegments)) { throw new Exception("You have to add at least one include segment."); } $segments = [ 'include' => $this->includeSegments, 'exclude' => $this->excludeSegments, ]; return Json::encode($segments); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Job/MailCache.php
Mailer/extensions/mailer-module/src/Models/Job/MailCache.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Job; use Remp\MailerModule\Models\RedisClientFactory; use Remp\MailerModule\Models\RedisClientTrait; class MailCache { use RedisClientTrait; const REDIS_KEY = 'mail-queue-'; const REDIS_PRIORITY_QUEUES_KEY = 'priority-mail-queues'; private $host; private $port; private $db; public function __construct(protected RedisClientFactory $redisClientFactory) { } /** * @link https://redis.io/commands/ping * @param string|null $message * @return mixed */ public function ping(string $message = null) { return $this->redis()->ping($message); } /** * Adds mail job to mail processing cache * * Note: all parameters in $params having name with suffix '_href_url' are treated as URLs that can be changed later by email sender. * The URL destination itself will be kept, however, e.g. tracking parameters could be added, URL shortener used. * Example: https://dennikn.sk/1589603/ could be changed to https://dennikn.sk/1589603/?rtm_source=email * * @param int $userId * @param string $email * @param string $templateCode * @param int $queueId * @param string|null $context * @param array $params contains array of key-value items that will replace variables in email and subject * * @return bool */ public function addJob(int $userId, string $email, string $templateCode, int $queueId, ?string $context = null, array $params = []): bool { $job = json_encode([ 'userId' => $userId, 'email' => $email, 'templateCode' => $templateCode, 'context' => $context, 'params' => $params ]); if ($this->jobExists($job, $queueId)) { return false; } return (bool)$this->redis()->sadd(static::REDIS_KEY . $queueId, [$job]); } public function getJob(int $queueId): ?string { return $this->redis()->spop(static::REDIS_KEY . $queueId); } public function getJobs(int $queueId, int $count = 1): array { return (array) $this->redis()->spop(static::REDIS_KEY . $queueId, $count); } public function hasJobs(int $queueId): bool { return $this->redis()->scard(static::REDIS_KEY . $queueId) > 0; } public function countJobs(int $queueId): int { return $this->redis()->scard(static::REDIS_KEY . $queueId); } public function jobExists(string $job, int $queueId): bool { return (bool)$this->redis()->sismember(static::REDIS_KEY . $queueId, $job); } // Mail queue public function removeQueue(int $queueId): bool { $res1 = $this->redis()->del([static::REDIS_KEY . $queueId]); $res2 = $this->redis()->zrem(static::REDIS_PRIORITY_QUEUES_KEY, $queueId); return $res1 && $res2; } public function pauseQueue(int $queueId): int { return $this->redis()->zadd(static::REDIS_PRIORITY_QUEUES_KEY, [$queueId => 0]); } public function restartQueue(int $queueId, int $priority): int { return $this->redis()->zadd(static::REDIS_PRIORITY_QUEUES_KEY, [$queueId => $priority]); } public function isQueueActive(int $queueId): bool { return $this->redis()->zscore(static::REDIS_PRIORITY_QUEUES_KEY, $queueId) > 0; } /** * getTopPriorityQueues returns array of queue-score pairs order by queue priority (descending). */ public function getTopPriorityQueues(int $count = 1) { // TODO: change to zrange with "byscore" and "rev" options once we upgrade to Predis 2.0 return $this->redis()->zrevrangebyscore( static::REDIS_PRIORITY_QUEUES_KEY, '+inf', 1, [ 'withscores' => true, 'limit' => [ 'offset' => 0, 'count' => $count, ], ] ); } public function isQueueTopPriority(int $queueId): bool { $topPriorityQueue = $this->getTopPriorityQueues(); $selectedQueueScore = $this->redis()->zscore(static::REDIS_PRIORITY_QUEUES_KEY, $queueId); return isset($topPriorityQueue[$queueId]) || // topPriorityQueue is requested queue reset($topPriorityQueue) == $selectedQueueScore; // or requested queue has same priority as topPriorityQueue } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Job/BatchEmailGenerator.php
Mailer/extensions/mailer-module/src/Models/Job/BatchEmailGenerator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Job; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use Remp\MailerModule\Models\Beam\UnreadArticlesResolver; use Remp\MailerModule\Models\Beam\UserUnreadArticlesResolveException; use Remp\MailerModule\Models\Segment\Aggregator; use Remp\MailerModule\Models\Users\IUser; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\JobQueueRepository; class BatchEmailGenerator { const BEAM_UNREAD_ARTICLES_RESOLVER = 'beam-unread-articles'; private int $deleteLimit = 10000; private $templates = []; public function __construct( private LoggerInterface $logger, private JobQueueRepository $mailJobQueueRepository, private Aggregator $segmentAggregator, private IUser $userProvider, private MailCache $mailCache, private UnreadArticlesResolver $unreadArticlesResolver, ) { } public function setDeleteLimit($limit): void { $this->deleteLimit = $limit; } protected function insertUsersIntoJobQueue(ActiveRow $batch, &$userMap): array { $this->logger->info('Clearing batch', ['batchId' => $batch->id]); $this->mailJobQueueRepository->clearBatch($batch); $batchInsert = 200; $insert = []; $processed = 0; $templateUsersCount = []; $job = $batch->job; $usersSegments = []; $jobSegmentsManager = new JobSegmentsManager($batch->mail_job); $this->logger->info('Fetching users from include segments', ['batchId' => $batch->id]); $includeSegments = $jobSegmentsManager->getIncludeSegments(); foreach ($includeSegments as $segment) { $this->logger->info('Fetching users from the include segment', [ 'batchId' => $batch->id, 'provider' => $segment['provider'], 'code' => $segment['code'], ]); $includeUserIds = $this->segmentAggregator->users(['provider' => $segment['provider'], 'code' => $segment['code']]); $usersSegments = array_unique(array_merge($usersSegments, $includeUserIds), SORT_NUMERIC); } $this->logger->info('Fetching users from exclude segments', ['batchId' => $batch->id]); $excludeSegments = $jobSegmentsManager->getExcludeSegments(); foreach ($excludeSegments as $segment) { $this->logger->info('Fetching users from the exclude segment', [ 'batchId' => $batch->id, 'provider' => $segment['provider'], 'code' => $segment['code'], ]); $excludeUserIds = $this->segmentAggregator->users(['provider' => $segment['provider'], 'code' => $segment['code']]); $usersSegments = array_diff($usersSegments, $excludeUserIds); } $this->logger->info('Processing users from segments to mail_job_queue', ['batchId' => $batch->id]); foreach (array_chunk($usersSegments, 1000, true) as $userIdsChunk) { $page = 1; while ($users = $this->userProvider->list($userIdsChunk, $page)) { foreach ($users as $user) { $userMap[$user['email']] = $user['id']; $templateId = $this->getTemplate($batch); $templateUsersCount[$templateId] = ($templateUsersCount[$templateId] ?? 0) + 1; $insert[] = [ 'batch' => $batch, 'templateId' => $templateId, 'email' => $user['email'], 'sorting' => rand(), /** @phpstan-ignore-line */ 'context' => $job->context, 'params' => json_encode($user) // forward all user attributes to template params ]; ++$processed; if ($processed === $batchInsert) { $processed = 0; $this->mailJobQueueRepository->multiInsert($insert); $insert = []; } } $page++; } } if ($processed) { $this->mailJobQueueRepository->multiInsert($insert); } return $templateUsersCount; } protected function filterQueue($batch): array { $job = $batch->job; $this->logger->info('Users in queue before filter: ' . $this->mailJobQueueRepository->getBatchUsersCount($batch), ['batchId' => $batch->id]); $this->logger->info('Removing unsubscribed', ['batchId' => $batch->id]); $this->mailJobQueueRepository->removeUnsubscribed($batch, $this->deleteLimit); $this->logger->info('Users left in queue: ' . $this->mailJobQueueRepository->getBatchUsersCount($batch), ['batchId' => $batch->id]); if ($job->mail_type_variant_id) { $this->logger->info('Removing other variants', ['batchId' => $batch->id]); $this->mailJobQueueRepository->removeOtherVariants($batch, $job->mail_type_variant_id, $this->deleteLimit); $this->logger->info('Users left in queue: ' . $this->mailJobQueueRepository->getBatchUsersCount($batch), ['batchId' => $batch->id]); } if ($job->context) { $this->logger->info('Removing already sent context', ['batchId' => $batch->id]); $this->mailJobQueueRepository->removeAlreadySentContext($batch, $job->context, $this->deleteLimit); $this->logger->info('Users left in queue: ' . $this->mailJobQueueRepository->getBatchUsersCount($batch), ['batchId' => $batch->id]); } $this->logger->info('Removing already queued in other job batch', ['batchId' => $batch->id]); $this->mailJobQueueRepository->removeAlreadyQueued($batch, $this->deleteLimit); $this->logger->info('Users left in queue: ' . $this->mailJobQueueRepository->getBatchUsersCount($batch), ['batchId' => $batch->id]); $this->logger->info('Removing already sent template', ['batchId' => $batch->id]); $this->mailJobQueueRepository->removeAlreadySent($batch, $this->deleteLimit); $this->logger->info('Users left in queue: ' . $this->mailJobQueueRepository->getBatchUsersCount($batch), ['batchId' => $batch->id]); if ($batch->max_emails) { $this->logger->info('Removing emails above configured count', ['batchId' => $batch->id]); $this->mailJobQueueRepository->stripEmails($batch, $batch->max_emails, $this->deleteLimit); $this->logger->info('Users left in queue: ' . $this->mailJobQueueRepository->getBatchUsersCount($batch), ['batchId' => $batch->id]); } // Count remaining users $templateUsersCount = []; $q = $this->mailJobQueueRepository->getTable() ->select('count(*) AS users_count, mail_template_id') ->where(['mail_batch_id' => $batch->id]) ->group('mail_template_id'); foreach ($q->fetchAll() as $row) { $templateUsersCount[$row->mail_template_id] = $row->users_count; } return $templateUsersCount; } public function generate(ActiveRow $batch) { $userMap = []; $this->logger->info('Acquiring users for batch', [ 'batchId' => $batch->id, ]); $templateUsersCount = $this->insertUsersIntoJobQueue($batch, $userMap); foreach ($templateUsersCount as $templateId => $count) { $this->logger->info('Generating batch queue', [ 'batchId' => $batch->id, 'templateId' => $templateId, 'usersCount' => $count ]); } $templateUsersCount = $this->filterQueue($batch); foreach ($templateUsersCount as $templateId => $count) { $this->logger->info('Users from batch queue filtered', [ 'batchId' => $batch->id, 'templateId' => $templateId, 'usersCount' => $count ]); } $queueJobsSelection = $this->mailJobQueueRepository->getBatchEmails($batch, 0, null); $this->mailCache->pauseQueue($batch->id); $totalQueueSize = (clone $queueJobsSelection)->count('*'); $lastId = PHP_INT_MIN; $limit = 1000; $jobsCount = 0; for ($i = 0, $iMax = ceil($totalQueueSize / $limit); $i <= $iMax; $i++) { $userJobOptions = []; $queueJobs = (clone $queueJobsSelection) ->where('id > ?', $lastId) ->limit($limit); /** @var ActiveRow $queueJob */ foreach ($queueJobs as $queueJob) { $template = $queueJob->ref('mail_templates', 'mail_template_id'); $userId = $userMap[$queueJob->email]; $jobOptions = [ 'email' => $queueJob->email, 'code' => $template->code, 'mail_batch_id' => $queueJob->mail_batch_id, 'context' => $queueJob->context, 'params' => json_decode($queueJob->params, true) ?? [] ]; // Retrieve dynamic parameters (specified by 'extras') if ($template->extras) { $extras = json_decode($template->extras, true); $extrasHandler = $extras['handler'] ?? null; // Unread articles are resolved for multiple users at once, add them to resolver queue if ($extrasHandler === self::BEAM_UNREAD_ARTICLES_RESOLVER) { $jobOptions['handler'] = $extrasHandler; $parameters = $extras['parameters'] ?? false; if ($parameters) { $this->unreadArticlesResolver->addToResolveQueue($template->code, $userId, $parameters); } } elseif ($extrasHandler !== null) { $this->logger->log(LogLevel::ERROR, "Unknown extras handler: {$extrasHandler}"); } } $userJobOptions[$userId] = $jobOptions; $lastId = $queueJob->id; } // Resolve dynamic parameters for given jobs at once $this->unreadArticlesResolver->resolve(); foreach ($userJobOptions as $userId => $jobOptions) { if ($jobOptions['handler'] ?? null === self::BEAM_UNREAD_ARTICLES_RESOLVER) { try { $additionalParams = $this->unreadArticlesResolver->getResolvedMailParameters($jobOptions['code'], $userId); foreach ($additionalParams as $name => $value) { $jobOptions['params'][$name] = $value; } } catch (UserUnreadArticlesResolveException $exception) { // just log and continue to next user $this->logger->log(LogLevel::ERROR, $exception->getMessage()); continue; } } $result = $this->mailCache->addJob( $userId, $jobOptions['email'], $jobOptions['code'], $jobOptions['mail_batch_id'], $jobOptions['context'], $jobOptions['params'] ); if ($result !== false) { $jobsCount++; } } } $this->logger->info('Jobs inserted into mail cache', ['jobsCount' => $jobsCount]); } private function getTemplate(ActiveRow $batch) { if (isset($this->templates[$batch->id])) { return $this->templates[$batch->id][ array_rand($this->templates[$batch->id]) ]; } $this->templates[$batch->id] = []; $templates = $batch->related('mail_job_batch_templates'); /** @var ActiveRow $template */ foreach ($templates as $template) { $this->templates[$batch->id] = array_merge($this->templates[$batch->id], array_fill(0, $template->weight, $template->mail_template_id)); } return $this->templates[$batch->id][ array_rand($this->templates[$batch->id]) ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Mailer/Mailer.php
Mailer/extensions/mailer-module/src/Models/Mailer/Mailer.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Mailer; use Nette\Utils\Strings; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\Config\ConfigNotExistsException; use Remp\MailerModule\Repositories\ConfigsRepository; abstract class Mailer implements \Nette\Mail\Mailer { public const ALIAS = ""; protected array $options = []; protected ?string $code = null; public function __construct( private Config $config, private ConfigsRepository $configsRepository, ?string $code = null, ) { $this->code = $code; $this->buildConfig(); } public function getMailerAlias(): string { return self::buildAlias($this::ALIAS, $this->code); } public static function buildAlias($alias, $code) { $mailerAlias = str_replace('-', '_', Strings::webalize($alias)); if (isset($code)) { $mailerAlias .= '_' . $code; } return $mailerAlias; } public function getIdentifier(): string { $array = explode('\\', get_class($this)); $label = end($array); if (isset($this->code)) { $label .= '_' . $this->code; } return $label; } public function getConfigs(): array { return $this->options; } /** * Returns single config value * * @param string $config * @return string|null */ public function getConfig(string $config): ?string { return $this->options[$config]['value'] ?? null; } protected function buildConfig(): void { foreach ($this->options as $name => $definition) { $configName = $this->getConfigFieldName($name); try { $this->options[$name]['value'] = $this->config->get($configName); } catch (ConfigNotExistsException $e) { $this->configsRepository->add( $configName, $definition['label'], null, $definition['description'] ?? null, Config::TYPE_STRING ); $this->config->refresh(true); $this->options[$name] = [ 'label' => $definition['label'], 'required' => $definition['required'], 'value' => null, ]; } } } private function getConfigFieldName(string $name): string { return $this->getMailerAlias() . '_' . $name; } public function isConfigured(): bool { foreach ($this->getRequiredOptions() as $option) { if (!isset($option['value'])) { return false; } } return true; } public function getRequiredOptions(): array { return array_filter($this->options, function ($option) { return $option['required']; }); } /** * If Mailer implementation supports template parameters (e.g. within batch email sending) * you can replace the real values of params with names of template variables which will * be used to inject the values by Mailer service. * * Return value is ordered as [transformed params for twig, * altered params for mailer header X-Mailer-Template-Params] * * @param array $params * @return array */ public function transformTemplateParams(array $params): array { return [$params, $params]; } /** * supportsBatch returns flag, whether the selected Mailer supports batch sending * * @return bool */ public function supportsBatch(): bool { return false; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Mailer/MailHeaderTrait.php
Mailer/extensions/mailer-module/src/Models/Mailer/MailHeaderTrait.php
<?php namespace Remp\MailerModule\Models\Mailer; trait MailHeaderTrait { /** * Get parameter from header string * * <code> * $headerValue = 'Content-Disposition: attachment; filename="invoice-2024-09-24.pdf"'; * // $filename will contain string "invoice-2024-09-24.pdf" * $filename = $this->getHeaderParameter($headerValue, 'filename'); * </code> */ public function getHeaderParameter(string $headerValue, string $parameter): ?string { preg_match('/.*' . $parameter . '="(?<value>([^"]*))"/', $headerValue, $result); return $result['value'] ?? null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Mailer/MailgunMailer.php
Mailer/extensions/mailer-module/src/Models/Mailer/MailgunMailer.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Mailer; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use GuzzleHttp\MessageFormatter; use GuzzleHttp\Middleware; use Mailgun\HttpClient\HttpClientConfigurator; use Mailgun\Mailgun; use Nette\Mail\Message; use Nette\Utils\Json; use Psr\Log\LoggerInterface; use Remp\MailerModule\Models\Sender\MailerBatchException; use Remp\MailerModule\Models\Sender\MailerRuntimeException; use RuntimeException; class MailgunMailer extends Mailer { use MailHeaderTrait; public const ALIAS = 'remp_mailgun'; private ?LoggerInterface $logger = null; protected array $options = [ 'api_key' => [ 'required' => true, 'label' => 'Mailgun API key', 'description' => 'Mailgun domain (e.g. key-abcdefgh12345678)', ], 'domain' => [ 'required' => true, 'label' => 'Mailgun domain', 'description' => 'Mailgun domain (e.g. mg.example.com)', ], 'endpoint' => [ 'required' => false, 'label' => 'Mailgun endpoint', 'description' => 'Mailgun server URL (e.g. https://api.mailgun.net)', ], 'http_webhook_signing_key' => [ 'required' => false, 'label' => 'HTTP webhook signing key', 'description' => "This key is used by Mailgun to sign webhook requests. It can be obtained in Mailgun's dashboard (Sending - Webhooks).", ], ]; public function setLogger(LoggerInterface $logger): void { $this->logger = $logger; } public function createMailer(): Mailgun { $this->buildConfig(); // fetch newer values $clientConfigurator = (new HttpClientConfigurator()) ->setApiKey($this->option('api_key')); if ($endpoint = $this->option('endpoint')) { $clientConfigurator->setEndpoint($endpoint); } if ($this->logger) { $stack = HandlerStack::create(); $stack->push( Middleware::log($this->logger, new MessageFormatter(MessageFormatter::DEBUG)) ); $client = new Client([ 'handler' => $stack, ]); $clientConfigurator->setHttpClient($client); } return new Mailgun($clientConfigurator); } public function send(Message $mail): void { $mailer = $this->createMailer(); $from = null; foreach ($mail->getFrom() as $email => $name) { $from = "$name <$email>"; } $toHeader = $mail->getHeader('To'); $recipientVariablesHeaderJson = $mail->getHeader('X-Mailer-Template-Params'); if (count($toHeader) > 1 && !$recipientVariablesHeaderJson) { throw new MailerBatchException("unsafe use of Mailgun mailer with multiple recipients: recipient variables (X-Mailer-Template-Params header) missing"); } $recipientVariablesHeader = Json::decode($recipientVariablesHeaderJson, Json::FORCE_ARRAY); $to = []; $now = microtime(true); $messageIdHeader = null; foreach ($toHeader as $email => $name) { $messageId = sprintf( "remp_mailer_%s_%s@%s", hash("crc32c", $email . $now), (int) $now, $this->option('domain') ); if (count($toHeader) > 1) { if (!isset($recipientVariablesHeader[$email])) { throw new MailerBatchException("unsafe use of Mailgun mailer with multiple recipients: recipient variables (X-Mailer-Template-Params header) missing for email: {$email}"); } $messageIdHeader = "%recipient.message_id%"; $recipientVariablesHeader[$email]['message_id'] = $messageId; } else { $messageIdHeader = $messageId; } $to[] = $email; } $attachments = []; foreach ($mail->getAttachments() as $attachment) { // example header with attachment: `Content-Disposition: attachment; filename="invoice-2024-09-24.pdf"` $filename = $this->getHeaderParameter($attachment->getHeader('Content-Disposition'), 'filename'); $attachments[] = [ 'fileContent' => $attachment->getBody(), 'filename' => $filename, ]; } $tag = $mail->getHeader('X-Mailer-Tag'); $clickTracking = $mail->getHeader('X-Mailer-Click-Tracking'); $listUnsubscribe = $mail->getHeader('List-Unsubscribe'); $listUnsubscribePost = $mail->getHeader('List-Unsubscribe-Post'); $data = [ 'from' => $from, 'to' => $to, 'subject' => $mail->getSubject(), 'text' => $mail->getBody(), 'html' => $mail->getHtmlBody(), 'attachment' => $attachments, 'recipient-variables' => Json::encode($recipientVariablesHeader), 'h:Precedence' => 'bulk', // https://blog.returnpath.com/precedence/ 'h:Message-ID' => $messageIdHeader, ]; if ($tag) { $data['o:tag'] = $tag; } if ($clickTracking !== null) { $data['o:tracking-clicks'] = (bool) $clickTracking ? 'yes' : 'no'; } if (isset($listUnsubscribe)) { $data['h:List-Unsubscribe'] = $listUnsubscribe; } if (isset($listUnsubscribe)) { $data['h:List-Unsubscribe-Post'] = $listUnsubscribePost; } $mailVariables = Json::decode($mail->getHeader('X-Mailer-Variables'), Json::FORCE_ARRAY); foreach ($mailVariables as $key => $val) { $data["v:".$key] = (string) $val; } try { $mailer->messages()->send($this->option('domain'), $data); } catch (RuntimeException $exception) { throw new MailerRuntimeException($exception->getMessage()); } } /** * @deprecated Use `createMailer()` method instead. */ public function mailer(): Mailgun { return $this->createMailer(); } public function option(string $key): ?string { return $this->options[$key]['value'] ?? null; } public function transformTemplateParams(array $params): array { $transformed = []; foreach ($params as $key => $value) { $prefix = ''; $value = (string) $value; if ($value !== '' && $value[0] === '?') { $prefix = '?'; $params[$key] = substr($value, 1); } $transformed[$key] = "{$prefix}%recipient.{$key}%"; } return [$transformed, $params]; } public function supportsBatch(): bool { return true; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false