feat: first commit
This commit is contained in:
31
composer.json
Executable file
31
composer.json
Executable file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "gbili/pdowithfilters",
|
||||
"description": "PDO minimalistic abstraction allows for filtering sql query strings before execution",
|
||||
"authors" : [
|
||||
{
|
||||
"name" : "Guillermo Pages",
|
||||
"email" : "public.gullermo@gmail.com"
|
||||
}
|
||||
],
|
||||
"keywords": [
|
||||
"db",
|
||||
"req",
|
||||
"PDO"
|
||||
],
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Gbili\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Gbili\\": "tests/"
|
||||
}
|
||||
},
|
||||
"require": {
|
||||
"php": ">=8.0.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^9"
|
||||
}
|
||||
}
|
||||
55
src/PDOWithFilters.php
Normal file
55
src/PDOWithFilters.php
Normal file
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
namespace PdoWithFilters;
|
||||
|
||||
class PDOWithFilters {
|
||||
|
||||
private static \PDO $pdo;
|
||||
private static array $filtersConf = [];
|
||||
|
||||
public static function prepare($sql, array $filtersConf = []) {
|
||||
$filters = !empty($filtersConf) ? $filtersConf : self::$filtersConf;
|
||||
$finalSql = !empty($filters)
|
||||
? self::applyFilters($sql, $filters)
|
||||
: $sql;
|
||||
return self::$pdo->prepare($finalSql);
|
||||
}
|
||||
|
||||
public static function setFilters($filtesConf) {
|
||||
self::$filtersConf = $filtesConf;
|
||||
}
|
||||
|
||||
public static function applyFilter($sql, $needles, $needlesModifier) {
|
||||
$replacements = array_map(function ($needle) use ($needlesModifier) {
|
||||
return sprintf($needlesModifier, $needle);
|
||||
}, $needles);
|
||||
return str_replace($needles, $replacements, $sql);
|
||||
}
|
||||
|
||||
public static function applyFilters($sql, $filtersConf) {
|
||||
return array_reduce($filtersConf, function ($prev, $filterConf) {
|
||||
$needles = $filterConf['params']['needles'];
|
||||
$needlesModifier = $filterConf['params']['needle_modifier'];
|
||||
return self::applyFilter($prev, $needles, $needlesModifier);
|
||||
}, $sql);
|
||||
}
|
||||
|
||||
|
||||
public static function connect($dsn, $username, $password) {
|
||||
if (!empty($pdo)) {
|
||||
throw new \Exception('Create Pdo only once');
|
||||
}
|
||||
self::$pdo = new \PDO($dsn, $username, $password);
|
||||
|
||||
return self::$pdo;
|
||||
}
|
||||
|
||||
public static function getPDOInstance() {
|
||||
if (empty($pdo)) {
|
||||
throw new \Exception('You must call connect() first');
|
||||
}
|
||||
return self::$pdo;
|
||||
}
|
||||
|
||||
public static function prepareExecute($sql, $params) {
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user