Dsn.php 2.4 KB

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