From 2fc807cf0cdf8d079bb6d874dd56e9edad5d5ffb Mon Sep 17 00:00:00 2001 From: Oleg Voronkovich Date: Mon, 20 Feb 2023 17:22:49 +0300 Subject: [PATCH] Implment DSN parsing --- src/DSNConfigurator.php | 71 ++++++++++++++++++++++++++ test/PHPMailer/DSNConfiguratorTest.php | 31 +++++++++++ 2 files changed, 102 insertions(+) create mode 100644 src/DSNConfigurator.php create mode 100644 test/PHPMailer/DSNConfiguratorTest.php diff --git a/src/DSNConfigurator.php b/src/DSNConfigurator.php new file mode 100644 index 00000000..6da7f781 --- /dev/null +++ b/src/DSNConfigurator.php @@ -0,0 +1,71 @@ + + * @author Jim Jagielski (jimjag) + * @author Andy Prevost (codeworxtech) + * @author Brent R. Matzelle (original founder) + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2010 - 2012 Jim Jagielski + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + * @note This program is distributed in the hope that it will be useful - WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + */ + +namespace PHPMailer\PHPMailer; + +/** + * Configure PHPMailer via DSN. + * + * @author Oleg Voronkovich (voronkovich) + */ +class DSNConfigurator +{ + /** + * Configure PHPMailer via DSN. + * + * @param PHPMailer $mailer PHPMailer instance + * @param string $dsn DSN + * + * @return PHPMailer + */ + public function configure(PHPMailer $mailer, $dsn) + { + $config = $this->parseDSN($dsn); + + return $mailer; + } + + /** + * Parse DSN. + * + * @param string $dsn DSN + * + * @throws Exception If DSN is mailformed + * + * @return array configruration + */ + private function parseDSN($dsn) + { + $config = parse_url($dsn); + + if (false === $config || !isset($config['scheme']) || !isset($config['host'])) { + throw new Exception( + sprintf('Mailformed DSN: "%s".', $dsn) + ); + } + + if (isset($config['query'])) { + parse_str($config['query'], $config['query']); + } + + return $config; + } +} diff --git a/test/PHPMailer/DSNConfiguratorTest.php b/test/PHPMailer/DSNConfiguratorTest.php new file mode 100644 index 00000000..1a68c094 --- /dev/null +++ b/test/PHPMailer/DSNConfiguratorTest.php @@ -0,0 +1,31 @@ + + * @author Andy Prevost + * @copyright 2012 - 2020 Marcus Bointon + * @copyright 2004 - 2009 Andy Prevost + * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License + */ + +namespace PHPMailer\Test\PHPMailer; + +use PHPMailer\PHPMailer\DSNConfigurator; +use PHPMailer\PHPMailer\Exception; +use PHPMailer\Test\TestCase; + +final class DSNConfiguratorTest extends TestCase +{ + public function testInvalidDSN() + { + $configurator = new DSNConfigurator(); + + $this->expectException(Exception::class); + $this->expectExceptionMessage('Mailformed DSN: "localhost".'); + + $configurator->configure($this->Mail, 'localhost'); + } +}