From 5c89694a9cff18b89b68f7589e48cb0f6999dd3b Mon Sep 17 00:00:00 2001 From: "Paul M. Jones" Date: Tue, 3 Apr 2018 07:59:31 -0500 Subject: [PATCH] add static new() and factory() on ConnectionLocator --- src/Connection.php | 4 ++++ src/ConnectionLocator.php | 18 ++++++++++++++++++ tests/ConnectionLocatorTest.php | 26 ++++++++++++++++++++++++++ 3 files changed, 48 insertions(+) diff --git a/src/Connection.php b/src/Connection.php index bee9c3c..7f7ca11 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -20,6 +20,10 @@ class Connection public static function new(...$args) : Connection { + if ($args[0] instanceof PDO) { + return new static($args[0]); + } + return new static(new PDO(...$args)); } diff --git a/src/ConnectionLocator.php b/src/ConnectionLocator.php index ef81778..953dd7f 100644 --- a/src/ConnectionLocator.php +++ b/src/ConnectionLocator.php @@ -36,6 +36,24 @@ class ConnectionLocator protected $lockToWrite = false; + public static function new(...$args) + { + if ($args[0] instanceof Connection) { + return new static(function () use ($args) { + return $args[0]; + }); + } + + return new static(Connection::factory(...$args)); + } + + public static function factory(...$args) + { + return function () use ($args) { + return static::new(...$args); + }; + } + public function __construct( callable $default = null, array $read = [], diff --git a/tests/ConnectionLocatorTest.php b/tests/ConnectionLocatorTest.php index 714b71f..21a3c94 100644 --- a/tests/ConnectionLocatorTest.php +++ b/tests/ConnectionLocatorTest.php @@ -1,6 +1,8 @@ default, $read, $write); } + public function testNewWithConnection() + { + $connection = Connection::new('sqlite::memory:'); + $actual = ConnectionLocator::new($connection); + $this->assertInstanceOf(ConnectionLocator::CLASS, $actual); + $this->assertSame($connection, $actual->getDefault()); + } + + public function testNewWithPdo() + { + $pdo = new Pdo('sqlite::memory:'); + $actual = ConnectionLocator::new($pdo); + $this->assertInstanceOf(ConnectionLocator::CLASS, $actual); + $this->assertSame($pdo, $actual->getDefault()->getPdo()); + } + + public function testFactory() + { + $factory = ConnectionLocator::factory('sqlite::memory:'); + $actual = $factory(); + $this->assertInstanceOf(ConnectionLocator::CLASS, $actual); + $this->assertInstanceOf(PDO::CLASS, $actual->getDefault()->getPdo()); + } + public function testGetDefault() { $locator = $this->newLocator();