ulmus/src/ConnectionAdapter.php

85 lines
2.0 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;
protected PdoObject $pdo;
2019-08-21 20:13:00 +00:00
public function __construct(string $name = "default", array $configuration = [], bool $default = false)
2019-08-21 20:13:00 +00:00
{
$this->name = $name;
2019-08-21 20:13:00 +00:00
$this->configuration = $configuration;
Ulmus::registerAdapter($this, $default);
2019-08-21 20:13:00 +00:00
}
public function resolveConfiguration() : void
2019-08-21 20:13:00 +00:00
{
$connection = $this->configuration['connections'][$this->name] ?? [];
if ( false !== ( $adapterName = $connection['adapter'] ?? false ) ) {
2019-08-21 20:13:00 +00:00
$this->adapter = $this->instanciateAdapter($adapterName);
}
else {
throw new \InvalidArgumentException("Adapter not found within your configuration array.");
}
$this->adapter->setup($connection);
2019-08-21 20:13:00 +00:00
}
2020-10-16 15:27:54 +00:00
public function getConfiguration() : array
{
return $this->configuration['connections'][$this->name];
}
2019-08-21 20:13:00 +00:00
/**
* Connect the adapter
* @return self
*/
public function connect() : self
2019-08-21 20:13:00 +00:00
{
$this->pdo = $this->adapter->connect();
2019-08-21 20:13:00 +00:00
return $this;
}
public function adapter() : AdapterInterface
{
return $this->adapter;
}
public function pdo() : PdoObject
{
return $this->pdo ?? $this->pdo = $this->connect()->pdo;
}
2019-08-21 20:13:00 +00:00
public function connector() : object
{
return $this->pdo();
}
2019-08-21 20:13:00 +00:00
/**
* 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) : AdapterInterface
2019-08-21 20:13:00 +00:00
{
$class = substr($name, 0, 2) === "\\" ? $name : "\\Ulmus\\Adapter\\$name";
2019-08-21 20:13:00 +00:00
return new $class();
}
}