1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Ecodev\Felix\Service; |
6
|
|
|
|
7
|
|
|
use Laminas\ServiceManager\Factory\FactoryInterface; |
8
|
|
|
use Psr\Container\ContainerInterface; |
9
|
|
|
use Symfony\Component\Mailer\Transport; |
10
|
|
|
use Symfony\Component\Mailer\Transport\TransportInterface; |
11
|
|
|
|
12
|
|
|
final class TransportFactory implements FactoryInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Return a configured mail transport. |
16
|
|
|
* |
17
|
|
|
* @param string $requestedName |
18
|
|
|
*/ |
19
|
|
|
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null): TransportInterface |
20
|
|
|
{ |
21
|
|
|
/** @var array $config */ |
22
|
|
|
$config = $container->get('config'); |
23
|
|
|
|
24
|
|
|
// Setup SMTP transport, or a mock one |
25
|
|
|
$configSmtp = $config['smtp'] ?? null; |
26
|
|
|
$dsn = self::dsn($configSmtp); |
27
|
|
|
|
28
|
|
|
$transport = Transport::fromDsn($dsn); |
29
|
|
|
|
30
|
|
|
return $transport; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Return a DSN for Symfony Mailer from given parameters. If input is empty, then it will default to a DSN for a NullTransport. |
35
|
|
|
* |
36
|
|
|
* @param null|array{host?: string, port?: int, user?: ?string, password?: ?string, connection_config?: array{username?: ?string, password?: ?string}}|string $configSmtp |
37
|
|
|
*/ |
38
|
12 |
|
public static function dsn(null|array|string $configSmtp): string |
39
|
|
|
{ |
40
|
12 |
|
if (!$configSmtp) { |
41
|
3 |
|
return 'null://null'; |
42
|
|
|
} |
43
|
|
|
|
44
|
9 |
|
if (is_string($configSmtp)) { |
|
|
|
|
45
|
1 |
|
return $configSmtp; |
46
|
|
|
} |
47
|
|
|
|
48
|
8 |
|
$host = urlencode($configSmtp['host'] ?? ''); |
49
|
8 |
|
$port = $configSmtp['port'] ?? null ?: 587; |
50
|
8 |
|
$user = urlencode($configSmtp['user'] ?? $configSmtp['connection_config']['username'] ?? ''); |
51
|
8 |
|
$password = urlencode($configSmtp['password'] ?? $configSmtp['connection_config']['password'] ?? ''); |
52
|
|
|
|
53
|
8 |
|
if (!$host) { |
54
|
2 |
|
return 'null://null'; |
55
|
|
|
} |
56
|
|
|
|
57
|
6 |
|
$credentials = $user && $password ? "$user:$password@" : ''; |
58
|
|
|
|
59
|
6 |
|
return "smtp://$credentials$host:$port"; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|