php-spark/plugins/com.noccy.pdo/PdoResource.php

80 lines
2.1 KiB
PHP
Raw Normal View History

2021-12-08 23:58:28 +00:00
<?php
namespace SparkPlug\Com\Noccy\Pdo;
use Spark\Resource\ResourceType;
use PDO;
use SparkPlug\Com\Noccy\Pdo\Reflection\Reflector\MysqlReflector;
use SparkPlug\Com\Noccy\Pdo\Reflection\Reflector\ReflectorInterface;
use SparkPlug\Com\Noccy\Pdo\Reflection\Reflector\SqliteReflector;
2021-12-08 23:58:28 +00:00
class PdoResource extends ResourceType
{
private PDO|null $pdo = null;
private array $options;
public function __construct(array $options)
{
$this->options = $options;
}
private function createFromURI(string $uri)
{
$uris = parse_url($uri);
$username = $uris['user']??null;
$password = $uris['pass']??null;
switch ($uris['scheme']??null) {
case 'mysql':
$database = ltrim($uris['path']??null, '/');
$dsn = sprintf("mysql:host=%s;port=%d;dbname=%s", $uris['host']??'127.0.0.1', $uris['port']??3306, $database);
break;
case 'sqlite':
$database = $uris['path']??':memory:';
$dsn = sprintf("sqlite:%s", $database);
break;
default:
fprintf(STDERR, "error: Unable to create PDO resource from URI, invalid type %s\n", $uris['scheme']??null);
return;
}
$this->pdo = new \PDO($dsn, $username, $password);
}
public function getPDO(): ?PDO
{
if (!$this->pdo) {
$this->createFromURI($this->options['uri']);
}
return $this->pdo;
}
public function getReflector(): ?ReflectorInterface
{
$uri = $this->options['uri'];
if (!preg_match('|^(.+?):|', $uri, $m)) {
fprintf(STDERR, "error: Bad resource URI\n");
return null;
}
switch ($m[1]) {
case 'mysql':
return new MysqlReflector($this);
case 'sqlite':
return new SqliteReflector($this);
}
}
2021-12-08 23:58:28 +00:00
public function info()
{
return $this->options['uri'];
}
public function createTable(string $name, array $columns, bool $ifNotExists=false)
{
}
}