php-spark/plugins/com.noccy.pdo/PdoResource.php
Christopher Vagnetoft 538383c33d PDO plugin: Reflections
* com.noccy.pdo: Implemented reflection for PDO databases,
  tables and columns. Reflectors for MySQL and Sqlite.
* com.noccy.pdo: Added pdo:inspect command.
* com.noccy.docker: Added basic stack management and commands.
* com.noccy.docker: Moved commands to dedicated namespace.
* Environment: readConfig and writeConfig helper added, with
  a flag to use the global config dir ~/.config/spark.
2021-12-24 01:27:57 +01:00

80 lines
2.1 KiB
PHP

<?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;
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);
}
}
public function info()
{
return $this->options['uri'];
}
public function createTable(string $name, array $columns, bool $ifNotExists=false)
{
}
}