Last active
April 6, 2018 01:34
-
-
Save f3ath/13719ef77c649dc9386b9fa779c043ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class PdoArgs implements IteratorAggregate | |
{ | |
/** | |
* @var array | |
*/ | |
private $state; | |
public static function factory(string $username = null, string $password = null) | |
{ | |
return new self([ | |
'dsn' => "sqlite::memory:", | |
'username' => $username, | |
'password' => $password, | |
'options' => [] | |
]); | |
} | |
private function __construct(array $state) | |
{ | |
$this->state = $state; | |
} | |
public function withErrorModeException(): self | |
{ | |
return $this->withOptions([PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); | |
} | |
public function getIterator(): Traversable | |
{ | |
return new ArrayIterator([ | |
$this->state['dsn'], | |
$this->state['username'], | |
$this->state['password'], | |
$this->state['options'], | |
]); | |
} | |
public function withOptions(array $options): self | |
{ | |
$state = $this->state; | |
$state['options'] = array_replace($state['options'], $options); | |
return new self($state); | |
} | |
} | |
$pdo = new PDO(...PdoArgs::factory()->withErrorModeException()); | |
$select = $pdo->prepare('SELECT 1 + 1'); | |
$select->execute(); | |
var_dump($select->fetchAll()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment