ulmus/src/ConnectionAdapter.php

88 lines
2.8 KiB
PHP
Raw Normal View History

2019-08-21 20:13:00 +00:00
<?php
namespace Ulmus;
use Ulmus\Adapter\AdapterInterface;
use Ulmus\Common\PdoObject;
class ConnectionAdapter
{
public string $name;
public array $configuration;
protected AdapterInterface $adapter;
public PdoObject $pdo;
public function __construct(string $name = "default", array $configuration = [])
{
$this->name = $name;
$this->configuration = $configuration;
if ( $name === "default" ) {
Ulmus::$defaultAdapter = $this;
}
}
public function resolveConfiguration()
{
$connection = $this->configuration['connections'][$this->name] ?? [];
if ( $adapterName = $connection['adapter'] ?? false ) {
$this->adapter = $this->instanciateAdapter($adapterName);
}
else {
throw new \InvalidArgumentException("Adapter not found within your configuration array.");
}
if ( false === $this->adapter->hostname = $connection['host'] ?? false ) {
throw new \InvalidArgumentException("Your `host` name is missing from your configuration array");
}
if ( false === $this->adapter->port = $connection['port'] ?? false ) {
throw new \InvalidArgumentException("Your `port` number is missing from your configuration array");
}
if ( false === $this->adapter->database = $connection['database'] ?? false ) {
throw new \InvalidArgumentException("Your `database` name is missing from your configuration array");
}
if ( false === $this->adapter->username = $connection['username'] ?? false ) {
throw new \InvalidArgumentException("Your `username` is missing from your configuration array");
}
if ( false === $this->adapter->password = $connection['password'] ?? false ) {
throw new \InvalidArgumentException("Your `password` is missing from your configuration array");
}
}
/**
* Connect the adapter
* @return self
*/
public function connect()
{
$this->pdo = $this->adapter->connect();
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->pdo->setAttribute(\PDO::ATTR_AUTOCOMMIT, false);
$this->pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
$this->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
return $this;
}
/**
* Instanciate an adapter which interact with the data source
* @param string $name An Ulmus adapter or full class name implementing AdapterInterface
* @return AdapterInterface
*/
protected function instanciateAdapter($name)
{
$class = substr($name, 0, 2) === "\\" ? $name : "\\Ulmus\\Adapter\\$name";
return new $class();
}
}