summaryrefslogtreecommitdiff
path: root/src/Database
diff options
context:
space:
mode:
Diffstat (limited to 'src/Database')
-rw-r--r--src/Database/DatabaseServiceProvider.php39
-rw-r--r--src/Database/Db.php131
-rw-r--r--src/Database/Migration/Migrate.php192
-rw-r--r--src/Database/Migration/Migration.php16
-rw-r--r--src/Database/Migration/MigrationServiceProvider.php20
5 files changed, 283 insertions, 115 deletions
diff --git a/src/Database/DatabaseServiceProvider.php b/src/Database/DatabaseServiceProvider.php
index 49fb4af5..7328bc4e 100644
--- a/src/Database/DatabaseServiceProvider.php
+++ b/src/Database/DatabaseServiceProvider.php
@@ -4,23 +4,40 @@ namespace Engelsystem\Database;
use Engelsystem\Container\ServiceProvider;
use Exception;
-use PDO;
+use Illuminate\Database\Capsule\Manager as CapsuleManager;
+use PDOException;
class DatabaseServiceProvider extends ServiceProvider
{
public function register()
{
$config = $this->app->get('config');
- Db::connect(
- 'mysql:host=' . $config->get('database')['host']
- . ';dbname=' . $config->get('database')['db']
- . ';charset=utf8',
- $config->get('database')['user'],
- $config->get('database')['pw']
- ) || $this->exitOnError();
-
- Db::getPdo()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- Db::getPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
+ $capsule = $this->app->make(CapsuleManager::class);
+
+ $dbConfig = $config->get('database');
+ $capsule->addConnection(array_merge([
+ 'driver' => 'mysql',
+ 'host' => '',
+ 'database' => '',
+ 'username' => '',
+ 'password' => '',
+ 'charset' => 'utf8',
+ 'collation' => 'utf8_unicode_ci',
+ 'prefix' => '',
+ ], $dbConfig));
+
+ $capsule->setAsGlobal();
+ $capsule->bootEloquent();
+ $capsule->getConnection()->useDefaultSchemaGrammar();
+
+ try {
+ $capsule->getConnection()->getPdo();
+ } catch (PDOException $e) {
+ $this->exitOnError();
+ }
+
+ $this->app->instance('db', $capsule);
+ Db::setDbManager($capsule);
}
/**
diff --git a/src/Database/Db.php b/src/Database/Db.php
index 114bd8fc..f34d1564 100644
--- a/src/Database/Db.php
+++ b/src/Database/Db.php
@@ -2,68 +2,23 @@
namespace Engelsystem\Database;
+use Illuminate\Database\Capsule\Manager as CapsuleManager;
+use Illuminate\Database\Connection as DatabaseConnection;
use PDO;
-use PDOException;
-use PDOStatement;
class Db
{
- /** @var PDO */
- protected static $db;
-
- /** @var PDOStatement */
- protected static $stm = null;
-
- /** @var bool */
- protected static $lastStatus = true;
-
- /**
- * Connect to database
- *
- * @param string $dsn
- * @param string $username
- * @param string $password
- * @param array $options
- * @return bool
- */
- public static function connect($dsn, $username = null, $password = null, $options = [])
- {
- try {
- self::$db = new PDO($dsn, $username, $password, $options);
- } catch (PDOException $e) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Run a prepared query
- *
- * @param string $query
- * @param array $bindings
- * @return PDOStatement
- */
- public static function query($query, array $bindings = [])
- {
- self::$stm = self::$db->prepare($query);
- self::$lastStatus = self::$stm->execute($bindings);
-
- return self::$stm;
- }
+ /** @var CapsuleManager */
+ protected static $dbManager;
/**
- * Run a sql query
+ * Set the database connection manager
*
- * @param string $query
- * @return bool
+ * @param CapsuleManager $dbManager
*/
- public static function unprepared($query)
+ public static function setDbManager($dbManager)
{
- self::$stm = self::$db->query($query);
- self::$lastStatus = (self::$stm instanceof PDOStatement);
-
- return self::$lastStatus;
+ self::$dbManager = $dbManager;
}
/**
@@ -75,9 +30,14 @@ class Db
*/
public static function select($query, array $bindings = [])
{
- self::query($query, $bindings);
+ $return = self::connection()->select($query, $bindings);
- return self::$stm->fetchAll(PDO::FETCH_ASSOC);
+ // @TODO: Remove type casting
+ foreach ($return as $key => $value) {
+ $return[$key] = (array)$value;
+ }
+
+ return $return;
}
/**
@@ -85,17 +45,14 @@ class Db
*
* @param string $query
* @param array $bindings
- * @return array|null
+ * @return array
*/
public static function selectOne($query, array $bindings = [])
{
- $result = self::select($query, $bindings);
+ $result = self::connection()->selectOne($query, $bindings);
- if (empty($result)) {
- return null;
- }
-
- return array_shift($result);
+ // @TODO: remove typecast
+ return (array)$result;
}
/**
@@ -103,13 +60,11 @@ class Db
*
* @param string $query
* @param array $bindings
- * @return int Row count
+ * @return bool
*/
public static function insert($query, array $bindings = [])
{
- self::query($query, $bindings);
-
- return self::$stm->rowCount();
+ return self::connection()->insert($query, $bindings);
}
/**
@@ -121,9 +76,7 @@ class Db
*/
public static function update($query, array $bindings = [])
{
- self::query($query, $bindings);
-
- return self::$stm->rowCount();
+ return self::connection()->update($query, $bindings);
}
/**
@@ -135,37 +88,15 @@ class Db
*/
public static function delete($query, array $bindings = [])
{
- self::query($query, $bindings);
-
- return self::$stm->rowCount();
+ return self::connection()->delete($query, $bindings);
}
/**
- * Run a single statement
- *
- * @param string $query
- * @param array $bindings
- * @return bool
+ * @return DatabaseConnection
*/
- public static function statement($query, array $bindings = [])
+ public static function connection()
{
- self::query($query, $bindings);
-
- return self::$lastStatus;
- }
-
- /**
- * Returns the last error
- *
- * @return array
- */
- public static function getError()
- {
- if (!self::$stm instanceof PDOStatement) {
- return [-1, null, null];
- }
-
- return self::$stm->errorInfo();
+ return self::$dbManager->getConnection();
}
/**
@@ -175,14 +106,6 @@ class Db
*/
public static function getPdo()
{
- return self::$db;
- }
-
- /**
- * @return PDOStatement|false|null
- */
- public static function getStm()
- {
- return self::$stm;
+ return self::connection()->getPdo();
}
}
diff --git a/src/Database/Migration/Migrate.php b/src/Database/Migration/Migrate.php
new file mode 100644
index 00000000..3a08bb6e
--- /dev/null
+++ b/src/Database/Migration/Migrate.php
@@ -0,0 +1,192 @@
+<?php
+
+namespace Engelsystem\Database\Migration;
+
+use Engelsystem\Application;
+use Illuminate\Database\Query\Builder;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Database\Schema\Builder as SchemaBuilder;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Str;
+
+class Migrate
+{
+ const UP = 'up';
+ const DOWN = 'down';
+
+ /** @var Application */
+ protected $app;
+
+ /** @var SchemaBuilder */
+ protected $scheme;
+
+ /** @var callable */
+ protected $output;
+
+ /** @var string */
+ protected $table = 'migrations';
+
+ /**
+ * Migrate constructor
+ *
+ * @param SchemaBuilder $scheme
+ * @param Application $app
+ */
+ public function __construct(SchemaBuilder $scheme, Application $app)
+ {
+ $this->app = $app;
+ $this->scheme = $scheme;
+ $this->output = function () { };
+ }
+
+ /**
+ * Run a migration
+ *
+ * @param string $path
+ * @param string $type (up|down)
+ * @param bool $oneStep
+ */
+ public function run($path, $type = self::UP, $oneStep = false)
+ {
+ $this->initMigration();
+ $migrations = $this->getMigrations($path);
+ $migrated = $this->getMigrated();
+
+ if ($type == self::DOWN) {
+ $migrations = array_reverse($migrations, true);
+ }
+
+ foreach ($migrations as $file => $migration) {
+ if (
+ ($type == self::UP && $migrated->contains('migration', $migration))
+ || ($type == self::DOWN && !$migrated->contains('migration', $migration))
+ ) {
+ call_user_func($this->output, 'Skipping ' . $migration);
+ continue;
+ }
+
+ call_user_func($this->output, 'Migrating ' . $migration . ' (' . $type . ')');
+
+ $this->migrate($file, $migration, $type);
+ $this->setMigrated($migration, $type);
+
+ if ($oneStep) {
+ return;
+ }
+ }
+ }
+
+ /**
+ * Get all migrated migrations
+ *
+ * @return Collection
+ */
+ protected function getMigrated()
+ {
+ return $this->getTableQuery()->get();
+ }
+
+ /**
+ * Migrate a migration
+ *
+ * @param string $file
+ * @param string $migration
+ * @param string $type (up|down)
+ */
+ protected function migrate($file, $migration, $type = self::UP)
+ {
+ require_once $file;
+
+ $className = Str::studly(preg_replace('/\d+_/', '', $migration));
+ /** @var Migration $class */
+ $class = $this->app->make($className);
+
+ if (method_exists($class, $type)) {
+ $class->{$type}();
+ }
+ }
+
+ /**
+ * Set a migration to migrated
+ *
+ * @param string $migration
+ * @param string $type (up|down)
+ */
+ protected function setMigrated($migration, $type = self::UP)
+ {
+ $table = $this->getTableQuery();
+
+ if ($type == self::DOWN) {
+ $table->where(['migration' => $migration])->delete();
+ return;
+ }
+
+ $table->insert(['migration' => $migration]);
+ }
+
+ /**
+ * Get a list of migration files
+ *
+ * @param string $dir
+ * @return array
+ */
+ protected function getMigrations($dir)
+ {
+ $files = $this->getMigrationFiles($dir);
+
+ $migrations = [];
+ foreach ($files as $dir) {
+ $name = str_replace('.php', '', basename($dir));
+ $migrations[$dir] = $name;
+ }
+
+ asort($migrations);
+ return $migrations;
+ }
+
+ /**
+ * List all migration files from the given directory
+ *
+ * @param string $dir
+ * @return array
+ */
+ protected function getMigrationFiles($dir)
+ {
+ return glob($dir . '/*_*.php');
+ }
+
+ /**
+ * Setup migration tables
+ */
+ protected function initMigration()
+ {
+ if ($this->scheme->hasTable($this->table)) {
+ return;
+ }
+
+ $this->scheme->create($this->table, function (Blueprint $table) {
+ $table->increments('id');
+ $table->string('migration');
+ });
+ }
+
+ /**
+ * Init a table query
+ *
+ * @return Builder
+ */
+ protected function getTableQuery()
+ {
+ return $this->scheme->getConnection()->table($this->table);
+ }
+
+ /**
+ * Set the output function
+ *
+ * @param callable $output
+ */
+ public function setOutput(callable $output)
+ {
+ $this->output = $output;
+ }
+}
diff --git a/src/Database/Migration/Migration.php b/src/Database/Migration/Migration.php
new file mode 100644
index 00000000..fcc57b82
--- /dev/null
+++ b/src/Database/Migration/Migration.php
@@ -0,0 +1,16 @@
+<?php
+
+namespace Engelsystem\Database\Migration;
+
+use Illuminate\Database\Schema\Builder as SchemaBuilder;
+
+abstract class Migration
+{
+ /** @var SchemaBuilder */
+ protected $schema;
+
+ public function __construct(SchemaBuilder $schemaBuilder)
+ {
+ $this->schema = $schemaBuilder;
+ }
+}
diff --git a/src/Database/Migration/MigrationServiceProvider.php b/src/Database/Migration/MigrationServiceProvider.php
new file mode 100644
index 00000000..15d06eaf
--- /dev/null
+++ b/src/Database/Migration/MigrationServiceProvider.php
@@ -0,0 +1,20 @@
+<?php
+
+namespace Engelsystem\Database\Migration;
+
+use Engelsystem\Container\ServiceProvider;
+use Engelsystem\Database\Db;
+use Illuminate\Database\Schema\Builder as SchemaBuilder;
+
+class MigrationServiceProvider extends ServiceProvider
+{
+ public function register()
+ {
+ $schema = Db::connection()->getSchemaBuilder();
+ $this->app->instance('db.scheme', $schema);
+ $this->app->bind(SchemaBuilder::class, 'db.scheme');
+
+ $migration = $this->app->make(Migrate::class);
+ $this->app->instance('db.migration', $migration);
+ }
+}