Skip to content

Commit

Permalink
add static new() and factory() on ConnectionLocator
Browse files Browse the repository at this point in the history
  • Loading branch information
Paul M. Jones committed Apr 3, 2018
1 parent 777802e commit 5c89694
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand Down
18 changes: 18 additions & 0 deletions src/ConnectionLocator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [],
Expand Down
26 changes: 26 additions & 0 deletions tests/ConnectionLocatorTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?php
namespace Atlas\Pdo;

use PDO;

class ConnectionLocatorTest extends \PHPUnit\Framework\TestCase
{
/**
Expand Down Expand Up @@ -47,6 +49,30 @@ protected function newLocator($read = [], $write = [])
return new ConnectionLocator($this->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();
Expand Down

0 comments on commit 5c89694

Please sign in to comment.