Failed Conditions
Push — master ( 5f5e96...daf37e )
by Adrien
03:02
created

TransportFactory::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
dl 0
loc 12
rs 10
c 1
b 0
f 0
ccs 0
cts 6
cp 0
cc 1
nc 1
nop 3
crap 2
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 11
    public static function dsn(null|array|string $configSmtp): string
39
    {
40 11
        if (!$configSmtp) {
41 3
            return 'null://null';
42
        }
43
44 8
        if (is_string($configSmtp)) {
0 ignored issues
show
introduced by
The condition is_string($configSmtp) is always false.
Loading history...
45 1
            return $configSmtp;
46
        }
47
48 7
        $host = $configSmtp['host'] ?? '';
49 7
        $port = $configSmtp['port'] ?? null ?: 587;
50 7
        $user = $configSmtp['user'] ?? $configSmtp['connection_config']['username'] ?? '';
51 7
        $password = $configSmtp['password'] ?? $configSmtp['connection_config']['password'] ?? '';
52
53 7
        if (!$host) {
54 2
            return 'null://null';
55
        }
56
57 5
        $credentials = $user && $password ? "$user:$password@" : '';
58
59 5
        return "smtp://$credentials$host:$port";
60
    }
61
}
62