Dsn.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. public function __construct(
  18. private string $scheme,
  19. private string $host,
  20. private ?string $user = null,
  21. #[\SensitiveParameter] private ?string $password = null,
  22. private ?int $port = null,
  23. private array $options = [],
  24. ) {
  25. }
  26. public static function fromString(#[\SensitiveParameter] string $dsn): self
  27. {
  28. if (false === $params = parse_url($dsn)) {
  29. throw new InvalidArgumentException('The mailer DSN is invalid.');
  30. }
  31. if (!isset($params['scheme'])) {
  32. throw new InvalidArgumentException('The mailer DSN must contain a scheme.');
  33. }
  34. if (!isset($params['host'])) {
  35. throw new InvalidArgumentException('The mailer DSN must contain a host (use "default" by default).');
  36. }
  37. $user = '' !== ($params['user'] ?? '') ? rawurldecode($params['user']) : null;
  38. $password = '' !== ($params['pass'] ?? '') ? rawurldecode($params['pass']) : null;
  39. $port = $params['port'] ?? null;
  40. parse_str($params['query'] ?? '', $query);
  41. return new self($params['scheme'], $params['host'], $user, $password, $port, $query);
  42. }
  43. public function getScheme(): string
  44. {
  45. return $this->scheme;
  46. }
  47. public function getHost(): string
  48. {
  49. return $this->host;
  50. }
  51. public function getUser(): ?string
  52. {
  53. return $this->user;
  54. }
  55. public function getPassword(): ?string
  56. {
  57. return $this->password;
  58. }
  59. public function getPort(?int $default = null): ?int
  60. {
  61. return $this->port ?? $default;
  62. }
  63. public function getOption(string $key, mixed $default = null): mixed
  64. {
  65. return $this->options[$key] ?? $default;
  66. }
  67. }