feat: add method chaining

This commit is contained in:
Victor Westerlund 2023-10-26 14:02:13 +02:00
parent 4c18f5686d
commit 676e337a06
3 changed files with 166 additions and 74 deletions

18
composer.lock generated Normal file
View file

@ -0,0 +1,18 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "aa59b0c90afdd92fd11d1cbc9352676c",
"packages": [],
"packages-dev": [],
"aliases": [],
"minimum-stability": "dev",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": [],
"plugin-api-version": "2.0.0"
}

View file

@ -13,29 +13,6 @@
parent::__construct(...func_get_args()); parent::__construct(...func_get_args());
} }
// Create CSV from array
private static function csv(array $items): string {
return implode(",", $items);
}
/* ---- */
// Create CSV from columns
public static function columns(array|string $columns): string {
return is_array($columns)
? self::csv($columns)
: $columns;
}
// Return CSV of '?' for use with prepared statements
public static function values(array|string $values): string {
return is_array($values)
? self::csv(array_fill(0, count($values), "?"))
: "?";
}
/* ---- */
// Bind SQL statements // Bind SQL statements
private function bind_params(mysqli_stmt &$stmt, mixed $params): bool { private function bind_params(mysqli_stmt &$stmt, mixed $params): bool {
// Convert single value parameter to array // Convert single value parameter to array

View file

@ -2,52 +2,107 @@
namespace libmysqldriver; namespace libmysqldriver;
use \Exception;
use \victorwesterlund\xEnum;
use libmysqldriver\Driver\DatabaseDriver; use libmysqldriver\Driver\DatabaseDriver;
require_once "DatabaseDriver.php"; require_once "DatabaseDriver.php";
// Interface for MySQL_Driver with abstractions for data manipulation // Interface for MySQL_Driver with abstractions for data manipulation
class MySQL extends DatabaseDriver { class MySQL extends DatabaseDriver {
private string $table;
private array $model;
private ?string $order_by = null;
private ?string $filter_sql = null;
private array $filter_values = [];
private int|string|null $limit = null;
// Pass constructor arguments to driver // Pass constructor arguments to driver
function __construct() { function __construct(string $table) {
parent::__construct(...func_get_args()); parent::__construct(...func_get_args());
} }
// Create WHERE AND clause from assoc array of "column" => "value" private function throw_if_no_table() {
private static function where(?array $filter = null): array { if (!$this->table) {
// Return array of an empty string and empty array if no filter is defined throw new Exception("No table name defined");
if (!$filter) { }
return ["", []];
} }
// Format each filter as $key = ? for prepared statement // Return value(s) that exist in $this->model
$stmt = array_map(fn($k): string => "`{$k}` = ?", array_keys($filter)); private function in_model(string|array $columns): ?array {
// Place string into array
// Separate each filter with ANDs $columns = is_array($columns) ? $columns : [$columns];
$sql = " WHERE " . implode(" AND ", $stmt); // Return columns that exist in table model
// Return array of SQL prepared statement string and values return array_filter($columns, fn($col): string => in_array($col, $this->model));
return [$sql, array_values($filter)];
} }
// Return SQL SORT BY string from assoc array of columns and direction /* ---- */
private static function order_by(array $order_by): string {
$sql = " ORDER BY ";
// Create CSV from columns // Use the following table name
$sql .= implode(",", array_keys($order_by)); public function for(string $table): self {
// Create pipe DSV from values $this->table = $table;
$sql .= " " . implode("|", array_values($order_by)); return $this;
}
return $sql; // Restrict query to array of column names
public function with(array $model): self {
// Reset table model
$this->model = [];
foreach ($model as $k => $v) {
// Column values must be strings
if (!is_string($v)) {
throw new Exception("Key {$k} must have a value of type string");
}
// Append column to model
$this->model[] = $v;
}
return $this;
}
// Create a WHERE statement from filters
public function where(?array ...$conditions): self {
$values = [];
$filters = [];
// Group each condition into an AND block
foreach ($conditions as $condition) {
$filter = [];
// Create SQL string and append values to array for prepared statement
foreach ($condition as $col => $value) {
if ($this->model && !$this->in_model($col)) {
continue;
}
// Create SQL for prepared statement
$filter[] = "`{$col}` = ?";
// Append value to array with all other values
$values[] = $value;
}
// AND together all conditions into a group
$filters[] = "(" . implode(" AND ", $filter) . ")";
}
// OR all filter groups
$this->filter_sql = implode(" OR ", $filters);
// Set values property
$this->filter_values = $values;
return $this;
} }
// Return SQL LIMIT string from integer or array of [offset => limit] // Return SQL LIMIT string from integer or array of [offset => limit]
private static function limit(int|array $limit): string { public function limit(int|array $limit): self {
$sql = " LIMIT "; // Set LIMIT without range directly as integer
// Return LIMIT without range directly as string
if (is_int($limit)) { if (is_int($limit)) {
return $sql . $limit; $this->limit = $limit;
return $this;
} }
// Use array key as LIMIT range start value // Use array key as LIMIT range start value
@ -55,65 +110,107 @@
// Use array value as LIMIT range end value // Use array value as LIMIT range end value
$limit = (int) array_values($limit)[0]; $limit = (int) array_values($limit)[0];
// Return as SQL LIMIT CSV // Set limit as SQL CSV
return $sql . "{$offset},{$limit}"; $this->limit = "{$offset},{$limit}";
return $this;
}
// Return SQL SORT BY string from assoc array of columns and direction
public function order(array $order_by): self {
// Create CSV from columns
$sql = implode(",", array_keys($order_by));
// Create pipe DSV from values
$sql .= " " . implode("|", array_values($order_by));
$this->order_by = $sql;
return $this;
} }
/* ---- */ /* ---- */
// Create Prepared Statament for SELECT with optional WHERE filters // Create Prepared Statament for SELECT with optional WHERE filters
public function get(string $table, array|string $columns = null, ?array $filter = [], ?array $order_by = null, int|array|null $limit = null): array|bool { public function select(?array $columns = null): array|bool {
// Create CSV string of columns if argument defined, else return bool $this->throw_if_no_table();
$columns_sql = $columns ? self::columns($columns) : "NULL";
// Filter columns that aren't in the model if defiend
if ($columns && $this->model) {
$columns = $this->in_model($columns);
}
// Create CSV from columns or default to SQL NULL as a string
$columns_sql = $columns ? implode(",", $columns) : "NULL";
// Create LIMIT statement if argument is defined // Create LIMIT statement if argument is defined
$limit_sql = $limit ? self::limit($limit) : ""; $limit_sql = !is_null($this->limit) ? " LIMIT {$this->limit}" : "";
// Create ORDER BY statement if argument is defined // Create ORDER BY statement if argument is defined
$order_by_sql = $order_by ? self::order_by($order_by) : ""; $order_by_sql = !is_null($this->order_by) ? " ORDER BY {$this->order_by}" : "";
// Get array of SQL WHERE string and filter values // Get array of SQL WHERE string and filter values
[$filter_sql, $filter_values] = self::where($filter); $filter_sql = !is_null($this->filter_sql) ? " WHERE {$this->filter_sql}" : "";
// Interpolate components into an SQL SELECT statmenet and execute // Interpolate components into an SQL SELECT statmenet and execute
$sql = "SELECT {$columns_sql} FROM {$table}{$filter_sql}{$order_by_sql}{$limit_sql}"; $sql = "SELECT {$columns_sql} FROM {$this->table}{$filter_sql}{$order_by_sql}{$limit_sql}";
$test = $this->model;
// No columns were specified, return true if query matched rows // No columns were specified, return true if query matched rows
if (!$columns) { if (!$columns) {
return $this->exec_bool($sql, $filter_values); return $this->exec_bool($sql, $this->filter_values);
} }
// Return array of matched rows // Return array of matched rows
$exec = $this->exec($sql, $filter_values); $exec = $this->exec($sql, $this->filter_values);
// Flatten array if $limit === 1 // Flatten array if LIMIT is 1
return empty($exec) || $limit !== 1 ? $exec : $exec[0]; return empty($exec) || $this->limit !== 1 ? $exec : $exec[0];
} }
// Create Prepared Statement for UPDATE using PRIMARY KEY as anchor // Create Prepared Statement for UPDATE using PRIMARY KEY as anchor
public function update(string $table, array $fields, ?array $filter = null): bool { public function update(array $entity): bool {
$this->throw_if_no_table();
// Make constraint for table model if defined
if ($this->model) {
foreach (array_keys($entity) as $col) {
// Throw if column in entity does not exist in defiend table model
if (!in_array($col, $this->model)) {
throw new Exception("Column key '{$col}' does not exist in table model");
}
}
}
// Create CSV string with Prepared Statement abbreviations from length of fields array. // Create CSV string with Prepared Statement abbreviations from length of fields array.
$changes = array_map(fn($column) => "{$column} = ?", array_keys($fields)); $changes = array_map(fn($column) => "{$column} = ?", array_keys($entity));
$changes = implode(",", $changes); $changes = implode(",", $changes);
// Get array of SQL WHERE string and filter values // Get array of SQL WHERE string and filter values
[$filter_sql, $filter_values] = self::where($filter); $filter_sql = !is_null($this->filter_sql) ? " WHERE {$this->filter_sql}" : "";
$values = array_values($fields); $values = array_values($entity);
// Append filter values if defined // Append filter values if defined
if ($filter_values) { if ($this->filter_values) {
array_push($values, ...$filter_values); array_push($values, ...$this->filter_values);
} }
// Interpolate components into an SQL UPDATE statement and execute // Interpolate components into an SQL UPDATE statement and execute
$sql = "UPDATE {$table} SET {$changes} {$filter_sql}"; $sql = "UPDATE {$this->table} SET {$changes} {$filter_sql}";
return $this->exec_bool($sql, $values); return $this->exec_bool($sql, $values);
} }
// Create Prepared Statemt for INSERT // Create Prepared Statemt for INSERT
public function insert(string $table, array $values): bool { public function insert(array $values): bool {
// Return CSV string with Prepared Statement abbreviatons from length of fields array. $this->throw_if_no_table();
$values_stmt = self::csv(array_fill(0, count($values), "?"));
// A value for each column in table model must be provided
if ($this->model && count($values) !== count($this->model)) {
throw new Exception("Values length does not match columns in model");
}
// Create CSV string with Prepared Statement abbreviatons from length of fields array.
$values_stmt = implode(",", array_fill(0, count($values), "?"));
// Interpolate components into an SQL INSERT statement and execute // Interpolate components into an SQL INSERT statement and execute
$sql = "INSERT INTO {$table} VALUES ({$values_stmt})"; $sql = "INSERT INTO {$this->table} VALUES ({$values_stmt})";
return $this->exec_bool($sql, $values); return $this->exec_bool($sql, $values);
} }
} }