86 lines
2.3 KiB
PHP
86 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace Ulmus;
|
|
|
|
use Psr\SimpleCache\CacheInterface;
|
|
use Ulmus\Adapter\AdapterInterface;
|
|
|
|
class ConnectionAdapter
|
|
{
|
|
protected AdapterInterface $adapter;
|
|
|
|
protected \PDO $pdo;
|
|
|
|
public function __construct(
|
|
public string $name = "default",
|
|
protected array $configuration = [],
|
|
public bool $default = false,
|
|
public ? CacheInterface $cacheObject = null
|
|
) {
|
|
Ulmus::registerAdapter($this, $default);
|
|
}
|
|
|
|
public function resolveConfiguration() : void
|
|
{
|
|
$connection = $this->configuration['connections'][$this->name] ?? [];
|
|
|
|
if ( false !== ( $adapterName = $connection['adapter'] ?? false ) ) {
|
|
if (is_array($adapterName)) {
|
|
throw new \InvalidArgumentException(sprintf("Given adapter (%s) name is an array, not a string.. received : %s.", $this->name, json_encode($adapterName)));
|
|
}
|
|
|
|
$this->adapter = $this->instanciateAdapter($adapterName);
|
|
}
|
|
else {
|
|
throw new \InvalidArgumentException(sprintf("Adapter not found within your configuration array. (%s)", json_encode($connection)));
|
|
}
|
|
|
|
$this->adapter->setup($connection);
|
|
|
|
unset($this->configuration['connections']);
|
|
}
|
|
|
|
public function getConfiguration() : array
|
|
{
|
|
return $this->configuration['connections'][$this->name] ?? [];
|
|
}
|
|
|
|
/**
|
|
* Connect the adapter
|
|
* @return self
|
|
*/
|
|
public function connect() : self
|
|
{
|
|
$this->pdo = $this->adapter->connect();
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function adapter() : AdapterInterface
|
|
{
|
|
return $this->adapter;
|
|
}
|
|
|
|
public function pdo() : \PDO
|
|
{
|
|
return $this->pdo ?? $this->connect()->pdo;
|
|
}
|
|
|
|
public function connector() : object
|
|
{
|
|
return $this->pdo();
|
|
}
|
|
|
|
/**
|
|
* 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(string $name) : AdapterInterface
|
|
{
|
|
$class = substr($name, 0, 2) === "\\" ? $name : sprintf("\\%s\\Adapter\\%s", __NAMESPACE__, $name);
|
|
|
|
return new $class();
|
|
}
|
|
}
|