60 lines
1.5 KiB
PHP
60 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace SparkPlug\Com\Noccy\Pdo;
|
|
|
|
use Spark\Resource\ResourceType;
|
|
use PDO;
|
|
|
|
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 info()
|
|
{
|
|
return $this->options['uri'];
|
|
}
|
|
|
|
public function createTable(string $name, array $columns, bool $ifNotExists=false)
|
|
{
|
|
|
|
}
|
|
}
|