Skip to content
This repository has been archived by the owner on Feb 6, 2022. It is now read-only.

Commit

Permalink
merged branch jeremyFreeAgent/feature/mailers (PR #34)
Browse files Browse the repository at this point in the history
This PR was merged into the master branch.

Discussion
----------

Added mailers

Now you can configure several mailers.

Commits
-------

cf5de43 Added mailers
  • Loading branch information
fabpot committed Jul 19, 2013
2 parents 5573e11 + cf5de43 commit 69d6c36
Show file tree
Hide file tree
Showing 31 changed files with 1,087 additions and 300 deletions.
145 changes: 145 additions & 0 deletions Command/DebugCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SwiftmailerBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
* A console command for retrieving information about mailers
*
* @author Jérémy Romey <jeremy@free-agent.fr>
*/
class DebugCommand extends ContainerAwareCommand
{
/**
* @see Command
*/
protected function configure()
{
$this
->setName('swiftmailer:debug')
->setDefinition(array(
new InputArgument('name', InputArgument::OPTIONAL, 'A mailer name'),
))
->setDescription('Displays current mailers for an application')
->setHelp(<<<EOF
The <info>%command.name%</info> displays the configured mailers:
<info>php %command.full_name% mailer-name</info>
EOF
)
;
}

/**
* @see Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');

if ($name) {
$this->outputMailer($output, $name);
} else {
$this->outputMailers($output);
}
}

protected function outputMailers(OutputInterface $output, $routes = null)
{
$output->writeln($this->getHelper('formatter')->formatSection('swiftmailer', 'Current mailers'));

$maxName = strlen('name');
$maxTransport = strlen('transport');
$maxSpool = strlen('spool');
$maxDelivery = strlen('delivery');
$maxSingleAddress = strlen('single address');

$mailers = $this->getContainer()->getParameter('swiftmailer.mailers');
foreach ($mailers as $name => $mailer) {
$mailer = $this->getContainer()->get($mailer);
$transport = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.transport.name', $name));
$spool = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.spool.enabled', $name)) ? 'YES' : 'NO';
$delivery = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.delivery.enabled', $name)) ? 'YES' : 'NO';
$singleAddress = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.single_address', $name));

if ($this->isDefaultMailer($name)) {
$name = sprintf('%s (default mailer)', $name);
}
$maxName = max($maxName, strlen($name));
$maxTransport = max($maxTransport, strlen($transport));
$maxSpool = max($maxSpool, strlen($spool));
$maxDelivery = max($maxDelivery, strlen($delivery));
$maxSingleAddress = max($maxSingleAddress, strlen($singleAddress));
}
$format = '%-'.$maxName.'s %-'.$maxTransport.'s %-'.$maxSpool.'s %-'.$maxDelivery.'s %-'.$maxSingleAddress.'s';

$format1 = '%-'.($maxName + 19).'s %-'.($maxTransport + 19).'s %-'.($maxSpool + 19).'s %-'.($maxDelivery + 19).'s %-'.($maxSingleAddress + 19).'s';
$output->writeln(sprintf($format1, '<comment>Name</comment>', '<comment>Transport</comment>', '<comment>Spool</comment>', '<comment>Delivery</comment>', '<comment>Single Address</comment>'));
foreach ($mailers as $name => $mailer) {
$mailer = $this->getContainer()->get($mailer);
$transport = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.transport.name', $name));
$spool = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.spool.enabled', $name)) ? 'YES' : 'NO';
$delivery = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.delivery.enabled', $name)) ? 'YES' : 'NO';
$singleAddress = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.single_address', $name));
if ($this->isDefaultMailer($name)) {
$name = sprintf('%s (default mailer)', $name);
}
$output->writeln(sprintf($format, $name, $transport, $spool, $delivery, $singleAddress));
}
}

/**
* @throws \InvalidArgumentException When route does not exist
*/
protected function outputMailer(OutputInterface $output, $name)
{
try {
$service = sprintf('swiftmailer.mailer.%s', $name);
$mailer = $this->getContainer()->get($service);
} catch (ServiceNotFoundException $e) {
throw new \InvalidArgumentException(sprintf('The mailer "%s" does not exist.', $name));
}

$transport = $mailer->getTransport();
$spool = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.spool.enabled', $name)) ? 'YES' : 'NO';
$delivery = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.delivery.enabled', $name)) ? 'YES' : 'NO';
$singleAddress = $this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.single_address', $name));

$output->writeln($this->getHelper('formatter')->formatSection('swiftmailer', sprintf('Mailer "%s"', $name)));
if ($this->isDefaultMailer($name)) {
$output->writeln('This is the default mailer');
}

$output->writeln(sprintf('<comment>Name</comment> %s', $name));
$output->writeln(sprintf('<comment>Service</comment> %s', $service));
$output->writeln(sprintf('<comment>Class</comment> %s', get_class($mailer)));
$output->writeln(sprintf('<comment>Transport</comment> %s (%s)', sprintf('swiftmailer.mailer.%s.transport.name', $name), get_class($transport)));
$output->writeln(sprintf('<comment>Spool</comment> %s', $spool));
if ($this->getContainer()->hasParameter(sprintf('swiftmailer.spool.%s.file.path', $name))) {
$output->writeln(sprintf('<comment>Spool file</comment> %s', $this->getContainer()->getParameter(sprintf('swiftmailer.spool.%s.file.path', $name))));
}
$output->writeln(sprintf('<comment>Delivery</comment> %s', $delivery));
$output->writeln(sprintf('<comment>Single Address</comment> %s', $singleAddress));
}

private function isDefaultMailer($name)
{
return ($this->getContainer()->getParameter('swiftmailer.default_mailer') == $name || 'default' == $name) ? true : false;
}
}
56 changes: 39 additions & 17 deletions Command/SendEmailCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ protected function configure()
->addOption('message-limit', 0, InputOption::VALUE_OPTIONAL, 'The maximum number of messages to send.')
->addOption('time-limit', 0, InputOption::VALUE_OPTIONAL, 'The time limit for sending messages (in seconds).')
->addOption('recover-timeout', 0, InputOption::VALUE_OPTIONAL, 'The timeout for recovering messages that have taken too long to send (in seconds).')
->addOption('mailer', null, InputOption::VALUE_OPTIONAL, 'The mailer name.')
->setHelp(<<<EOF
The <info>swiftmailer:spool:send</info> command sends all emails from the spool.
<info>php app/console swiftmailer:spool:send --message-limit=10 --time-limit=10 --recover-timeout=900</info>
<info>php app/console swiftmailer:spool:send --message-limit=10 --time-limit=10 --recover-timeout=900 --mailer=default</info>
EOF
)
Expand All @@ -50,25 +51,46 @@ protected function configure()
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$mailer = $this->getContainer()->get('mailer');
$transport = $mailer->getTransport();

if ($transport instanceof \Swift_Transport_SpoolTransport) {
$spool = $transport->getSpool();
if ($spool instanceof \Swift_ConfigurableSpool) {
$spool->setMessageLimit($input->getOption('message-limit'));
$spool->setTimeLimit($input->getOption('time-limit'));
$name = $input->getOption('mailer');
if ($name) {
$this->processMailer($name, $input, $output);
} else {
$mailers = array_keys($this->getContainer()->getParameter('swiftmailer.mailers'));
foreach ($mailers as $name) {
$this->processMailer($name, $input, $output);
}
if ($spool instanceof \Swift_FileSpool) {
if (null !== $input->getOption('recover-timeout')) {
$spool->recover($input->getOption('recover-timeout'));
} else {
$spool->recover();
}
}

private function processMailer($name, $input, $output)
{
if (!$this->getContainer()->has(sprintf('swiftmailer.mailer.%s', $name))) {
throw new \InvalidArgumentException(sprintf('The mailer "%s" does not exist.', $name));
}

$output->write(sprintf('Processing <info>%s</info> mailer... ', $name));
if ($this->getContainer()->getParameter(sprintf('swiftmailer.mailer.%s.spool.enabled', $name))) {
$mailer = $this->getContainer()->get(sprintf('swiftmailer.mailer.%s', $name));
$transport = $mailer->getTransport();
if ($transport instanceof \Swift_Transport_SpoolTransport) {
$spool = $transport->getSpool();
if ($spool instanceof \Swift_ConfigurableSpool) {
$spool->setMessageLimit($input->getOption('message-limit'));
$spool->setTimeLimit($input->getOption('time-limit'));
}
}
$sent = $spool->flushQueue($this->getContainer()->get('swiftmailer.transport.real'));
if ($spool instanceof \Swift_FileSpool) {
if (null !== $input->getOption('recover-timeout')) {
$spool->recover($input->getOption('recover-timeout'));
} else {
$spool->recover();
}
}
$sent = $spool->flushQueue($this->getContainer()->get(sprintf('swiftmailer.mailer.%s.transport.real', $name)));

$output->writeln(sprintf('sent %s emails', $sent));
$output->writeln(sprintf('<comment>%d</comment> emails sent', $sent));
}
} else {
$output->writeln('No email to send as the spool is disabled.');
}
}
}
160 changes: 160 additions & 0 deletions DataCollector/MessageDataCollector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SwiftmailerBundle\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* MessageDataCollector.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Clément JOBEILI <clement.jobeili@gmail.com>
* @author Jérémy Romey <jeremy@free-agent.fr>
*/
class MessageDataCollector extends DataCollector
{
private $container;

/**
* Constructor.
*
* We don't inject the message logger and mailer here
* to avoid the creation of these objects when no emails are sent.
*
* @param ContainerInterface $container A ContainerInterface instance
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}

/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->data = array(
'mailer' => array(),
'messageCount' => 0,
'defaultMailer' => '',
);
// only collect when Swiftmailer has already been initialized
if (class_exists('Swift_Mailer', false)) {
$mailers = $this->container->getParameter('swiftmailer.mailers');
foreach ($mailers as $name => $mailer) {
if ($this->container->getParameter('swiftmailer.default_mailer') == $name) {
$this->data['defaultMailer'] = $name;
}
$loggerName = sprintf('swiftmailer.mailer.%s.plugin.messagelogger', $name);
if ($this->container->has($loggerName)) {
$logger = $this->container->get($loggerName);
$this->data['mailer'][$name] = array(
'messages' => $logger->getMessages(),
'messageCount' => $logger->countMessages(),
'isSpool' => $this->container->getParameter(sprintf('swiftmailer.mailer.%s.spool.enabled', $name)),
);
$this->data['messageCount'] += $logger->countMessages();
}
}
}
}

/**
* Returns the mailer names.
*
* @return array The mailer names.
*/
public function getMailers()
{
return array_keys($this->data['mailer']);
}

/**
* Returns the data collected of a mailer.
*
* @return array The data of the mailer.
*/

public function getMailerData($name)
{
if (!isset($this->data['mailer'][$name])) {
throw new \LogicException(sprintf("Missing %s data in %s", $name, get_class()));
}

return $this->data['mailer'][$name];
}

/**
* Returns the message count of a mailer or the total.
*
* @return int The number of messages.
*/
public function getMessageCount($name = null)
{
if (is_null($name)) {
return $this->data['messageCount'];
} elseif ($data = $this->getMailerData($name)) {
return $data['messageCount'];
}

return null;
}

/**
* Returns the message of a mailer.
*
* @return array The messages.
*/
public function getMessages($name)
{
if ($data = $this->getMailerData($name)) {
return $data['messages'];
}

return array();
}

/**
* Returns if the mailer has spool.
*
* @return boolean
*/
public function isSpool($name)
{
if ($data = $this->getMailerData($name)) {
return $data['isSpool'];
}

return null;
}

/**
* Returns if the mailer is the default mailer.
*
* @return boolean
*/
public function isDefaultMailer($name)
{
return $this->data['defaultMailer'] == $name;
}

/**
* {@inheritdoc}
*/
public function getName()
{
return 'swiftmailer';
}
}

1 comment on commit 69d6c36

@jameshalsall
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should also have a documentation update in the cookbook (see: http://symfony.com/doc/master/cookbook/email/testing.html)

Please sign in to comment.