Skip to content

Commit

Permalink
Separate Xeed class and PDO (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
cable8mm authored Mar 20, 2024
1 parent 77a996b commit f65db7d
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 35 deletions.
4 changes: 2 additions & 2 deletions src/Command/ImportXeedCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
if ($argument === 'drop' || $argument === 'refresh') {
$sql = 'DROP TABLE IF EXISTS '.self::TABLE_NAME;

$xeed->exec($sql);
$xeed->pdo->exec($sql);

$output->writeln('`'.self::TABLE_NAME.'` table was dropped.');
}
Expand All @@ -77,7 +77,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int

$sql = File::system()->read($filename);

$xeed->exec($sql);
$xeed->pdo->exec($sql);

$output->writeln($filename.' was imported.');

Expand Down
4 changes: 2 additions & 2 deletions src/Provider/MysqlProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ final class MysqlProvider implements ProviderInterface
*/
public function attach(Xeed $xeed): void
{
$tables = $xeed->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);
$tables = $xeed->pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);

foreach ($tables as $table) {
$columns = $xeed->query('SHOW COLUMNS FROM '.$table)->fetchAll(PDO::FETCH_ASSOC);
$columns = $xeed->pdo->query('SHOW COLUMNS FROM '.$table)->fetchAll(PDO::FETCH_ASSOC);

$tableColumns = array_map(
fn (array $column) => new Column(...self::map($column)),
Expand Down
6 changes: 3 additions & 3 deletions src/Provider/SqliteProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ final class SqliteProvider implements ProviderInterface
*/
public function attach(Xeed $xeed): void
{
$query = $xeed->query("SELECT name FROM sqlite_master WHERE type='table';");
$query = $xeed->pdo->query("SELECT name FROM sqlite_master WHERE type='table';");

$tables = array_filter($query->fetchAll(), fn ($item) => $item['name'] !== 'sqlite_sequence');

$tables = array_flatten($tables);

foreach ($tables as $table) {
$columns = $xeed->query('SELECT * FROM PRAGMA_TABLE_INFO("'.$table.'");')->fetchAll();
$columns = $xeed->pdo->query('SELECT * FROM PRAGMA_TABLE_INFO("'.$table.'");')->fetchAll();

foreach ($columns as $column) {
$columnObject[] = new Column(...self::map($column, $table, $xeed));
Expand All @@ -44,7 +44,7 @@ public static function map(array $column, ?string $table = null, ?Xeed $xeed = n
$authIncrement = false;

if ($column['pk'] == 1) {
$count = $xeed->query('SELECT COUNT(*) FROM sqlite_sequence WHERE name=\''.$table.'\'');
$count = $xeed->pdo->query('SELECT COUNT(*) FROM sqlite_sequence WHERE name=\''.$table.'\'');
$authIncrement = $count == 1;
}

Expand Down
74 changes: 54 additions & 20 deletions src/Xeed.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,25 @@
/**
* Database Object.
*/
final class Xeed extends PDO implements ArrayAccess
final class Xeed implements ArrayAccess
{
/**
* Singleton Instance.
*/
private static $instance = null;

/**
* PDO Instance.
*/
public PDO $pdo;

/**
* Driver name.
*
* @var string, eg. 'mysql' or 'sqlite'
*/
public string $driver;

Check failure on line 31 in src/Xeed.php

View workflow job for this annotation

GitHub Actions / publish-pages / publish-pages

The hint on "driver" at @var is invalid: "string, eg. 'mysql' or 'sqlite'" on "Cable8mm\Xeed\Xeed::$driver"

/**
* Array of available databases.
*/
Expand All @@ -30,30 +42,45 @@ final class Xeed extends PDO implements ArrayAccess

private ProviderInterface $provider;

private function __construct(
public string $driver,
?string $database = null,
?string $host = null,
?string $port = null,
?string $username = null,
?string $password = '',
?array $options = null
) {
$options = $options ?? [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
/**
* Establish connection
*
* @param array $connection The elements of the connection array.($driver, $database, $host, $port, $username, $password)
* @return static The method returns the current instance that enables method chaining.
*/
public function addConnection(array $connection): static
{
// self::$instance = new self($driver, $database, $host, $port, $username, $password);

$options = $connection['options'] ?? [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];

$this->provider = new (__NAMESPACE__.'\\Provider\\'.ucfirst($connection['driver']).'Provider');

$this->provider = new (__NAMESPACE__.'\\Provider\\'.ucfirst($driver).'Provider');
$this->driver = $connection['driver'];

if ($driver === 'sqlite') {
$dns = $driver.':'.($database ?? Path::database().'database.sqlite');
if ($connection['driver'] === 'sqlite') {
$dns = $connection['driver'].':'.($database ?? Path::database().'database.sqlite');

$this->pdo = new PDO($dns, options: $options);
}

parent::__construct($dns, options: $options);
if ($connection['driver'] === 'mysql') {
$dns = $connection['driver'].
':host='.
$connection['host'].
((! empty($connection['port'])) ? (';port='.$connection['port']) : '').';dbname='.$connection['database'];

return;
$this->pdo = new PDO($dns, $connection['username'], $connection['password'], $options);
}

$dns = $driver.':host='.$host.((! empty($port)) ? (';port='.$port) : '').';dbname='.$database;
return $this;
}

parent::__construct($dns, $username, $password, $options);
public function addPdo(PDO $pdo): static
{
$this->pdo = $pdo;

return $this;
}

/**
Expand All @@ -74,7 +101,14 @@ public static function getInstance(): static
$username = $_ENV['DB_USERNAME'] ?? null;
$password = $_ENV['DB_PASSWORD'] ?? null;

self::$instance = new self($driver, $database, $host, $port, $username, $password);
self::$instance = (new static())->addConnection([
'driver' => $driver,
'database' => $database,
'host' => $host,
'port' => $port,
'username' => $username,
'password' => $password,
]);
}

return self::$instance;
Expand Down Expand Up @@ -107,7 +141,7 @@ public function attach(): static
/**
* Get attached tables.
*
* @return array<\Cable8mm\Xeed\Table> The method returns the attached tables
* @return \Cable8mm\Xeed\Table[] The method returns the attached tables
*/
public function getTables(): array
{
Expand Down
6 changes: 3 additions & 3 deletions tests/Bootstrap/Seeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function run(): void

public function dropTables()
{
$sql = $this->xeed->prepare('DROP TABLE IF EXISTS '.self::TABLE);
$sql = $this->xeed->pdo->prepare('DROP TABLE IF EXISTS '.self::TABLE);

return $sql->execute();
}
Expand All @@ -43,13 +43,13 @@ private function createUserTable(): int|false

$schema = 'CREATE TABLE `'.self::TABLE.'` ( id INTEGER PRIMARY KEY '.$autoIncrement.', name VARCHAR(25) NOT NULL, email VARCHAR(100) NOT NULL)';

return $this->xeed->exec($schema);
return $this->xeed->pdo->exec($schema);
}

private function addItem(): void
{
$sql = 'INSERT INTO '.self::TABLE.' (name, email) VALUES (:name, :email)';
$stmt = $this->xeed->prepare($sql);
$stmt = $this->xeed->pdo->prepare($sql);

for ($i = 0; $i < self::TOTAL; $i++) {
$stmt->execute($this->factory());
Expand Down
6 changes: 3 additions & 3 deletions tests/Unit/Command/ImportXeedCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function test_execute(): void
]);

try {
Xeed::getInstance()->query('SELECT 1 FROM '.ImportXeedCommand::TABLE_NAME);
Xeed::getInstance()->pdo->query('SELECT 1 FROM '.ImportXeedCommand::TABLE_NAME);

$this->assertTrue(true);
} catch (PDOException $e) {
Expand All @@ -41,7 +41,7 @@ public function test_execute(): void
]);

try {
Xeed::getInstance()->query('SELECT 1 FROM '.ImportXeedCommand::TABLE_NAME);
Xeed::getInstance()->pdo->query('SELECT 1 FROM '.ImportXeedCommand::TABLE_NAME);

$this->assertTrue(false);
} catch (PDOException $e) {
Expand All @@ -54,7 +54,7 @@ public function test_execute(): void
]);

try {
Xeed::getInstance()->query('SELECT 1 FROM '.ImportXeedCommand::TABLE_NAME);
Xeed::getInstance()->pdo->query('SELECT 1 FROM '.ImportXeedCommand::TABLE_NAME);

$this->assertTrue(true);
} catch (PDOException $e) {
Expand Down
4 changes: 2 additions & 2 deletions tests/Unit/XeedTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function test_can_retrieve_tables(): void
{
$tables = Xeed::getNewInstance()->attach()->getTables();

$this->assertNotEmpty($tables);
$this->assertIsArray($tables);
}

public function test_seeder_can_make_seeds(): void
Expand All @@ -52,7 +52,7 @@ public function test_seeder_can_make_seeds(): void

$sql = 'SELECT * FROM '.Seeder::TABLE;

$result = $xeed->query($sql);
$result = $xeed->pdo->query($sql);

$users = $result->fetchAll();

Expand Down

0 comments on commit f65db7d

Please sign in to comment.