woodpecker-email/src/Factory/EmailFactory.php

77 lines
2.1 KiB
PHP

<?php
namespace Plugin\Factory;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\File;
use Twig\Environment;
class EmailFactory
{
public function __construct(
protected Environment $twig,
protected array $config,
protected array $build
) {
}
public function createMailer(): Mailer
{
return new Mailer(Transport::fromDsn((string) $this->config['dsn']));
}
public function createEmail(): Email
{
$from = json_decode($this->config['from'], true);
$content = json_decode($this->config['content'], true);
$subject = $this->twig->createTemplate(
$content['subject'] ?? '[{{ pipeline.status }}] {{ repo.full_name }} ({{ commit.branch }} - {{ commit.sha[0:8] }})'
);
$email = (new Email())
->subject($subject->render($this->build))
->from(
new Address(
$from['address'] ?? '',
$from['name'] ?? ''
)
)
;
$recipients = explode(',', $this->config['recipients']);
$attachments = explode(',', $this->config['attachments']);
foreach ($recipients as $item) {
$item = filter_var(trim($item), FILTER_VALIDATE_EMAIL);
if ($item) {
$email->addBcc($item);
}
}
foreach ($attachments as $item) {
foreach (glob($item) as $file) {
if (is_file($file)) {
$email->addPart(new DataPart(new File($file)));
}
}
}
if (false === $this->config['is_recipients_only']) {
$email->addBcc($this->build['commit']['author_email']);
}
$email->html($this->twig->render('build_status.html.twig', [
'build' => $this->build,
'body' => $content['body'] ?? null,
]));
return $email;
}
}