1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Mailer\Transport;
13
14use Symfony\Component\Mailer\Exception\InvalidArgumentException;
15
16/**
17 * @author Konstantin Myakshin <molodchick@gmail.com>
18 */
19final class Dsn
20{
21    private $scheme;
22    private $host;
23    private $user;
24    private $password;
25    private $port;
26    private $options;
27
28    public function __construct(string $scheme, string $host, ?string $user = null, ?string $password = null, ?int $port = null, array $options = [])
29    {
30        $this->scheme = $scheme;
31        $this->host = $host;
32        $this->user = $user;
33        $this->password = $password;
34        $this->port = $port;
35        $this->options = $options;
36    }
37
38    public static function fromString(string $dsn): self
39    {
40        if (false === $parsedDsn = parse_url($dsn)) {
41            throw new InvalidArgumentException(sprintf('The "%s" mailer DSN is invalid.', $dsn));
42        }
43
44        if (!isset($parsedDsn['scheme'])) {
45            throw new InvalidArgumentException(sprintf('The "%s" mailer DSN must contain a scheme.', $dsn));
46        }
47
48        if (!isset($parsedDsn['host'])) {
49            throw new InvalidArgumentException(sprintf('The "%s" mailer DSN must contain a host (use "default" by default).', $dsn));
50        }
51
52        $user = '' !== ($parsedDsn['user'] ?? '') ? urldecode($parsedDsn['user']) : null;
53        $password = '' !== ($parsedDsn['pass'] ?? '') ? urldecode($parsedDsn['pass']) : null;
54        $port = $parsedDsn['port'] ?? null;
55        parse_str($parsedDsn['query'] ?? '', $query);
56
57        return new self($parsedDsn['scheme'], $parsedDsn['host'], $user, $password, $port, $query);
58    }
59
60    public function getScheme(): string
61    {
62        return $this->scheme;
63    }
64
65    public function getHost(): string
66    {
67        return $this->host;
68    }
69
70    public function getUser(): ?string
71    {
72        return $this->user;
73    }
74
75    public function getPassword(): ?string
76    {
77        return $this->password;
78    }
79
80    public function getPort(int $default = null): ?int
81    {
82        return $this->port ?? $default;
83    }
84
85    public function getOption(string $key, $default = null)
86    {
87        return $this->options[$key] ?? $default;
88    }
89}
90