Skip to content

Commit

Permalink
MailSender takes host from nette/http (#566)
Browse files Browse the repository at this point in the history
  • Loading branch information
janfejtek authored Jun 20, 2023
1 parent db0a128 commit 69cb79a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
"nette/tester": "^2.2",
"latte/latte": "^2.5",
"psr/log": "^1.0 || ^2.0 || ^3.0",
"phpstan/phpstan": "^1.0"
"phpstan/phpstan": "^1.0",
"nette/http": "^3.0"
},
"conflict": {
"nette/di": "<3.0"
Expand Down
9 changes: 6 additions & 3 deletions src/Bridges/Nette/MailSender.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
use Nette;
use Tracy;


/**
* Tracy logger bridge for Nette Mail.
*/
Expand All @@ -25,17 +24,21 @@ class MailSender
/** @var string|null sender of email notifications */
private ?string $fromEmail = null;

/** @var string|null actual host on which notification occurred - visible in subject */
private ?string $host = null;


public function __construct(Nette\Mail\IMailer $mailer, ?string $fromEmail = null)
public function __construct(Nette\Mail\IMailer $mailer, ?string $fromEmail = null, ?string $host = null)
{
$this->mailer = $mailer;
$this->fromEmail = $fromEmail;
$this->host = $host;
}


public function send(mixed $message, string $email): void
{
$host = preg_replace('#[^\w.-]+#', '', $_SERVER['SERVER_NAME'] ?? php_uname('n'));
$host = preg_replace('#[^\w.-]+#', '', $this->host ?? $_SERVER['SERVER_NAME'] ?? php_uname('n'));

$mail = new Nette\Mail\Message;
$mail->setHeader('X-Mailer', 'Tracy');
Expand Down
8 changes: 7 additions & 1 deletion src/Bridges/Nette/TracyExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,14 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class)
}

if ($this->config->netteMailer && $builder->getByType(Nette\Mail\IMailer::class)) {
$senderParams = [];
$senderParams['fromEmail'] = $this->config->fromEmail;
if (class_exists(Nette\Http\Request::class)) {
$senderParams['host'] = new Statement('($request = $this->getByType(?, false)) \? $request->getUrl()->getHost() : null', [Nette\Http\Request::class]);
}

$initialize->addBody($builder->formatPhp('if ($logger instanceof Tracy\Logger) $logger->mailer = ?;', [
[new Statement(Tracy\Bridges\Nette\MailSender::class, ['fromEmail' => $this->config->fromEmail]), 'send'],
[new Statement(Tracy\Bridges\Nette\MailSender::class, $senderParams), 'send'],
]));
}

Expand Down

0 comments on commit 69cb79a

Please sign in to comment.