From 77f68e77786772539c1b62cf86e43394464f0166 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Wed, 28 May 2025 17:13:54 +0400 Subject: [PATCH 01/12] ISSUE-345: mailer packages --- composer.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 89a2fcde..c447bc9d 100644 --- a/composer.json +++ b/composer.json @@ -59,7 +59,12 @@ "masterminds/html5": "^2.9", "ext-dom": "*", "league/csv": "^9.23.0", - "doctrine/doctrine-migrations-bundle": "^3.4" + "doctrine/doctrine-migrations-bundle": "^3.4", + "symfony/mailer": "^6.4", + "symfony/google-mailer": "^6.4", + "symfony/amazon-mailer": "^6.4", + "symfony/mailchimp-mailer": "^6.4", + "symfony/sendgrid-mailer": "^6.4" }, "require-dev": { "phpunit/phpunit": "^9.5", From 6aa337b1093a44ff5fbb2e45429d6ba66695f98e Mon Sep 17 00:00:00 2001 From: Tatevik Date: Wed, 28 May 2025 17:19:58 +0400 Subject: [PATCH 02/12] ISSUE-345: add env --- .env.example | 27 ++++++++++++++++++++++++++ .gitignore | 2 ++ README.md | 35 +++++++++++++++++++++++++++++++++- bin/console | 17 +++++++++++++++-- composer.json | 3 ++- src/Core/Bootstrap.php | 43 +++++++++++++++++++++++++++++++++++++++++- 6 files changed, 122 insertions(+), 5 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..648459f6 --- /dev/null +++ b/.env.example @@ -0,0 +1,27 @@ +# This is an example .env file for phpList +# Copy this file to .env and customize it for your environment + +# Application environment (dev, test, prod) +APP_ENV=dev + +# Debug mode (1 for enabled, 0 for disabled) +APP_DEBUG=1 + +# Database configuration +PHPLIST_DATABASE_DRIVER=pdo_mysql +PHPLIST_DATABASE_PATH= +PHPLIST_DATABASE_HOST='127.0.0.1' +PHPLIST_DATABASE_PORT=3306 +PHPLIST_DATABASE_NAME='phplistdb' +PHPLIST_DATABASE_USER='phplist' +PHPLIST_DATABASE_PASSWORD='phplist' + +# Mailer configuration +MAILER_DSN=smtp://user:pass@smtp.example.com:25 +#MAILER_DSN=gmail://username:password@default +#MAILER_DSN=ses://ACCESS_KEY:SECRET_KEY@default?region=eu-west-1 +#MAILER_DSN=sendgrid://KEY@default +#MAILER_DSN=mandrill://KEY@default + +# Secret key for security +PHPLIST_SECRET=bd21d72faef90cdb9c4e99e82f5edd089bfb0c5a diff --git a/.gitignore b/.gitignore index 25db886b..73f08282 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,5 @@ .vagrant .phpdoc/ .phpunit.result.cache +/.env +/.env.local diff --git a/README.md b/README.md index 502e84c6..c5fa8798 100755 --- a/README.md +++ b/README.md @@ -63,7 +63,40 @@ this code. The phpList application is configured so that the built-in PHP web server can run in development and testing mode, while Apache can run in production mode. -Please first set the database credentials in `config/parameters.yml`. +Please first set the database credentials in `config/parameters.yml` or in the `.env` file (see below). + +## Environment Variables + +phpList now supports loading environment variables from `.env` files. This allows you to configure your application without modifying any code or configuration files. + +### Usage + +1. Copy the `.env.example` file to `.env` in the project root: + ```bash + cp .env.example .env + ``` + +2. Edit the `.env` file and customize the variables according to your environment: + ``` + # Application environment (dev, test, prod) + APP_ENV=dev + + # Debug mode (1 for enabled, 0 for disabled) + APP_DEBUG=1 + + # Database configuration + DATABASE_URL=mysql://db_user:db_password@localhost:3306/db_name + + # Mailer configuration + MAILER_DSN=smtp://localhost:25 + + # Secret key for security + APP_SECRET=change_this_to_a_secret_value + ``` + +3. For local overrides, you can create a `.env.local` file which will be loaded after `.env`. + +Note: The `.env` and `.env.local` files are excluded from version control to prevent sensitive information from being committed. ### Development diff --git a/bin/console b/bin/console index ba36a420..7f06c77f 100755 --- a/bin/console +++ b/bin/console @@ -7,15 +7,28 @@ use PhpList\Core\Core\Bootstrap; use PhpList\Core\Core\Environment; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Input\ArgvInput; +use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\ErrorHandler\ErrorHandler; set_time_limit(0); require __DIR__ . '/../vendor/autoload.php'; +// Load environment variables from .env file +$dotenv = new Dotenv(); +$rootDir = dirname(__DIR__); +if (file_exists($rootDir . '/.env')) { + $dotenv->load($rootDir . '/.env'); + // Load .env.local if it exists (for local overrides) + if (file_exists($rootDir . '/.env.local')) { + $dotenv->load($rootDir . '/.env.local'); + } +} + $input = new ArgvInput(); -$environment = $input->getParameterOption(['--env', '-e'], getenv('SYMFONY_ENV') ?: Environment::DEVELOPMENT); -$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(['--no-debug', '']) +$environment = $input->getParameterOption(['--env', '-e'], $_ENV['APP_ENV'] ?? getenv('SYMFONY_ENV') ?: Environment::DEVELOPMENT); +$debug = (isset($_ENV['APP_DEBUG']) ? $_ENV['APP_DEBUG'] !== '0' : getenv('SYMFONY_DEBUG') !== '0') + && !$input->hasParameterOption(['--no-debug', '']) && $environment !== Environment::PRODUCTION; if ($debug) { diff --git a/composer.json b/composer.json index c447bc9d..4efede16 100644 --- a/composer.json +++ b/composer.json @@ -64,7 +64,8 @@ "symfony/google-mailer": "^6.4", "symfony/amazon-mailer": "^6.4", "symfony/mailchimp-mailer": "^6.4", - "symfony/sendgrid-mailer": "^6.4" + "symfony/sendgrid-mailer": "^6.4", + "symfony/dotenv": "^6.4" }, "require-dev": { "phpunit/phpunit": "^9.5", diff --git a/src/Core/Bootstrap.php b/src/Core/Bootstrap.php index fe79a805..8aee505e 100644 --- a/src/Core/Bootstrap.php +++ b/src/Core/Bootstrap.php @@ -7,6 +7,7 @@ use Doctrine\ORM\EntityManagerInterface; use Exception; use RuntimeException; +use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\ErrorHandler\ErrorHandler; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Request; @@ -35,6 +36,7 @@ class Bootstrap private ?ApplicationKernel $applicationKernel = null; private ApplicationStructure $applicationStructure; private ErrorHandler $errorHandler; + private bool $envLoaded = false; /** * Protected constructor to avoid direct instantiation of this class. @@ -45,6 +47,33 @@ protected function __construct() { $this->applicationStructure = new ApplicationStructure(); $this->errorHandler = new ErrorHandler(); + $this->loadEnvironmentVariables(); + } + + /** + * Loads environment variables from .env files. + * + * @return void fluent interface + */ + private function loadEnvironmentVariables(): void + { + if ($this->envLoaded) { + return; + } + + $dotenv = new Dotenv(); + $rootDir = $this->getApplicationRoot(); + + if (file_exists($rootDir . '/.env')) { + $dotenv->load($rootDir . '/.env'); + + if (file_exists($rootDir . '/.env.local')) { + $dotenv->load($rootDir . '/.env.local'); + } + + $this->envLoaded = true; + } + } /** @@ -89,6 +118,10 @@ public static function purgeInstance(): void */ public function setEnvironment(string $environment): Bootstrap { + if ($environment === Environment::DEFAULT_ENVIRONMENT && isset($_ENV['APP_ENV'])) { + $environment = $_ENV['APP_ENV']; + } + Environment::validateEnvironment($environment); $this->environment = $environment; @@ -102,11 +135,19 @@ public function getEnvironment(): string private function isSymfonyDebugModeEnabled(): bool { + if (isset($_ENV['APP_DEBUG'])) { + return $_ENV['APP_DEBUG'] === '1' || $_ENV['APP_DEBUG'] === 'true'; + } + return $this->environment !== Environment::PRODUCTION; } private function isDebugEnabled(): bool { + if (isset($_ENV['APP_DEBUG'])) { + return $_ENV['APP_DEBUG'] === '1' || $_ENV['APP_DEBUG'] === 'true'; + } + return $this->environment !== Environment::PRODUCTION; } @@ -138,7 +179,7 @@ public function ensureDevelopmentOrTestingEnvironment(): self } /** - * Main entry point called at every request usually from global scope. Checks if everything is correct + * The main entry point called at every request usually from global scope. Checks if everything is correct * and loads the configuration. * * @return Bootstrap fluent interface From 8b81b6a38b7838aad03c3fec44fc89071838fa4e Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 29 May 2025 20:51:29 +0400 Subject: [PATCH 03/12] ISSUE-345: refactor --- .env.example | 27 ----- composer.json | 4 +- config/PHPMD/rules.xml | 2 +- config/config.yml | 2 + config/parameters.yml.dist | 5 + config/services/commands.yml | 10 ++ config/services/managers.yml | 6 + src/Core/Bootstrap.php | 41 ------- .../Command/SendTestEmailCommand.php | 72 ++++++++++++ src/Domain/Messaging/Service/EmailService.php | 103 ++++++++++++++++++ 10 files changed, 202 insertions(+), 70 deletions(-) delete mode 100644 .env.example create mode 100644 config/services/commands.yml create mode 100644 src/Domain/Messaging/Command/SendTestEmailCommand.php create mode 100644 src/Domain/Messaging/Service/EmailService.php diff --git a/.env.example b/.env.example deleted file mode 100644 index 648459f6..00000000 --- a/.env.example +++ /dev/null @@ -1,27 +0,0 @@ -# This is an example .env file for phpList -# Copy this file to .env and customize it for your environment - -# Application environment (dev, test, prod) -APP_ENV=dev - -# Debug mode (1 for enabled, 0 for disabled) -APP_DEBUG=1 - -# Database configuration -PHPLIST_DATABASE_DRIVER=pdo_mysql -PHPLIST_DATABASE_PATH= -PHPLIST_DATABASE_HOST='127.0.0.1' -PHPLIST_DATABASE_PORT=3306 -PHPLIST_DATABASE_NAME='phplistdb' -PHPLIST_DATABASE_USER='phplist' -PHPLIST_DATABASE_PASSWORD='phplist' - -# Mailer configuration -MAILER_DSN=smtp://user:pass@smtp.example.com:25 -#MAILER_DSN=gmail://username:password@default -#MAILER_DSN=ses://ACCESS_KEY:SECRET_KEY@default?region=eu-west-1 -#MAILER_DSN=sendgrid://KEY@default -#MAILER_DSN=mandrill://KEY@default - -# Secret key for security -PHPLIST_SECRET=bd21d72faef90cdb9c4e99e82f5edd089bfb0c5a diff --git a/composer.json b/composer.json index 4efede16..936a1a69 100644 --- a/composer.json +++ b/composer.json @@ -65,7 +65,9 @@ "symfony/amazon-mailer": "^6.4", "symfony/mailchimp-mailer": "^6.4", "symfony/sendgrid-mailer": "^6.4", - "symfony/dotenv": "^6.4" + "symfony/dotenv": "^6.4", + "symfony/twig-bundle": "^6.4", + "symfony/messenger": "^6.4" }, "require-dev": { "phpunit/phpunit": "^9.5", diff --git a/config/PHPMD/rules.xml b/config/PHPMD/rules.xml index 8c88111a..2d88410b 100644 --- a/config/PHPMD/rules.xml +++ b/config/PHPMD/rules.xml @@ -51,7 +51,7 @@ - + diff --git a/config/config.yml b/config/config.yml index fd4705bb..93df3f5c 100644 --- a/config/config.yml +++ b/config/config.yml @@ -40,3 +40,5 @@ framework: serializer: enabled: true enable_attributes: true + mailer: + dsn: '%app.mailer_dsn%' diff --git a/config/parameters.yml.dist b/config/parameters.yml.dist index 00ce9a48..e2c5b62d 100644 --- a/config/parameters.yml.dist +++ b/config/parameters.yml.dist @@ -25,3 +25,8 @@ parameters: # A secret key that's used to generate certain security-related tokens secret: '%%env(PHPLIST_SECRET)%%' env(PHPLIST_SECRET): %1$s + + app.mailer_from: '%env(MAILER_FROM)%' + env(MAILER_FROM): 'noreply@phplist.com' + app.mailer_dsn: '%env(MAILER_DSN)%' + env(MAILER_DSN): 'smtp://username:password@smtp.mailtrap.io:2525' diff --git a/config/services/commands.yml b/config/services/commands.yml new file mode 100644 index 00000000..61dad7a5 --- /dev/null +++ b/config/services/commands.yml @@ -0,0 +1,10 @@ +services: + _defaults: + autowire: true + autoconfigure: true + public: false + + PhpList\Core\Domain\Messaging\Command\: + resource: '../../src/Domain/Messaging/Command' + tags: ['console.command'] + diff --git a/config/services/managers.yml b/config/services/managers.yml index cdb1eb63..eaa37758 100644 --- a/config/services/managers.yml +++ b/config/services/managers.yml @@ -61,3 +61,9 @@ services: autowire: true autoconfigure: true public: true + + PhpList\Core\Domain\Messaging\Service\EmailService: + autowire: true + autoconfigure: true + arguments: + $defaultFromEmail: '%app.mailer_from%' diff --git a/src/Core/Bootstrap.php b/src/Core/Bootstrap.php index 8aee505e..c56b6e4a 100644 --- a/src/Core/Bootstrap.php +++ b/src/Core/Bootstrap.php @@ -7,7 +7,6 @@ use Doctrine\ORM\EntityManagerInterface; use Exception; use RuntimeException; -use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\ErrorHandler\ErrorHandler; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Request; @@ -36,7 +35,6 @@ class Bootstrap private ?ApplicationKernel $applicationKernel = null; private ApplicationStructure $applicationStructure; private ErrorHandler $errorHandler; - private bool $envLoaded = false; /** * Protected constructor to avoid direct instantiation of this class. @@ -47,33 +45,6 @@ protected function __construct() { $this->applicationStructure = new ApplicationStructure(); $this->errorHandler = new ErrorHandler(); - $this->loadEnvironmentVariables(); - } - - /** - * Loads environment variables from .env files. - * - * @return void fluent interface - */ - private function loadEnvironmentVariables(): void - { - if ($this->envLoaded) { - return; - } - - $dotenv = new Dotenv(); - $rootDir = $this->getApplicationRoot(); - - if (file_exists($rootDir . '/.env')) { - $dotenv->load($rootDir . '/.env'); - - if (file_exists($rootDir . '/.env.local')) { - $dotenv->load($rootDir . '/.env.local'); - } - - $this->envLoaded = true; - } - } /** @@ -118,10 +89,6 @@ public static function purgeInstance(): void */ public function setEnvironment(string $environment): Bootstrap { - if ($environment === Environment::DEFAULT_ENVIRONMENT && isset($_ENV['APP_ENV'])) { - $environment = $_ENV['APP_ENV']; - } - Environment::validateEnvironment($environment); $this->environment = $environment; @@ -135,19 +102,11 @@ public function getEnvironment(): string private function isSymfonyDebugModeEnabled(): bool { - if (isset($_ENV['APP_DEBUG'])) { - return $_ENV['APP_DEBUG'] === '1' || $_ENV['APP_DEBUG'] === 'true'; - } - return $this->environment !== Environment::PRODUCTION; } private function isDebugEnabled(): bool { - if (isset($_ENV['APP_DEBUG'])) { - return $_ENV['APP_DEBUG'] === '1' || $_ENV['APP_DEBUG'] === 'true'; - } - return $this->environment !== Environment::PRODUCTION; } diff --git a/src/Domain/Messaging/Command/SendTestEmailCommand.php b/src/Domain/Messaging/Command/SendTestEmailCommand.php new file mode 100644 index 00000000..4e78ba12 --- /dev/null +++ b/src/Domain/Messaging/Command/SendTestEmailCommand.php @@ -0,0 +1,72 @@ +emailService = $emailService; + } + + protected function configure(): void + { + $this + ->setDescription(self::$defaultDescription) + ->addArgument('recipient', InputArgument::OPTIONAL, 'Recipient email address'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $recipient = $input->getArgument('recipient'); + if (!$recipient) { + $output->writeln('Recipient email address not provided'); + + return Command::FAILURE; + } + + if (!filter_var($recipient, FILTER_VALIDATE_EMAIL)) { + $output->writeln('Invalid email address: ' . $recipient); + + return Command::FAILURE; + } + + try { + $output->writeln('Sending test email to ' . $recipient); + + $email = (new Email()) + ->from(new Address('admin@example.com', 'Admin Team')) + ->to($recipient) + ->subject('Test Email from phpList') + ->text('This is a test email sent from phpList Email Service.') + ->html('

Test

This is a test email sent from phpList Email Service

'); + + $this->emailService->sendEmail($email); + $output->writeln('Test email sent successfully!'); + + return Command::SUCCESS; + } catch (Exception $e) { + $output->writeln('Failed to send test email: ' . $e->getMessage()); + + return Command::FAILURE; + } + } +} diff --git a/src/Domain/Messaging/Service/EmailService.php b/src/Domain/Messaging/Service/EmailService.php new file mode 100644 index 00000000..8a97eeb0 --- /dev/null +++ b/src/Domain/Messaging/Service/EmailService.php @@ -0,0 +1,103 @@ +mailer = $mailer; + $this->defaultFromEmail = $defaultFromEmail; + } + + /** + * Send a simple email + * + * @param Email $email + * @param array $cc + * @param array $bcc + * @param array $replyTo + * @param array $attachments + * @return void + * @throws TransportExceptionInterface + */ + public function sendEmail( + Email $email, + array $cc = [], + array $bcc = [], + array $replyTo = [], + array $attachments = [] + ): void { + if (count($email->getFrom()) === 0) { + $email->from($this->defaultFromEmail); + } + + foreach ($cc as $ccAddress) { + $email->addCc($ccAddress); + } + + foreach ($bcc as $bccAddress) { + $email->addBcc($bccAddress); + } + + foreach ($replyTo as $replyToAddress) { + $email->addReplyTo($replyToAddress); + } + + foreach ($attachments as $attachment) { + $email->attachFromPath($attachment); + } + + $this->mailer->send($email); + } + + /** + * Email multiple recipients + * + * @param array $toAddresses Array of recipient email addresses + * @param string $subject Email subject + * @param string $text Plain text content + * @param string $html HTML content (optional) + * @param string|null $from Sender email address (optional, uses default if not provided) + * @param string|null $fromName Sender name (optional) + * @param array $attachments Array of file paths to attach (optional) + * + * @return void + * @throws TransportExceptionInterface + */ + public function sendBulkEmail( + array $toAddresses, + string $subject, + string $text, + string $html = '', + ?string $from = null, + ?string $fromName = null, + array $attachments = [] + ): void { + $baseEmail = (new Email()) + ->subject($subject) + ->text($text) + ->html($html); + + if ($from) { + $baseEmail->from($fromName ? new Address($from, $fromName) : $from); + } + + foreach ($toAddresses as $recipient) { + $email = clone $baseEmail; + $email->to($recipient); + + $this->sendEmail($email, [], [], [], $attachments); + } + } +} From b85de93be20af39bcd36a73c00a475869e356365 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 29 May 2025 21:01:50 +0400 Subject: [PATCH 04/12] ISSUE-345: tests --- .gitignore | 2 - README.md | 87 +++------- bin/console | 17 +- composer.json | 1 - .../Command/SendTestEmailCommand.php | 1 - .../Command/SendTestEmailCommandTest.php | 106 ++++++++++++ .../Messaging/Service/EmailServiceTest.php | 157 ++++++++++++++++++ 7 files changed, 292 insertions(+), 79 deletions(-) create mode 100644 tests/Unit/Domain/Messaging/Command/SendTestEmailCommandTest.php create mode 100644 tests/Unit/Domain/Messaging/Service/EmailServiceTest.php diff --git a/.gitignore b/.gitignore index 73f08282..25db886b 100644 --- a/.gitignore +++ b/.gitignore @@ -16,5 +16,3 @@ .vagrant .phpdoc/ .phpunit.result.cache -/.env -/.env.local diff --git a/README.md b/README.md index c5fa8798..f21c5cff 100755 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ phpList is an open source newsletter manager. This project is a rewrite of the ## About this package -This is the core module of the successor to phpList 3. It will have the +This is the core module of the successor to phpList 3. It will have the following responsibilities: * provide access to the DB via Doctrine models and repositories (and raw SQL @@ -41,7 +41,7 @@ Since this package is only a service required to run a full installation of **ph ## Contributing to this package -Contributions to phpList repositories are highly welcomed! To get started please take a look at the [contribution guide](.github/CONTRIBUTING.md). It contains everything you would need to make your first contribution including how to run local style checks and run tests. +Contributions to phpList repositories are highly welcomed! To get started please take a look at the [contribution guide](.github/CONTRIBUTING.md). It contains everything you would need to make your first contribution including how to run local style checks and run tests. ### Code of Conduct @@ -63,40 +63,7 @@ this code. The phpList application is configured so that the built-in PHP web server can run in development and testing mode, while Apache can run in production mode. -Please first set the database credentials in `config/parameters.yml` or in the `.env` file (see below). - -## Environment Variables - -phpList now supports loading environment variables from `.env` files. This allows you to configure your application without modifying any code or configuration files. - -### Usage - -1. Copy the `.env.example` file to `.env` in the project root: - ```bash - cp .env.example .env - ``` - -2. Edit the `.env` file and customize the variables according to your environment: - ``` - # Application environment (dev, test, prod) - APP_ENV=dev - - # Debug mode (1 for enabled, 0 for disabled) - APP_DEBUG=1 - - # Database configuration - DATABASE_URL=mysql://db_user:db_password@localhost:3306/db_name - - # Mailer configuration - MAILER_DSN=smtp://localhost:25 - - # Secret key for security - APP_SECRET=change_this_to_a_secret_value - ``` - -3. For local overrides, you can create a `.env.local` file which will be loaded after `.env`. - -Note: The `.env` and `.env.local` files are excluded from version control to prevent sensitive information from being committed. +Please first set the database credentials in `config/parameters.yml`. ### Development @@ -112,9 +79,9 @@ already in use, on the next free port after 8000). You can stop the server with CTRL + C. -#### Development and Documentation +#### Development and Documentation -We use `phpDocumentor` to automatically generate documentation for classes. To make this process efficient and easier, you are required to properly "document" your `classes`,`properties`, `methods` ... by annotating them with [docblocks](https://docs.phpdoc.org/latest/guide/guides/docblocks.html). +We use `phpDocumentor` to automatically generate documentation for classes. To make this process efficient and easier, you are required to properly "document" your `classes`,`properties`, `methods` ... by annotating them with [docblocks](https://docs.phpdoc.org/latest/guide/guides/docblocks.html). More about generatings docs in [PHPDOC.md](PHPDOC.md) @@ -157,12 +124,12 @@ listed in the `extra` section of the module's `composer.json` like this: ```json "extra": { - "phplist/core": { - "bundles": [ - "Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle", - "PhpList\\Core\\EmptyStartPageBundle\\PhpListEmptyStartPageBundle" - ] - } + "phplist/core": { + "bundles": [ + "Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle", + "PhpList\\Core\\EmptyStartPageBundle\\PhpListEmptyStartPageBundle" + ] + } } ``` @@ -177,14 +144,14 @@ the `extra` section of the module's `composer.json` like this: ```json "extra": { - "phplist/core": { - "routes": { - "homepage": { - "resource": "@PhpListEmptyStartPageBundle/Controller/", - "type": "annotation" - } - } + "phplist/core": { + "routes": { + "homepage": { + "resource": "@PhpListEmptyStartPageBundle/Controller/", + "type": "annotation" + } } + } } ``` @@ -192,17 +159,17 @@ You can also provide system configuration for your module: ```json "extra": { - "phplist/core": { - "configuration": { - "framework": { - "templating": { - "engines": [ - "twig" - ] - } - } + "phplist/core": { + "configuration": { + "framework": { + "templating": { + "engines": [ + "twig" + ] } + } } + } } ``` diff --git a/bin/console b/bin/console index 7f06c77f..ba36a420 100755 --- a/bin/console +++ b/bin/console @@ -7,28 +7,15 @@ use PhpList\Core\Core\Bootstrap; use PhpList\Core\Core\Environment; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Input\ArgvInput; -use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\ErrorHandler\ErrorHandler; set_time_limit(0); require __DIR__ . '/../vendor/autoload.php'; -// Load environment variables from .env file -$dotenv = new Dotenv(); -$rootDir = dirname(__DIR__); -if (file_exists($rootDir . '/.env')) { - $dotenv->load($rootDir . '/.env'); - // Load .env.local if it exists (for local overrides) - if (file_exists($rootDir . '/.env.local')) { - $dotenv->load($rootDir . '/.env.local'); - } -} - $input = new ArgvInput(); -$environment = $input->getParameterOption(['--env', '-e'], $_ENV['APP_ENV'] ?? getenv('SYMFONY_ENV') ?: Environment::DEVELOPMENT); -$debug = (isset($_ENV['APP_DEBUG']) ? $_ENV['APP_DEBUG'] !== '0' : getenv('SYMFONY_DEBUG') !== '0') - && !$input->hasParameterOption(['--no-debug', '']) +$environment = $input->getParameterOption(['--env', '-e'], getenv('SYMFONY_ENV') ?: Environment::DEVELOPMENT); +$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(['--no-debug', '']) && $environment !== Environment::PRODUCTION; if ($debug) { diff --git a/composer.json b/composer.json index 936a1a69..0fd65a52 100644 --- a/composer.json +++ b/composer.json @@ -65,7 +65,6 @@ "symfony/amazon-mailer": "^6.4", "symfony/mailchimp-mailer": "^6.4", "symfony/sendgrid-mailer": "^6.4", - "symfony/dotenv": "^6.4", "symfony/twig-bundle": "^6.4", "symfony/messenger": "^6.4" }, diff --git a/src/Domain/Messaging/Command/SendTestEmailCommand.php b/src/Domain/Messaging/Command/SendTestEmailCommand.php index 4e78ba12..9e9594da 100644 --- a/src/Domain/Messaging/Command/SendTestEmailCommand.php +++ b/src/Domain/Messaging/Command/SendTestEmailCommand.php @@ -5,7 +5,6 @@ namespace PhpList\Core\Domain\Messaging\Command; use Exception; -use PhpList\Core\Domain\Messaging\Model\Dto\EmailMessage; use PhpList\Core\Domain\Messaging\Service\EmailService; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; diff --git a/tests/Unit/Domain/Messaging/Command/SendTestEmailCommandTest.php b/tests/Unit/Domain/Messaging/Command/SendTestEmailCommandTest.php new file mode 100644 index 00000000..a8863a31 --- /dev/null +++ b/tests/Unit/Domain/Messaging/Command/SendTestEmailCommandTest.php @@ -0,0 +1,106 @@ +emailService = $this->createMock(EmailService::class); + $command = new SendTestEmailCommand($this->emailService); + + $application = new Application(); + $application->add($command); + + $this->commandTester = new CommandTester($command); + } + + public function testExecuteWithValidEmail(): void + { + $this->emailService->expects($this->once()) + ->method('sendEmail') + ->with($this->callback(function (Email $email) { + $this->assertEquals('Test Email from phpList', $email->getSubject()); + $this->assertStringContainsString('This is a test email', $email->getTextBody()); + $this->assertStringContainsString('

Test

', $email->getHtmlBody()); + + $toAddresses = $email->getTo(); + $this->assertCount(1, $toAddresses); + $this->assertEquals('test@example.com', $toAddresses[0]->getAddress()); + + $fromAddresses = $email->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals('admin@example.com', $fromAddresses[0]->getAddress()); + $this->assertEquals('Admin Team', $fromAddresses[0]->getName()); + + return true; + })); + + $this->commandTester->execute([ + 'recipient' => 'test@example.com', + ]); + + $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Test email sent successfully', $output); + + $this->assertEquals(0, $this->commandTester->getStatusCode()); + } + + public function testExecuteWithoutRecipient(): void + { + $this->emailService->expects($this->never()) + ->method('sendEmail'); + + $this->commandTester->execute([]); + + $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Recipient email address not provided', $output); + + $this->assertEquals(1, $this->commandTester->getStatusCode()); + } + + public function testExecuteWithInvalidEmail(): void + { + $this->emailService->expects($this->never()) + ->method('sendEmail'); + + $this->commandTester->execute([ + 'recipient' => 'invalid-email', + ]); + + $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Invalid email address', $output); + + $this->assertEquals(1, $this->commandTester->getStatusCode()); + } + + public function testExecuteWithEmailServiceException(): void + { + $this->emailService->expects($this->once()) + ->method('sendEmail') + ->willThrowException(new \Exception('Test exception')); + + $this->commandTester->execute([ + 'recipient' => 'test@example.com', + ]); + + $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Failed to send test email', $output); + $this->assertStringContainsString('Test exception', $output); + + $this->assertEquals(1, $this->commandTester->getStatusCode()); + } +} diff --git a/tests/Unit/Domain/Messaging/Service/EmailServiceTest.php b/tests/Unit/Domain/Messaging/Service/EmailServiceTest.php new file mode 100644 index 00000000..c7f5fcd8 --- /dev/null +++ b/tests/Unit/Domain/Messaging/Service/EmailServiceTest.php @@ -0,0 +1,157 @@ +mailer = $this->createMock(MailerInterface::class); + $this->emailService = new EmailService($this->mailer, $this->defaultFromEmail); + } + + public function testSendEmailWithDefaultFrom(): void + { + $email = (new Email()) + ->to('recipient@example.com') + ->subject('Test Subject') + ->text('Test Content'); + + $this->mailer->expects($this->once()) + ->method('send') + ->with($this->callback(function (Email $sentEmail) { + $fromAddresses = $sentEmail->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals($this->defaultFromEmail, $fromAddresses[0]->getAddress()); + return true; + })); + + $this->emailService->sendEmail($email); + } + + public function testSendEmailWithCustomFrom(): void + { + $customFrom = 'custom@example.com'; + $email = (new Email()) + ->from($customFrom) + ->to('recipient@example.com') + ->subject('Test Subject') + ->text('Test Content'); + + $this->mailer->expects($this->once()) + ->method('send') + ->with($this->callback(function (Email $sentEmail) use ($customFrom) { + $fromAddresses = $sentEmail->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals($customFrom, $fromAddresses[0]->getAddress()); + return true; + })); + + $this->emailService->sendEmail($email); + } + + public function testSendEmailWithCcBccAndReplyTo(): void + { + $email = (new Email()) + ->to('recipient@example.com') + ->subject('Test Subject') + ->text('Test Content'); + + $cc = ['cc@example.com']; + $bcc = ['bcc@example.com']; + $replyTo = ['reply@example.com']; + + $this->mailer->expects($this->once()) + ->method('send') + ->with($this->callback(function (Email $sentEmail) use ($cc, $bcc, $replyTo) { + $ccAddresses = $sentEmail->getCc(); + $bccAddresses = $sentEmail->getBcc(); + $replyToAddresses = $sentEmail->getReplyTo(); + + $this->assertCount(1, $ccAddresses); + $this->assertEquals($cc[0], $ccAddresses[0]->getAddress()); + + $this->assertCount(1, $bccAddresses); + $this->assertEquals($bcc[0], $bccAddresses[0]->getAddress()); + + $this->assertCount(1, $replyToAddresses); + $this->assertEquals($replyTo[0], $replyToAddresses[0]->getAddress()); + + return true; + })); + + $this->emailService->sendEmail($email, $cc, $bcc, $replyTo); + } + + public function testSendEmailWithAttachments(): void + { + $email = (new Email()) + ->to('recipient@example.com') + ->subject('Test Subject') + ->text('Test Content'); + + $attachments = ['/path/to/attachment.pdf']; + + $this->mailer->expects($this->once()) + ->method('send'); + + $this->emailService->sendEmail($email, [], [], [], $attachments); + } + + public function testSendBulkEmail(): void + { + $recipients = ['user1@example.com', 'user2@example.com', 'user3@example.com']; + $subject = 'Bulk Test Subject'; + $text = 'Bulk Test Content'; + $html = '

Bulk Test HTML Content

'; + $from = 'sender@example.com'; + $fromName = 'Sender Name'; + + $this->mailer->expects($this->exactly(count($recipients))) + ->method('send') + ->with($this->callback(function (Email $sentEmail) use ($subject, $text, $html, $from, $fromName) { + $this->assertEquals($subject, $sentEmail->getSubject()); + $this->assertEquals($text, $sentEmail->getTextBody()); + $this->assertEquals($html, $sentEmail->getHtmlBody()); + + $fromAddresses = $sentEmail->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals($from, $fromAddresses[0]->getAddress()); + $this->assertEquals($fromName, $fromAddresses[0]->getName()); + + return true; + })); + + $this->emailService->sendBulkEmail($recipients, $subject, $text, $html, $from, $fromName); + } + + public function testSendBulkEmailWithDefaultFrom(): void + { + $recipients = ['user1@example.com', 'user2@example.com']; + $subject = 'Bulk Test Subject'; + $text = 'Bulk Test Content'; + + $this->mailer->expects($this->exactly(count($recipients))) + ->method('send') + ->with($this->callback(function (Email $sentEmail) { + $fromAddresses = $sentEmail->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals($this->defaultFromEmail, $fromAddresses[0]->getAddress()); + return true; + })); + + $this->emailService->sendBulkEmail($recipients, $subject, $text); + } +} From c7bceefcda3231ccab2a0d9734bc5dbf9db08bc5 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 29 May 2025 21:27:36 +0400 Subject: [PATCH 05/12] ISSUE-345: fix params --- config/parameters.yml.dist | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/config/parameters.yml.dist b/config/parameters.yml.dist index e2c5b62d..988628dc 100644 --- a/config/parameters.yml.dist +++ b/config/parameters.yml.dist @@ -22,11 +22,12 @@ parameters: database_password: '%%env(PHPLIST_DATABASE_PASSWORD)%%' env(PHPLIST_DATABASE_PASSWORD): 'phplist' + # mailer configs + app.mailer_from: '%%env(MAILER_FROM)%%' + env(MAILER_FROM): 'noreply@phplist.com' + app.mailer_dsn: '%%env(MAILER_DSN)%%' + env(MAILER_DSN): 'smtp://username:password@smtp.mailtrap.io:2525' + # A secret key that's used to generate certain security-related tokens secret: '%%env(PHPLIST_SECRET)%%' env(PHPLIST_SECRET): %1$s - - app.mailer_from: '%env(MAILER_FROM)%' - env(MAILER_FROM): 'noreply@phplist.com' - app.mailer_dsn: '%env(MAILER_DSN)%' - env(MAILER_DSN): 'smtp://username:password@smtp.mailtrap.io:2525' From 808f55b123526b33de35bab923cd61c313267068 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 29 May 2025 21:43:18 +0400 Subject: [PATCH 06/12] ISSUE-345: doc + params --- README.md | 13 +++ .../app.yml => services/parameters.yml} | 4 +- docs/ClassStructure.md | 2 +- docs/MailerTransports.md | 105 ++++++++++++++++++ 4 files changed, 121 insertions(+), 3 deletions(-) rename config/{packages/app.yml => services/parameters.yml} (92%) create mode 100644 docs/MailerTransports.md diff --git a/README.md b/README.md index f21c5cff..0b0e41b4 100755 --- a/README.md +++ b/README.md @@ -53,9 +53,11 @@ this code. ## Structure * [Class Docs][docs/phpdoc/] +* [Mailer Transports](docs/mailer-transports.md) - How to use different email providers (Gmail, Amazon SES, Mailchimp, SendGrid) * [Class structure overview](docs/ClassStructure.md) * [Graphic domain model](docs/DomainModel/DomainModel.svg) and a [description of the domain entities](docs/DomainModel/Entities.md) +* [Mailer Transports](docs/mailer-transports.md) - How to use different email providers (Gmail, Amazon SES, Mailchimp, SendGrid) ## Running the web server @@ -204,6 +206,17 @@ phpList module), please use the [REST API](https://github.com/phpList/rest-api). +## Email Configuration + +phpList supports multiple email transport providers through Symfony Mailer. The following transports are included: + +* Gmail +* Amazon SES +* Mailchimp Transactional (Mandrill) +* SendGrid + +For detailed configuration instructions, see the [Mailer Transports documentation](docs/mailer-transports.md). + ## Copyright phpList is copyright (C) 2000-2021 [phpList Ltd](https://www.phplist.com/). diff --git a/config/packages/app.yml b/config/services/parameters.yml similarity index 92% rename from config/packages/app.yml rename to config/services/parameters.yml index 61cf7460..6c944ede 100644 --- a/config/packages/app.yml +++ b/config/services/parameters.yml @@ -1,5 +1,5 @@ -app: - config: +parameters: + app.config: message_from_address: 'news@example.com' admin_address: 'admin@example.com' default_message_age: 15768000 diff --git a/docs/ClassStructure.md b/docs/ClassStructure.md index ff4da328..e7cf6801 100644 --- a/docs/ClassStructure.md +++ b/docs/ClassStructure.md @@ -21,7 +21,7 @@ database access code in these classes. ### Repository/ -These classes are reponsible for reading domain models from the database, +These classes are responsible for reading domain models from the database, for writing them there, and for other database queries. diff --git a/docs/MailerTransports.md b/docs/MailerTransports.md new file mode 100644 index 00000000..cde763da --- /dev/null +++ b/docs/MailerTransports.md @@ -0,0 +1,105 @@ +# Using Different Mailer Transports in phpList + +This document explains how to use the various mailer transports that are included in the phpList core dependencies: + +- Google Mailer (Gmail) +- Amazon SES +- Mailchimp Transactional (Mandrill) +- SendGrid + +## Configuration + +The phpList core uses Symfony Mailer for sending emails. The mailer transport is configured using the `MAILER_DSN` environment variable, which is defined in `config/parameters.yml`. + +## Available Transports + +### 1. Google Mailer (Gmail) + +To use Gmail as your email transport: + +``` +# Using Gmail with OAuth (recommended) +MAILER_DSN=gmail://USERNAME:APP_PASSWORD@default + +# Using Gmail with SMTP +MAILER_DSN=smtp://USERNAME:PASSWORD@smtp.gmail.com:587 +``` + +Notes: +- Replace `USERNAME` with your Gmail address +- For OAuth setup, follow [Symfony Gmail documentation](https://symfony.com/doc/current/mailer.html#using-gmail-to-send-emails) +- For the SMTP method, you may need to enable "Less secure app access" or use an App Password + +### 2. Amazon SES + +To use Amazon SES: + +``` +# Using API credentials +MAILER_DSN=ses://ACCESS_KEY:SECRET_KEY@default?region=REGION + +# Using SMTP interface +MAILER_DSN=smtp://USERNAME:PASSWORD@email-smtp.REGION.amazonaws.com:587 +``` + +Notes: +- Replace `ACCESS_KEY` and `SECRET_KEY` with your AWS credentials +- Replace `REGION` with your AWS region (e.g., us-east-1) +- For SMTP, use the credentials generated in the Amazon SES console + +### 3. Mailchimp Transactional (Mandrill) + +To use Mailchimp Transactional (formerly Mandrill): + +``` +MAILER_DSN=mandrill://API_KEY@default +``` + +Notes: +- Replace `API_KEY` with your Mailchimp Transactional API key +- You can find your API key in the Mailchimp Transactional (Mandrill) dashboard + +### 4. SendGrid + +To use SendGrid: + +``` +# Using API +MAILER_DSN=sendgrid://API_KEY@default + +# Using SMTP +MAILER_DSN=smtp://apikey:API_KEY@smtp.sendgrid.net:587 +``` + +Notes: +- Replace `API_KEY` with your SendGrid API key +- For SMTP, the username is literally "apikey" and the password is your actual API key + +## Testing Your Configuration + +After setting up your preferred mailer transport, you can test it using the built-in test command: + +```bash +bin/console app:send-test-email recipient@example.com +``` + +## Switching Between Transports + +You can easily switch between different mailer transports by changing the `MAILER_DSN` environment variable. This can be done in several ways: + +1. Edit the `config/parameters.yml` file directly +2. Set the environment variable in your server configuration +3. Set the environment variable before running a command: + ```bash + MAILER_DSN=sendgrid://API_KEY@default bin/console app:send-test-email recipient@example.com + ``` + +## Additional Configuration + +Some transports may require additional configuration options. Refer to the Symfony documentation for more details: + +- [Symfony Mailer Documentation](https://symfony.com/doc/current/mailer.html) +- [Gmail Transport](https://symfony.com/doc/current/mailer.html#using-gmail-to-send-emails) +- [Amazon SES Transport](https://symfony.com/doc/current/mailer.html#using-amazon-ses) +- [Mailchimp Transport](https://symfony.com/doc/current/mailer.html#using-mailchimp) +- [SendGrid Transport](https://symfony.com/doc/current/mailer.html#using-sendgrid) From 77e2e77de02cad060b1b50df359ef7d4b14ed082 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Thu, 29 May 2025 22:11:50 +0400 Subject: [PATCH 07/12] ISSUE-345: async emails --- config/config.yml | 1 + config/packages/messenger.yaml | 26 +++ config/services.yml | 5 + docs/AsyncEmailSending.md | 102 +++++++++++ .../Command/SendTestEmailCommand.php | 24 ++- .../Messaging/Message/AsyncEmailMessage.php | 58 ++++++ .../AsyncEmailMessageHandler.php | 37 ++++ src/Domain/Messaging/Service/EmailService.php | 85 ++++++++- .../Command/SendTestEmailCommandTest.php | 110 +++++++++++- .../Messaging/Service/EmailServiceTest.php | 166 +++++++++++++++++- 10 files changed, 583 insertions(+), 31 deletions(-) create mode 100644 config/packages/messenger.yaml create mode 100644 docs/AsyncEmailSending.md create mode 100644 src/Domain/Messaging/Message/AsyncEmailMessage.php create mode 100644 src/Domain/Messaging/MessageHandler/AsyncEmailMessageHandler.php diff --git a/config/config.yml b/config/config.yml index 93df3f5c..6875f2c9 100644 --- a/config/config.yml +++ b/config/config.yml @@ -2,6 +2,7 @@ imports: - { resource: services.yml } - { resource: doctrine.yml } - { resource: doctrine_migrations.yml } + - { resource: packages/*.yml } # Put parameters here that don't need to change on each machine where the app is deployed # https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration diff --git a/config/packages/messenger.yaml b/config/packages/messenger.yaml new file mode 100644 index 00000000..3ae2402d --- /dev/null +++ b/config/packages/messenger.yaml @@ -0,0 +1,26 @@ +# This file is the Symfony Messenger configuration for asynchronous processing +framework: + messenger: + # Uncomment this (and the failed transport below) to send failed messages to this transport for later handling. + # failure_transport: failed + + transports: + # https://symfony.com/doc/current/messenger.html#transport-configuration + async_email: + dsn: '%env(MESSENGER_TRANSPORT_DSN)%' + options: + auto_setup: true + use_notify: true + check_delayed_interval: 60000 + retry_strategy: + max_retries: 3 + # milliseconds delay + delay: 1000 + multiplier: 2 + max_delay: 0 + + # failed: 'doctrine://default?queue_name=failed' + + routing: + # Route your messages to the transports + 'PhpList\Core\Domain\Messaging\Message\AsyncEmailMessage': async_email diff --git a/config/services.yml b/config/services.yml index b83adce3..e3329d6c 100644 --- a/config/services.yml +++ b/config/services.yml @@ -37,6 +37,11 @@ services: public: true tags: [controller.service_arguments] + # Register message handlers for Symfony Messenger + PhpList\Core\Domain\Messaging\MessageHandler\: + resource: '../src/Domain/Messaging/MessageHandler' + tags: ['messenger.message_handler'] + doctrine.orm.metadata.annotation_reader: alias: doctrine.annotation_reader diff --git a/docs/AsyncEmailSending.md b/docs/AsyncEmailSending.md new file mode 100644 index 00000000..da4f247c --- /dev/null +++ b/docs/AsyncEmailSending.md @@ -0,0 +1,102 @@ +# Asynchronous Email Sending in phpList + +This document explains how to use the asynchronous email sending functionality in phpList. + +## Overview + +phpList now supports sending emails asynchronously using Symfony Messenger. This means that when you send an email, it is queued for delivery rather than being sent immediately. This has several benefits: + +1. **Improved Performance**: Your application doesn't have to wait for the email to be sent before continuing execution +2. **Better Reliability**: If the email server is temporarily unavailable, the message remains in the queue and will be retried automatically +3. **Scalability**: You can process the email queue separately from your main application, allowing for better resource management + +## Configuration + +The asynchronous email functionality is configured in `config/packages/messenger.yaml` and uses the `MESSENGER_TRANSPORT_DSN` environment variable defined in `config/parameters.yml`. + +By default, the system uses Doctrine (database) as the transport for queued messages: + +```yaml +env(MESSENGER_TRANSPORT_DSN): 'doctrine://default?auto_setup=true' +``` + +You can change this to use other transports supported by Symfony Messenger, such as: + +- **AMQP (RabbitMQ)**: `amqp://guest:guest@localhost:5672/%2f/messages` +- **Redis**: `redis://localhost:6379/messages` +- **In-Memory (for testing)**: `in-memory://` + +## Using Asynchronous Email Sending + +### Basic Usage + +The `EmailService` class now sends emails asynchronously by default: + +```php +// This will queue the email for sending +$emailService->sendEmail($email); +``` + +### Synchronous Sending + +If you need to send an email immediately (synchronously), you can use the `sendEmailSync` method: + +```php +// This will send the email immediately +$emailService->sendEmailSync($email); +``` + +### Bulk Emails + +For sending to multiple recipients: + +```php +// Asynchronous (queued) +$emailService->sendBulkEmail($recipients, $subject, $text, $html); + +// Synchronous (immediate) +$emailService->sendBulkEmailSync($recipients, $subject, $text, $html); +``` + +## Testing Email Sending + +You can test the email functionality using the built-in command: + +```bash +# Queue an email for asynchronous sending +bin/console app:send-test-email recipient@example.com + +# Send an email synchronously (immediately) +bin/console app:send-test-email recipient@example.com --sync +``` + +## Processing the Email Queue + +To process queued emails, you need to run the Symfony Messenger worker: + +```bash +bin/console messenger:consume async_email +``` + +For production environments, it's recommended to run this command as a background service or using a process manager like Supervisor. + +## Monitoring + +You can monitor the queue status using the following commands: + +```bash +# View the number of messages in the queue +bin/console messenger:stats + +# View failed messages +bin/console messenger:failed:show +``` + +## Troubleshooting + +If emails are not being sent: + +1. Make sure the messenger worker is running +2. Check for failed messages using `bin/console messenger:failed:show` +3. Verify your mailer configuration in `config/parameters.yml` +4. Try sending an email synchronously to test the mailer configuration diff --git a/src/Domain/Messaging/Command/SendTestEmailCommand.php b/src/Domain/Messaging/Command/SendTestEmailCommand.php index 9e9594da..ce0cbc3c 100644 --- a/src/Domain/Messaging/Command/SendTestEmailCommand.php +++ b/src/Domain/Messaging/Command/SendTestEmailCommand.php @@ -15,7 +15,7 @@ class SendTestEmailCommand extends Command { - protected static $defaultName = 'app:send-test-email'; + protected static $defaultName = 'phplist:test-email'; protected static $defaultDescription = 'Send a test email to verify email configuration'; private EmailService $emailService; @@ -30,7 +30,8 @@ protected function configure(): void { $this ->setDescription(self::$defaultDescription) - ->addArgument('recipient', InputArgument::OPTIONAL, 'Recipient email address'); + ->addArgument('recipient', InputArgument::OPTIONAL, 'Recipient email address') + ->addOption('sync', null, InputArgument::OPTIONAL, 'Send email synchronously instead of queuing it', false); } protected function execute(InputInterface $input, OutputInterface $output): int @@ -49,7 +50,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int } try { - $output->writeln('Sending test email to ' . $recipient); + $syncMode = $input->getOption('sync'); + + if ($syncMode) { + $output->writeln('Sending test email synchronously to ' . $recipient); + } else { + $output->writeln('Queuing test email for ' . $recipient); + } $email = (new Email()) ->from(new Address('admin@example.com', 'Admin Team')) @@ -57,9 +64,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int ->subject('Test Email from phpList') ->text('This is a test email sent from phpList Email Service.') ->html('

Test

This is a test email sent from phpList Email Service

'); - - $this->emailService->sendEmail($email); - $output->writeln('Test email sent successfully!'); + + if ($syncMode) { + $this->emailService->sendEmailSync($email); + $output->writeln('Test email sent successfully!'); + } else { + $this->emailService->sendEmail($email); + $output->writeln('Test email queued successfully! It will be sent asynchronously.'); + } return Command::SUCCESS; } catch (Exception $e) { diff --git a/src/Domain/Messaging/Message/AsyncEmailMessage.php b/src/Domain/Messaging/Message/AsyncEmailMessage.php new file mode 100644 index 00000000..0ea834ba --- /dev/null +++ b/src/Domain/Messaging/Message/AsyncEmailMessage.php @@ -0,0 +1,58 @@ +email = $email; + $this->cc = $cc; + $this->bcc = $bcc; + $this->replyTo = $replyTo; + $this->attachments = $attachments; + } + + public function getEmail(): Email + { + return $this->email; + } + + public function getCc(): array + { + return $this->cc; + } + + public function getBcc(): array + { + return $this->bcc; + } + + public function getReplyTo(): array + { + return $this->replyTo; + } + + public function getAttachments(): array + { + return $this->attachments; + } +} diff --git a/src/Domain/Messaging/MessageHandler/AsyncEmailMessageHandler.php b/src/Domain/Messaging/MessageHandler/AsyncEmailMessageHandler.php new file mode 100644 index 00000000..42d91417 --- /dev/null +++ b/src/Domain/Messaging/MessageHandler/AsyncEmailMessageHandler.php @@ -0,0 +1,37 @@ +emailService = $emailService; + } + + /** + * Process an asynchronous email message by sending the email + */ + public function __invoke(AsyncEmailMessage $message): void + { + $this->emailService->sendEmailSync( + $message->getEmail(), + $message->getCc(), + $message->getBcc(), + $message->getReplyTo(), + $message->getAttachments() + ); + } +} diff --git a/src/Domain/Messaging/Service/EmailService.php b/src/Domain/Messaging/Service/EmailService.php index 8a97eeb0..c3c3fc30 100644 --- a/src/Domain/Messaging/Service/EmailService.php +++ b/src/Domain/Messaging/Service/EmailService.php @@ -4,8 +4,10 @@ namespace PhpList\Core\Domain\Messaging\Service; +use PhpList\Core\Domain\Messaging\Message\AsyncEmailMessage; use Symfony\Component\Mailer\Exception\TransportExceptionInterface; use Symfony\Component\Mailer\MailerInterface; +use Symfony\Component\Messenger\MessageBusInterface; use Symfony\Component\Mime\Email; use Symfony\Component\Mime\Address; @@ -13,15 +15,20 @@ class EmailService { private MailerInterface $mailer; private string $defaultFromEmail; + private MessageBusInterface $messageBus; - public function __construct(MailerInterface $mailer, string $defaultFromEmail) - { + public function __construct( + MailerInterface $mailer, + string $defaultFromEmail, + MessageBusInterface $messageBus + ) { $this->mailer = $mailer; $this->defaultFromEmail = $defaultFromEmail; + $this->messageBus = $messageBus; } /** - * Send a simple email + * Send a simple email asynchronously * * @param Email $email * @param array $cc @@ -29,7 +36,6 @@ public function __construct(MailerInterface $mailer, string $defaultFromEmail) * @param array $replyTo * @param array $attachments * @return void - * @throws TransportExceptionInterface */ public function sendEmail( Email $email, @@ -41,7 +47,33 @@ public function sendEmail( if (count($email->getFrom()) === 0) { $email->from($this->defaultFromEmail); } - + + $message = new AsyncEmailMessage($email, $cc, $bcc, $replyTo, $attachments); + $this->messageBus->dispatch($message); + } + + /** + * Send a simple email synchronously + * + * @param Email $email + * @param array $cc + * @param array $bcc + * @param array $replyTo + * @param array $attachments + * @return void + * @throws TransportExceptionInterface + */ + public function sendEmailSync( + Email $email, + array $cc = [], + array $bcc = [], + array $replyTo = [], + array $attachments = [] + ): void { + if (count($email->getFrom()) === 0) { + $email->from($this->defaultFromEmail); + } + foreach ($cc as $ccAddress) { $email->addCc($ccAddress); } @@ -62,7 +94,7 @@ public function sendEmail( } /** - * Email multiple recipients + * Email multiple recipients asynchronously * * @param array $toAddresses Array of recipient email addresses * @param string $subject Email subject @@ -73,7 +105,6 @@ public function sendEmail( * @param array $attachments Array of file paths to attach (optional) * * @return void - * @throws TransportExceptionInterface */ public function sendBulkEmail( array $toAddresses, @@ -100,4 +131,44 @@ public function sendBulkEmail( $this->sendEmail($email, [], [], [], $attachments); } } + + /** + * Email multiple recipients synchronously + * + * @param array $toAddresses Array of recipient email addresses + * @param string $subject Email subject + * @param string $text Plain text content + * @param string $html HTML content (optional) + * @param string|null $from Sender email address (optional, uses default if not provided) + * @param string|null $fromName Sender name (optional) + * @param array $attachments Array of file paths to attach (optional) + * + * @return void + * @throws TransportExceptionInterface + */ + public function sendBulkEmailSync( + array $toAddresses, + string $subject, + string $text, + string $html = '', + ?string $from = null, + ?string $fromName = null, + array $attachments = [] + ): void { + $baseEmail = (new Email()) + ->subject($subject) + ->text($text) + ->html($html); + + if ($from) { + $baseEmail->from($fromName ? new Address($from, $fromName) : $from); + } + + foreach ($toAddresses as $recipient) { + $email = clone $baseEmail; + $email->to($recipient); + + $this->sendEmailSync($email, [], [], [], $attachments); + } + } } diff --git a/tests/Unit/Domain/Messaging/Command/SendTestEmailCommandTest.php b/tests/Unit/Domain/Messaging/Command/SendTestEmailCommandTest.php index a8863a31..c1b4a92c 100644 --- a/tests/Unit/Domain/Messaging/Command/SendTestEmailCommandTest.php +++ b/tests/Unit/Domain/Messaging/Command/SendTestEmailCommandTest.php @@ -21,10 +21,10 @@ protected function setUp(): void { $this->emailService = $this->createMock(EmailService::class); $command = new SendTestEmailCommand($this->emailService); - + $application = new Application(); $application->add($command); - + $this->commandTester = new CommandTester($command); } @@ -36,16 +36,16 @@ public function testExecuteWithValidEmail(): void $this->assertEquals('Test Email from phpList', $email->getSubject()); $this->assertStringContainsString('This is a test email', $email->getTextBody()); $this->assertStringContainsString('

Test

', $email->getHtmlBody()); - + $toAddresses = $email->getTo(); $this->assertCount(1, $toAddresses); $this->assertEquals('test@example.com', $toAddresses[0]->getAddress()); - + $fromAddresses = $email->getFrom(); $this->assertCount(1, $fromAddresses); $this->assertEquals('admin@example.com', $fromAddresses[0]->getAddress()); $this->assertEquals('Admin Team', $fromAddresses[0]->getName()); - + return true; })); @@ -54,8 +54,43 @@ public function testExecuteWithValidEmail(): void ]); $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Queuing test email for', $output); + $this->assertStringContainsString('Test email queued successfully', $output); + $this->assertStringContainsString('It will be sent asynchronously', $output); + + $this->assertEquals(0, $this->commandTester->getStatusCode()); + } + + public function testExecuteWithValidEmailSync(): void + { + $this->emailService->expects($this->once()) + ->method('sendEmailSync') + ->with($this->callback(function (Email $email) { + $this->assertEquals('Test Email from phpList', $email->getSubject()); + $this->assertStringContainsString('This is a test email', $email->getTextBody()); + $this->assertStringContainsString('

Test

', $email->getHtmlBody()); + + $toAddresses = $email->getTo(); + $this->assertCount(1, $toAddresses); + $this->assertEquals('test@example.com', $toAddresses[0]->getAddress()); + + $fromAddresses = $email->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals('admin@example.com', $fromAddresses[0]->getAddress()); + $this->assertEquals('Admin Team', $fromAddresses[0]->getName()); + + return true; + })); + + $this->commandTester->execute([ + 'recipient' => 'test@example.com', + '--sync' => true, + ]); + + $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Sending test email synchronously to', $output); $this->assertStringContainsString('Test email sent successfully', $output); - + $this->assertEquals(0, $this->commandTester->getStatusCode()); } @@ -63,12 +98,31 @@ public function testExecuteWithoutRecipient(): void { $this->emailService->expects($this->never()) ->method('sendEmail'); + $this->emailService->expects($this->never()) + ->method('sendEmailSync'); $this->commandTester->execute([]); $output = $this->commandTester->getDisplay(); $this->assertStringContainsString('Recipient email address not provided', $output); - + + $this->assertEquals(1, $this->commandTester->getStatusCode()); + } + + public function testExecuteWithoutRecipientSync(): void + { + $this->emailService->expects($this->never()) + ->method('sendEmail'); + $this->emailService->expects($this->never()) + ->method('sendEmailSync'); + + $this->commandTester->execute([ + '--sync' => true, + ]); + + $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Recipient email address not provided', $output); + $this->assertEquals(1, $this->commandTester->getStatusCode()); } @@ -76,14 +130,34 @@ public function testExecuteWithInvalidEmail(): void { $this->emailService->expects($this->never()) ->method('sendEmail'); + $this->emailService->expects($this->never()) + ->method('sendEmailSync'); + + $this->commandTester->execute([ + 'recipient' => 'invalid-email', + ]); + + $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Invalid email address', $output); + + $this->assertEquals(1, $this->commandTester->getStatusCode()); + } + + public function testExecuteWithInvalidEmailSync(): void + { + $this->emailService->expects($this->never()) + ->method('sendEmail'); + $this->emailService->expects($this->never()) + ->method('sendEmailSync'); $this->commandTester->execute([ 'recipient' => 'invalid-email', + '--sync' => true, ]); $output = $this->commandTester->getDisplay(); $this->assertStringContainsString('Invalid email address', $output); - + $this->assertEquals(1, $this->commandTester->getStatusCode()); } @@ -100,7 +174,25 @@ public function testExecuteWithEmailServiceException(): void $output = $this->commandTester->getDisplay(); $this->assertStringContainsString('Failed to send test email', $output); $this->assertStringContainsString('Test exception', $output); - + + $this->assertEquals(1, $this->commandTester->getStatusCode()); + } + + public function testExecuteWithEmailServiceExceptionSync(): void + { + $this->emailService->expects($this->once()) + ->method('sendEmailSync') + ->willThrowException(new \Exception('Test sync exception')); + + $this->commandTester->execute([ + 'recipient' => 'test@example.com', + '--sync' => true, + ]); + + $output = $this->commandTester->getDisplay(); + $this->assertStringContainsString('Failed to send test email', $output); + $this->assertStringContainsString('Test sync exception', $output); + $this->assertEquals(1, $this->commandTester->getStatusCode()); } } diff --git a/tests/Unit/Domain/Messaging/Service/EmailServiceTest.php b/tests/Unit/Domain/Messaging/Service/EmailServiceTest.php index c7f5fcd8..9409320b 100644 --- a/tests/Unit/Domain/Messaging/Service/EmailServiceTest.php +++ b/tests/Unit/Domain/Messaging/Service/EmailServiceTest.php @@ -4,25 +4,51 @@ namespace PhpList\Core\Tests\Unit\Domain\Messaging\Service; +use PhpList\Core\Domain\Messaging\Message\AsyncEmailMessage; use PhpList\Core\Domain\Messaging\Service\EmailService; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Mailer\MailerInterface; +use Symfony\Component\Messenger\Envelope; +use Symfony\Component\Messenger\MessageBusInterface; use Symfony\Component\Mime\Email; class EmailServiceTest extends TestCase { private EmailService $emailService; private MailerInterface&MockObject $mailer; + private MessageBusInterface&MockObject $messageBus; private string $defaultFromEmail = 'default@example.com'; protected function setUp(): void { $this->mailer = $this->createMock(MailerInterface::class); - $this->emailService = new EmailService($this->mailer, $this->defaultFromEmail); + $this->messageBus = $this->createMock(MessageBusInterface::class); + $this->emailService = new EmailService($this->mailer, $this->defaultFromEmail, $this->messageBus); } public function testSendEmailWithDefaultFrom(): void + { + $email = (new Email()) + ->to('recipient@example.com') + ->subject('Test Subject') + ->text('Test Content'); + + $this->messageBus->expects($this->once()) + ->method('dispatch') + ->with($this->callback(function (AsyncEmailMessage $message) { + $sentEmail = $message->getEmail(); + $fromAddresses = $sentEmail->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals($this->defaultFromEmail, $fromAddresses[0]->getAddress()); + return true; + })) + ->willReturn(new Envelope(new AsyncEmailMessage($email))); + + $this->emailService->sendEmail($email); + } + + public function testSendEmailSyncWithDefaultFrom(): void { $email = (new Email()) ->to('recipient@example.com') @@ -38,10 +64,33 @@ public function testSendEmailWithDefaultFrom(): void return true; })); - $this->emailService->sendEmail($email); + $this->emailService->sendEmailSync($email); } public function testSendEmailWithCustomFrom(): void + { + $customFrom = 'custom@example.com'; + $email = (new Email()) + ->from($customFrom) + ->to('recipient@example.com') + ->subject('Test Subject') + ->text('Test Content'); + + $this->messageBus->expects($this->once()) + ->method('dispatch') + ->with($this->callback(function (AsyncEmailMessage $message) use ($customFrom) { + $sentEmail = $message->getEmail(); + $fromAddresses = $sentEmail->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals($customFrom, $fromAddresses[0]->getAddress()); + return true; + })) + ->willReturn(new Envelope(new AsyncEmailMessage($email))); + + $this->emailService->sendEmail($email); + } + + public function testSendEmailSyncWithCustomFrom(): void { $customFrom = 'custom@example.com'; $email = (new Email()) @@ -59,7 +108,7 @@ public function testSendEmailWithCustomFrom(): void return true; })); - $this->emailService->sendEmail($email); + $this->emailService->sendEmailSync($email); } public function testSendEmailWithCcBccAndReplyTo(): void @@ -73,6 +122,30 @@ public function testSendEmailWithCcBccAndReplyTo(): void $bcc = ['bcc@example.com']; $replyTo = ['reply@example.com']; + $this->messageBus->expects($this->once()) + ->method('dispatch') + ->with($this->callback(function (AsyncEmailMessage $message) use ($cc, $bcc, $replyTo) { + $this->assertEquals($cc, $message->getCc()); + $this->assertEquals($bcc, $message->getBcc()); + $this->assertEquals($replyTo, $message->getReplyTo()); + return true; + })) + ->willReturn(new Envelope(new AsyncEmailMessage($email))); + + $this->emailService->sendEmail($email, $cc, $bcc, $replyTo); + } + + public function testSendEmailSyncWithCcBccAndReplyTo(): void + { + $email = (new Email()) + ->to('recipient@example.com') + ->subject('Test Subject') + ->text('Test Content'); + + $cc = ['cc@example.com']; + $bcc = ['bcc@example.com']; + $replyTo = ['reply@example.com']; + $this->mailer->expects($this->once()) ->method('send') ->with($this->callback(function (Email $sentEmail) use ($cc, $bcc, $replyTo) { @@ -92,7 +165,7 @@ public function testSendEmailWithCcBccAndReplyTo(): void return true; })); - $this->emailService->sendEmail($email, $cc, $bcc, $replyTo); + $this->emailService->sendEmailSync($email, $cc, $bcc, $replyTo); } public function testSendEmailWithAttachments(): void @@ -104,10 +177,30 @@ public function testSendEmailWithAttachments(): void $attachments = ['/path/to/attachment.pdf']; + $this->messageBus->expects($this->once()) + ->method('dispatch') + ->with($this->callback(function (AsyncEmailMessage $message) use ($attachments) { + $this->assertEquals($attachments, $message->getAttachments()); + return true; + })) + ->willReturn(new Envelope(new AsyncEmailMessage($email))); + + $this->emailService->sendEmail($email, [], [], [], $attachments); + } + + public function testSendEmailSyncWithAttachments(): void + { + $email = (new Email()) + ->to('recipient@example.com') + ->subject('Test Subject') + ->text('Test Content'); + + $attachments = ['/path/to/attachment.pdf']; + $this->mailer->expects($this->once()) ->method('send'); - $this->emailService->sendEmail($email, [], [], [], $attachments); + $this->emailService->sendEmailSync($email, [], [], [], $attachments); } public function testSendBulkEmail(): void @@ -119,22 +212,57 @@ public function testSendBulkEmail(): void $from = 'sender@example.com'; $fromName = 'Sender Name'; + $this->messageBus->expects($this->exactly(count($recipients))) + ->method('dispatch') + ->with($this->callback(function (AsyncEmailMessage $message) use ( + $subject, + $text, + $html, + $from, + $fromName + ) { + $sentEmail = $message->getEmail(); + $this->assertEquals($subject, $sentEmail->getSubject()); + $this->assertEquals($text, $sentEmail->getTextBody()); + $this->assertEquals($html, $sentEmail->getHtmlBody()); + + $fromAddresses = $sentEmail->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals($from, $fromAddresses[0]->getAddress()); + $this->assertEquals($fromName, $fromAddresses[0]->getName()); + + return true; + })) + ->willReturn(new Envelope($this->createMock(AsyncEmailMessage::class))); + + $this->emailService->sendBulkEmail($recipients, $subject, $text, $html, $from, $fromName); + } + + public function testSendBulkEmailSync(): void + { + $recipients = ['user1@example.com', 'user2@example.com', 'user3@example.com']; + $subject = 'Bulk Test Subject'; + $text = 'Bulk Test Content'; + $html = '

Bulk Test HTML Content

'; + $from = 'sender@example.com'; + $fromName = 'Sender Name'; + $this->mailer->expects($this->exactly(count($recipients))) ->method('send') ->with($this->callback(function (Email $sentEmail) use ($subject, $text, $html, $from, $fromName) { $this->assertEquals($subject, $sentEmail->getSubject()); $this->assertEquals($text, $sentEmail->getTextBody()); $this->assertEquals($html, $sentEmail->getHtmlBody()); - + $fromAddresses = $sentEmail->getFrom(); $this->assertCount(1, $fromAddresses); $this->assertEquals($from, $fromAddresses[0]->getAddress()); $this->assertEquals($fromName, $fromAddresses[0]->getName()); - + return true; })); - $this->emailService->sendBulkEmail($recipients, $subject, $text, $html, $from, $fromName); + $this->emailService->sendBulkEmailSync($recipients, $subject, $text, $html, $from, $fromName); } public function testSendBulkEmailWithDefaultFrom(): void @@ -143,6 +271,26 @@ public function testSendBulkEmailWithDefaultFrom(): void $subject = 'Bulk Test Subject'; $text = 'Bulk Test Content'; + $this->messageBus->expects($this->exactly(count($recipients))) + ->method('dispatch') + ->with($this->callback(function (AsyncEmailMessage $message) { + $sentEmail = $message->getEmail(); + $fromAddresses = $sentEmail->getFrom(); + $this->assertCount(1, $fromAddresses); + $this->assertEquals($this->defaultFromEmail, $fromAddresses[0]->getAddress()); + return true; + })) + ->willReturn(new Envelope($this->createMock(AsyncEmailMessage::class))); + + $this->emailService->sendBulkEmail($recipients, $subject, $text); + } + + public function testSendBulkEmailSyncWithDefaultFrom(): void + { + $recipients = ['user1@example.com', 'user2@example.com']; + $subject = 'Bulk Test Subject'; + $text = 'Bulk Test Content'; + $this->mailer->expects($this->exactly(count($recipients))) ->method('send') ->with($this->callback(function (Email $sentEmail) { @@ -152,6 +300,6 @@ public function testSendBulkEmailWithDefaultFrom(): void return true; })); - $this->emailService->sendBulkEmail($recipients, $subject, $text); + $this->emailService->sendBulkEmailSync($recipients, $subject, $text); } } From 12fb0a0bada14ccb028c132fcd7181863072631b Mon Sep 17 00:00:00 2001 From: Tatevik Date: Sun, 8 Jun 2025 13:26:47 +0400 Subject: [PATCH 08/12] fix admin/token relation --- src/Domain/Identity/Model/AdministratorToken.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Domain/Identity/Model/AdministratorToken.php b/src/Domain/Identity/Model/AdministratorToken.php index 41ff75aa..1a6c511f 100644 --- a/src/Domain/Identity/Model/AdministratorToken.php +++ b/src/Domain/Identity/Model/AdministratorToken.php @@ -43,7 +43,7 @@ class AdministratorToken implements DomainModel, Identity, CreationDate private string $key = ''; #[ORM\ManyToOne(targetEntity: Administrator::class)] - #[ORM\JoinColumn(name: 'adminid')] + #[ORM\JoinColumn(name: 'adminid', referencedColumnName: 'id', onDelete: 'CASCADE')] private ?Administrator $administrator = null; public function __construct() From ecfe93fefa9c5e295a2a31ac548a224416e7c6be Mon Sep 17 00:00:00 2001 From: Tatevik Date: Sun, 8 Jun 2025 16:31:36 +0400 Subject: [PATCH 09/12] remove twig from dependencies --- composer.json | 1 - 1 file changed, 1 deletion(-) diff --git a/composer.json b/composer.json index 0fd65a52..6049237a 100644 --- a/composer.json +++ b/composer.json @@ -65,7 +65,6 @@ "symfony/amazon-mailer": "^6.4", "symfony/mailchimp-mailer": "^6.4", "symfony/sendgrid-mailer": "^6.4", - "symfony/twig-bundle": "^6.4", "symfony/messenger": "^6.4" }, "require-dev": { From afa50f4dd2b6825e894a346ca6873198e0cccf85 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Sun, 8 Jun 2025 19:24:57 +0400 Subject: [PATCH 10/12] configure twig --- composer.json | 2 ++ config/config.yml | 1 - config/packages/twig.yaml | 4 ++++ src/Core/ApplicationKernel.php | 1 + 4 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 config/packages/twig.yaml diff --git a/composer.json b/composer.json index 6049237a..7f56c174 100644 --- a/composer.json +++ b/composer.json @@ -65,6 +65,7 @@ "symfony/amazon-mailer": "^6.4", "symfony/mailchimp-mailer": "^6.4", "symfony/sendgrid-mailer": "^6.4", + "symfony/twig-bundle": "^6.4", "symfony/messenger": "^6.4" }, "require-dev": { @@ -133,6 +134,7 @@ "bundles": [ "Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle", "Symfony\\Bundle\\MonologBundle\\MonologBundle", + "Symfony\\Bundle\\TwigBundle\\TwigBundle", "Doctrine\\Bundle\\DoctrineBundle\\DoctrineBundle", "Doctrine\\Bundle\\MigrationsBundle\\DoctrineMigrationsBundle", "PhpList\\Core\\EmptyStartPageBundle\\EmptyStartPageBundle" diff --git a/config/config.yml b/config/config.yml index 6875f2c9..93df3f5c 100644 --- a/config/config.yml +++ b/config/config.yml @@ -2,7 +2,6 @@ imports: - { resource: services.yml } - { resource: doctrine.yml } - { resource: doctrine_migrations.yml } - - { resource: packages/*.yml } # Put parameters here that don't need to change on each machine where the app is deployed # https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration diff --git a/config/packages/twig.yaml b/config/packages/twig.yaml new file mode 100644 index 00000000..d5320edd --- /dev/null +++ b/config/packages/twig.yaml @@ -0,0 +1,4 @@ +twig: + debug: '%kernel.debug%' + strict_variables: '%kernel.debug%' + default_path: 'test/templates' diff --git a/src/Core/ApplicationKernel.php b/src/Core/ApplicationKernel.php index 1d3c64ab..042b48d0 100644 --- a/src/Core/ApplicationKernel.php +++ b/src/Core/ApplicationKernel.php @@ -122,6 +122,7 @@ public function registerContainerConfiguration(LoaderInterface $loader): void $loader->load($this->getApplicationDir() . '/config/parameters.yml'); $loader->load($this->getRootDir() . '/config/config_' . $this->getEnvironment() . '.yml'); $loader->load($this->getApplicationDir() . '/config/config_modules.yml'); + $loader->load($this->getApplicationDir() . '/config/packages/twig.yaml'); } /** From a862f61e021a9b3c8e339619581f4a44793fc476 Mon Sep 17 00:00:00 2001 From: Tatevik Date: Sun, 8 Jun 2025 20:12:32 +0400 Subject: [PATCH 11/12] remove twig --- config/packages/twig.yaml | 4 ---- src/Core/ApplicationKernel.php | 6 +++++- 2 files changed, 5 insertions(+), 5 deletions(-) delete mode 100644 config/packages/twig.yaml diff --git a/config/packages/twig.yaml b/config/packages/twig.yaml deleted file mode 100644 index d5320edd..00000000 --- a/config/packages/twig.yaml +++ /dev/null @@ -1,4 +0,0 @@ -twig: - debug: '%kernel.debug%' - strict_variables: '%kernel.debug%' - default_path: 'test/templates' diff --git a/src/Core/ApplicationKernel.php b/src/Core/ApplicationKernel.php index 042b48d0..97249b45 100644 --- a/src/Core/ApplicationKernel.php +++ b/src/Core/ApplicationKernel.php @@ -122,7 +122,11 @@ public function registerContainerConfiguration(LoaderInterface $loader): void $loader->load($this->getApplicationDir() . '/config/parameters.yml'); $loader->load($this->getRootDir() . '/config/config_' . $this->getEnvironment() . '.yml'); $loader->load($this->getApplicationDir() . '/config/config_modules.yml'); - $loader->load($this->getApplicationDir() . '/config/packages/twig.yaml'); + + $twigConfigFile = $this->getApplicationDir() . '/config/packages/twig.yaml'; + if (file_exists($twigConfigFile)) { + $loader->load($twigConfigFile); + } } /** From 848efae4639cbdd8eace58097cc7058606507fce Mon Sep 17 00:00:00 2001 From: Tatevik Date: Mon, 9 Jun 2025 11:42:25 +0400 Subject: [PATCH 12/12] ISSUE-345: config manager --- config/services/managers.yml | 4 + config/services/parameters.yml | 1 + config/services/repositories.yml | 5 + .../Exception/ConfigNotEditableException.php | 15 ++ src/Domain/Configuration/Model/Config.php | 12 +- .../Service/Manager/ConfigManager.php | 67 ++++++++ .../Service/Manager/ConfigManagerTest.php | 146 ++++++++++++++++++ 7 files changed, 244 insertions(+), 6 deletions(-) create mode 100644 src/Domain/Configuration/Exception/ConfigNotEditableException.php create mode 100644 src/Domain/Configuration/Service/Manager/ConfigManager.php create mode 100644 tests/Unit/Domain/Configuration/Service/Manager/ConfigManagerTest.php diff --git a/config/services/managers.yml b/config/services/managers.yml index eaa37758..41284f2c 100644 --- a/config/services/managers.yml +++ b/config/services/managers.yml @@ -67,3 +67,7 @@ services: autoconfigure: true arguments: $defaultFromEmail: '%app.mailer_from%' + + PhpList\Core\Domain\Configuration\Service\Manager\ConfigManager: + autowire: true + autoconfigure: true diff --git a/config/services/parameters.yml b/config/services/parameters.yml index 6c944ede..ebf1d99b 100644 --- a/config/services/parameters.yml +++ b/config/services/parameters.yml @@ -8,3 +8,4 @@ parameters: notify_start_default: 'start@example.com' notify_end_default: 'end@example.com' always_add_google_tracking: true + click_track: true diff --git a/config/services/repositories.yml b/config/services/repositories.yml index 21ce7114..44911f64 100644 --- a/config/services/repositories.yml +++ b/config/services/repositories.yml @@ -60,3 +60,8 @@ services: parent: PhpList\Core\Domain\Common\Repository\AbstractRepository arguments: - PhpList\Core\Domain\Messaging\Model\TemplateImage + + PhpList\Core\Domain\Configuration\Repository\ConfigRepository: + parent: PhpList\Core\Domain\Common\Repository\AbstractRepository + arguments: + - PhpList\Core\Domain\Configuration\Model\Config diff --git a/src/Domain/Configuration/Exception/ConfigNotEditableException.php b/src/Domain/Configuration/Exception/ConfigNotEditableException.php new file mode 100644 index 00000000..eb0ed456 --- /dev/null +++ b/src/Domain/Configuration/Exception/ConfigNotEditableException.php @@ -0,0 +1,15 @@ +item; + return $this->key; } - public function setItem(string $item): self + public function setKey(string $key): self { - $this->item = $item; + $this->key = $key; return $this; } diff --git a/src/Domain/Configuration/Service/Manager/ConfigManager.php b/src/Domain/Configuration/Service/Manager/ConfigManager.php new file mode 100644 index 00000000..cae380be --- /dev/null +++ b/src/Domain/Configuration/Service/Manager/ConfigManager.php @@ -0,0 +1,67 @@ +configRepository = $configRepository; + } + + /** + * Get a configuration item by its key + */ + public function getByItem(string $item): ?Config + { + return $this->configRepository->findOneBy(['item' => $item]); + } + + /** + * Get all configuration items + * + * @return Config[] + */ + public function getAll(): array + { + return $this->configRepository->findAll(); + } + + /** + * Update a configuration item + * @throws ConfigNotEditableException + */ + public function update(Config $config, string $value): void + { + if (!$config->isEditable()) { + throw new ConfigNotEditableException($config->getKey()); + } + $config->setValue($value); + + $this->configRepository->save($config); + } + + public function create(string $key, string $value, bool $editable, ?string $type = null): void + { + $config = (new Config()) + ->setKey($key) + ->setValue($value) + ->setEditable($editable) + ->setType($type); + + $this->configRepository->save($config); + } + + public function delete(Config $config): void + { + $this->configRepository->remove($config); + } +} diff --git a/tests/Unit/Domain/Configuration/Service/Manager/ConfigManagerTest.php b/tests/Unit/Domain/Configuration/Service/Manager/ConfigManagerTest.php new file mode 100644 index 00000000..3b14122b --- /dev/null +++ b/tests/Unit/Domain/Configuration/Service/Manager/ConfigManagerTest.php @@ -0,0 +1,146 @@ +createMock(ConfigRepository::class); + $manager = new ConfigManager($configRepository); + + $config = new Config(); + $config->setKey('test_item'); + $config->setValue('test_value'); + + $configRepository->expects($this->once()) + ->method('findOneBy') + ->with(['item' => 'test_item']) + ->willReturn($config); + + $result = $manager->getByItem('test_item'); + + $this->assertSame($config, $result); + $this->assertSame('test_item', $result->getKey()); + $this->assertSame('test_value', $result->getValue()); + } + + public function testGetAllReturnsAllConfigsFromRepository(): void + { + $configRepository = $this->createMock(ConfigRepository::class); + $manager = new ConfigManager($configRepository); + + $config1 = new Config(); + $config1->setKey('item1'); + $config1->setValue('value1'); + + $config2 = new Config(); + $config2->setKey('item2'); + $config2->setValue('value2'); + + $configs = [$config1, $config2]; + + $configRepository->expects($this->once()) + ->method('findAll') + ->willReturn($configs); + + $result = $manager->getAll(); + + $this->assertSame($configs, $result); + $this->assertCount(2, $result); + $this->assertSame('item1', $result[0]->getKey()); + $this->assertSame('value1', $result[0]->getValue()); + $this->assertSame('item2', $result[1]->getKey()); + $this->assertSame('value2', $result[1]->getValue()); + } + + public function testUpdateSavesConfigToRepository(): void + { + $configRepository = $this->createMock(ConfigRepository::class); + $manager = new ConfigManager($configRepository); + + $config = new Config(); + $config->setKey('test_item'); + $config->setValue('test_value'); + $config->setEditable(true); + + $configRepository->expects($this->once()) + ->method('save') + ->with($config); + + $manager->update($config, 'new_value'); + } + + public function testCreateSavesNewConfigToRepository(): void + { + $configRepository = $this->createMock(ConfigRepository::class); + $manager = new ConfigManager($configRepository); + + $configRepository->expects($this->once()) + ->method('save') + ->with($this->callback(function (Config $config) { + return $config->getKey() === 'test_key' && + $config->getValue() === 'test_value' && + $config->isEditable() === true && + $config->getType() === 'test_type'; + })); + + $manager->create('test_key', 'test_value', true, 'test_type'); + } + public function testGetByItemReturnsNullWhenItemDoesNotExist(): void + { + $configRepository = $this->createMock(ConfigRepository::class); + $manager = new ConfigManager($configRepository); + + $configRepository->expects($this->once()) + ->method('findOneBy') + ->with(['item' => 'non_existent_item']) + ->willReturn(null); + + $result = $manager->getByItem('non_existent_item'); + + $this->assertNull($result); + } + + public function testUpdateThrowsExceptionWhenConfigIsNotEditable(): void + { + $configRepository = $this->createMock(ConfigRepository::class); + $manager = new ConfigManager($configRepository); + + $config = new Config(); + $config->setKey('test_item'); + $config->setValue('test_value'); + $config->setEditable(false); + + $configRepository->expects($this->never()) + ->method('save'); + + $this->expectException(\PhpList\Core\Domain\Configuration\Exception\ConfigNotEditableException::class); + $this->expectExceptionMessage('Configuration item "test_item" is not editable.'); + + $manager->update($config, 'new_value'); + } + + public function testDeleteRemovesConfigFromRepository(): void + { + $configRepository = $this->createMock(ConfigRepository::class); + $manager = new ConfigManager($configRepository); + + $config = new Config(); + $config->setKey('test_item'); + $config->setValue('test_value'); + + $configRepository->expects($this->once()) + ->method('remove') + ->with($config); + + $manager->delete($config); + } +}