Fix PhpDoc + fix PhpStan errors

This commit is contained in:
Unknown 2018-03-11 16:14:12 +01:00
parent 12e8d4ea92
commit 24f7c41705
10 changed files with 325 additions and 178 deletions

View File

@ -16,14 +16,14 @@
interface AuthSystem{
/* VERIFICATION DES ACCES EN FONCTION DE PERMISSIONS ATTENDUES
*
* @expected<array> Liste des permissions attendues
*
* @return error<Error> Erreur associée à la permission (Success/PermissionError/TokenError/etc)
*
*/
public static function permission($expected);
/** VERIFICATION DES ACCES EN FONCTION DE PERMISSIONS ATTENDUES
*
* @param array $expected Liste des permissions attendues
*
* @return Error Erreur associée à la permission (Success/PermissionError/TokenError/etc)
*
*/
public static function permission(array $expected) : Error;
}
?>

View File

@ -79,22 +79,19 @@
/* VERIFICATION DES ACCES EN FONCTION DE PERMISSIONS ATTENDUES
*
* @expected<array> Liste des permissions attendues
*
* @return error<Error> Erreur associée à la permission (Success/PermissionError/TokenError/etc)
*
*/
public static function permission($expected){
/** VERIFICATION DES ACCES EN FONCTION DE PERMISSIONS ATTENDUES
*
* @param array $expected Liste des permissions attendues
*
* @return Error Erreur associée à la permission (Success/PermissionError/TokenError/etc)
*
*/
public static function permission(array $expected) : Error{
/* (1) Check format -> if not array of array(s) -> ERROR
---------------------------------------------------------*/
/* (1) If not array -> ERROR */
if( !is_array($expected) )
return new Error(Err::FormatError);
/* (2) If not array of array(s) -> ERROR */
/* (1) If not array of array(s) -> ERROR */
foreach($expected as $permission_group)
if( !is_array($permission_group) )
return new Error(Err::FormatError);

View File

@ -16,15 +16,15 @@
class Checker{
/* VERIFICATIONS DES TYPES UTILES GENERIQUES
/** VERIFICATIONS DES TYPES UTILES GENERIQUES
*
* @type<String> Type que l'on veut verifier
* @value<mixed*> Valeur a verifier
* @param String $type Type que l'on veut verifier
* @param mixed $value Valeur a verifier
*
* @return match<Boolean> Retourne si oui ou non la valeur @value est du bon type @type
* @return Boolean Retourne si oui ou non la valeur @value est du bon type @type
*
*/
public static function run($type, $value){
public static function run(String $type, $value) : bool {
$checker = true;
/* [0] On verifie que $value n'est pas nul

View File

@ -11,23 +11,34 @@
/* (1) Attributes
---------------------------------------------------------*/
/* (1) Static */
/** @var Config? */
private static $inst = null; // singleton instance
private static function config_path(){ return __ROOT__.'/config/modules.json'; }
private static function config_path() : String { return __ROOT__.'/config/modules.json'; }
/** @var array[String] */
public static $allowed_http_methods = [ "GET", "POST", "PUT", "DELETE" ];
/* (2) Instance */
/** @var array */
private $raw;
/** @var array */
public $index;
/** @var Error */
public $error;
/* (2) Private constructor
/** (2) Private constructor
*
* @path<String> Configuration path
* @param String|null $path Configuration path
*
---------------------------------------------------------*/
private function __construct($path=null){
private function __construct(?String $path=null){
// Set default error
$this->error = new Error(Err::Success);
@ -116,9 +127,9 @@
/* (3) Static singleton 'get-or-create'
/** (3) Static singleton 'get-or-create'
*
* @return inst<Config> Configuration singleton
* @return Config Configuration singleton
*
---------------------------------------------------------*/
public static function get() : Config{

View File

@ -15,15 +15,15 @@
class ModuleFactory{
/* INSTANCIE UN MODULE
/** INSTANCIE UN MODULE
*
* @module<String> Nom du module
* @arguments<Array> [OPTIONNEL] Arguments à passer au constructeur
* @param String $module Nom du module
* @param array $arguments [OPTIONNEL] Arguments à passer au constructeur
*
* @return instance<Module> Instance du module en question
* @return object|false Instance du module en question
*
*/
public static function getModule($module, $arguments=[]){
public static function getModule(String $module, array $arguments=[]){
/* (1) On gère les arguments */
$arguments = is_array($arguments) ? $arguments : [];

View File

@ -13,28 +13,42 @@ use \error\core\Error;
class Request{
// Constantes
/** @var array[bool] */
private static $default_options = [ 'download' => false ];
/** @var AuthSystem|null */
private static $authsystem = null;
// Attributs prives utiles (initialisation)
/** @var array */
private $id; // chemin extrait de l'URI
/** @var array */
private $raw_params; // paramètres reçus
/** @var array */
private $params; // paramètres donnés à la fonction
/** @var array */
private $options; // options
/** @var String */
private $http_method; // methode HTTP appelante
// Contiendra l'etat de la requete
/** @var Error */
public $error;
/* (0) Constructeur d'une requete de module
/** (0) Constructeur d'une requete de module
*
* @uri<String> URI relative de l'appel
* @param<Array> Tableau associatif contenant les parametres utiles au traitement
* @forced_method<String> Méthode demandée (optionnel)
* @param String|null $uri URI relative de l'appel
* @param array|null $params Tableau associatif contenant les parametres utiles au traitement
* @param String|null $forced_method Méthode demandée (optionnel)
*
* @return instance<Request> Instance crée
*
---------------------------------------------------------*/
public function __construct($uri=null, $params=null, $forced_method=null){
@ -45,38 +59,44 @@ use \error\core\Error;
/* (1) Constructeur d'une requete de module (delegation)
/** (1) Constructeur d'une requete de module (delegation)
*
* @uri<String> URI relative de l'appel
* @param<Array> Tableau associatif contenant les parametres utiles au traitement
* @forced_method<String> Méthode demandée (optionnel)
* @param String|null $uri URI relative de l'appel
* @param array|null $params Tableau associatif contenant les parametres utiles au traitement
* @param String|null $forced_method Méthode demandée (optionnel)
*
* @return status<Boolean> Retourne si oui ou non tout s'est bien passe
* @return boolean Retourne si oui ou non tout s'est bien passe
*
---------------------------------------------------------*/
private function buildRequestObject($uri=null, $params=null, $forced_method=null){
private function buildRequestObject($uri=null, $params=null, $forced_method=null) :bool{
/* (1) Initialisation
---------------------------------------------------------*/
/* (1) Erreur par défaut */
$this->error = new Error(Err::Success);
/* (2) Si pas parametre manquant, on quitte */
if( is_null($uri) )
return $this->error->set(Err::MissingPath);
if( is_null($uri) ){
$this->error->set(Err::MissingPath);
return false;
}
/* (2) On vérifie la configuration
---------------------------------------------------------*/
/* (1) Dispatch if error */
if( Config::get()->error->get() != Err::Success )
return ($this->error = Config::get()->error);
if( Config::get()->error->get() != Err::Success ){
$this->error = Config::get()->error;
return false;
}
/* (3) Verification des types des parametres
---------------------------------------------------------*/
/* (1) Si path est une <string> */
if( !is_string($uri) ) // Si le type est incorrect
return $this->error->set(Err::WrongPathModule);
if( !is_string($uri) ){
$this->error->set(Err::WrongPathModule);
return false;
}
/* (2) Add slash at the beginning of URI */
if( !preg_match('@^\/@', $uri) )
@ -86,8 +106,10 @@ use \error\core\Error;
$this->raw_params = (is_array($params)) ? $params : [];
/* (4) On définit en constante la méthode HTTP */
if( !isset($_SERVER['REQUEST_METHOD']) && !is_string($forced_method) )
return $this->error->set(Err::UnknownHttpMethod);
if( !isset($_SERVER['REQUEST_METHOD']) && !is_string($forced_method) ){
$this->error->set(Err::UnknownHttpMethod);
return false;
}
$this->http_method = is_string($forced_method) ? strtoupper($forced_method) : strtoupper($_SERVER['REQUEST_METHOD']);
@ -130,14 +152,14 @@ use \error\core\Error;
/* (2) Definit le systeme d'authentification
/** (2) Definit le systeme d'authentification
*
* @instance<AuthSystem> Instance de type AuthSystem
* @param AuthSystem $instance Instance de type AuthSystem
*
* @return success<Boolean> Whether the AuthSystem is valid or not
* @return boolean Whether the AuthSystem is valid or not
*
---------------------------------------------------------*/
public static function setAuthSystem($instance=null){
public static function setAuthSystem( ?AuthSystem $instance=null) : bool{
/* (1) Check instance type */
if( !($instance instanceof AuthSystem) )
return false;
@ -150,20 +172,22 @@ use \error\core\Error;
/* (3) Verification du format et de la coherence du chemin specifie
/** (3) Verification du format et de la coherence du chemin specifie
*
* @URI<String> URI d'appel (commence par /)
* @param String $uri URI d'appel (commence par /)
*
* @return validity<Boolean> Retourne si oui ou non l'objet est correct
* @return boolean Retourne si oui ou non l'objet est correct
*
---------------------------------------------------------*/
private function checkURI($uri){
private function checkURI(String $uri) : bool{
/* (1) Verification format general
---------------------------------------------------------*/
/* (1) If wrong format -> exit */
if( !preg_match('@^\/[^\/]*(\/[^\/]*)*\/?$@', $uri) )
return $this->error->set(Err::WrongPathModule);
if( !preg_match('@^\/[^\/]*(\/[^\/]*)*\/?$@', $uri) ){
$this->error->set(Err::WrongPathModule);
return false;
}
/* (2) Add ending '/' if not there */
if( $uri[strlen($uri)-1] != '/' )
@ -189,8 +213,10 @@ use \error\core\Error;
}
/* (2) If @path not found -> exit */
if( is_null($path) )
return $this->error->set(Err::UnknownModule);
if( is_null($path) ){
$this->error->set(Err::UnknownModule);
return false;
}
/* (3) Extract URI parameters
@ -203,8 +229,10 @@ use \error\core\Error;
$uri_end = "/$uri_end";
/* (3) If invalid format, return error */
if( !preg_match('@^((?:\/[^\/]*)*)\/?$@', $uri_end, $uri_match) )
return $this->error->set(Err::InvalidURI);
if( !preg_match('@^((?:\/[^\/]*)*)\/?$@', $uri_end, $uri_match) ){
$this->error->set(Err::InvalidURI);
return false;
}
/* (4) Add each URI parameter to the parameter store */
$uri_args = array_slice( explode('/', $uri_match[1]), 1);
@ -220,12 +248,16 @@ use \error\core\Error;
$doc_req = $this->http_method == 'OPTIONS';
/* (2) Check if HTTP method is in allowed methods */
if( !in_array($this->http_method, Config::$allowed_http_methods) && !$doc_req )
return $this->error->set(Err::UnknownHttpMethod, $this->http_method);
if( !in_array($this->http_method, Config::$allowed_http_methods) && !$doc_req ){
$this->error->set(Err::UnknownHttpMethod, $this->http_method);
return false;
}
/* (3) Check if HTTP method is defined for this @path */
if( !isset(Config::get()->index[$path][$this->http_method]) && !$doc_req )
return $this->error->set(Err::UnknownMethod, $this->http_method);
if( !isset(Config::get()->index[$path][$this->http_method]) && !$doc_req ){
$this->error->set(Err::UnknownMethod, $this->http_method);
return false;
}
@ -242,12 +274,12 @@ use \error\core\Error;
/* (4) Retourne si on a la permission d'executer cette methode
/** (4) Retourne si on a la permission d'executer cette methode
*
* @return permission<bool> Retourne si on a les droits ou pas pour executer cette methode
* @return bool Retourne si on a les droits ou pas pour executer cette methode
*
---------------------------------------------------------*/
private function checkPermission(){
private function checkPermission() : bool{
/* (1) On recupere les informations utiles
---------------------------------------------------------*/
@ -264,8 +296,10 @@ use \error\core\Error;
if( !is_object(self::$authsystem) || !self::$authsystem instanceof AuthSystem ){
// try to load default AuthSystem
if( !file_exists(__BUILD__.'/api/core/AuthSystemDefault.php') )
return $this->error->set(Err::UnreachableResource);
if( !file_exists(__BUILD__.'/api/core/AuthSystemDefault.php') ){
$this->error->set(Err::UnreachableResource);
return false;
}
// load default AuthSystem class
$classname = '\\api\\core\\AuthSystemDefault';
@ -289,25 +323,29 @@ use \error\core\Error;
/* (5) Verification du type des parametres envoyes
/** (5) Verification du type des parametres envoyes
*
* @return correct<bool> Retourne si oui ou non les parametres ont le bon type
* @return bool Retourne si oui ou non les parametres ont le bon type
*
---------------------------------------------------------*/
private function checkParams(){
private function checkParams() : bool{
/* (1) On verifie qu'il ne manque aucun parametre
---------------------------------------------------------*/
/* (1) Si @params n'est pas un tableau */
if( !is_array($this->raw_params) )
return $this->error->set(Err::MissingParam);
if( !is_array($this->raw_params) ){
$this->error->set(Err::MissingParam);
return false;
}
/* (2) On récupère les données de la méthode */
$method = Config::get()->index[$this->id['path']][$this->id['method']];
/* (3) Si pas 'parameters' dans la config */
if( !isset($method['par']) || !is_array($method['par']) )
return $this->error->set(Err::ConfigError);
if( !isset($method['par']) || !is_array($method['par']) ){
$this->error->set(Err::ConfigError);
return false;
}
/* (2) Si le type est defini, pour chaque param, on teste
@ -317,16 +355,22 @@ use \error\core\Error;
/* (2.1) Vérification des données
---------------------------------------------------------*/
/* (1) Si @name n'est pas une string */
if( !is_string($name) )
return $this->error->set(Err::ConfigError);
if( !is_string($name) ){
$this->error->set(Err::ConfigError);
return false;
}
/* (2) Si @config n'est pas un tableau */
if( !is_array($config) )
return $this->error->set(Err::ConfigError);
if( !is_array($config) ){
$this->error->set(Err::ConfigError);
return false;
}
/* (3) So @config['typ] manquant ou incorrect */
if( !isset($config['typ']) || !is_string($config['typ']) )
return $this->error->set(Err::ConfigError);
if( !isset($config['typ']) || !is_string($config['typ']) ) {
$this->error->set(Err::ConfigError);
return false;
}
/* (2.2) Gestion des spécifications
@ -349,10 +393,12 @@ use \error\core\Error;
$default = $config['def'];
/* (3.1.2) If FILE and not null -> Check type */
if( $config['typ'] != 'FILE' || $default != null )
if( !Checker::run($config['typ'], $default) )
return $this->error->set(Err::WrongDefaultParam, $rename, $config['typ']);
if( $config['typ'] != 'FILE' || $default != null ){
if( !Checker::run($config['typ'], $default) ) {
$this->error->set(Err::WrongDefaultParam, $rename, $config['typ']);
return false;
}
}
}
/* (4) Si de type 'FILE' + fichier existe => on enregistre la ref. */
@ -360,8 +406,10 @@ use \error\core\Error;
$this->params[$rename] = &$_FILES[$name];
/* (4) Si param obligatoire et manquant -> erreur */
if( !isset($this->raw_params[$name]) && !$optional )
return $this->error->set(Err::MissingParam, $rename);
if( !isset($this->raw_params[$name]) && !$optional ) {
$this->error->set(Err::MissingParam, $rename);
return false;
}
/* (2.3) Gestion des valeurs
@ -383,8 +431,10 @@ use \error\core\Error;
$this->raw_params[$name] = $json_rep['json'];
// Si la verification est fausse, on retourne faux
if( !Checker::run($config['typ'], $this->raw_params[$name]) )
return $this->error->set(Err::WrongParam, $rename, $config['typ']);
if( !Checker::run($config['typ'], $this->raw_params[$name]) ){
$this->error->set(Err::WrongParam, $rename, $config['typ']);
return false;
}
// Sinon, on ajoute aux params qu'on enverra à l'appel
else
@ -403,12 +453,12 @@ use \error\core\Error;
/* (6) Ajout des options a partir de la configuration
/** (6) Ajout des options a partir de la configuration
*
* @return correct<bool> Retourne FAUS en cas d'erreur
* @return bool Retourne FAUS en cas d'erreur
*
---------------------------------------------------------*/
private function buildOptions(){
private function buildOptions() : bool{
/* (1) On récupère les options de la méthode en cours
---------------------------------------------------------*/
@ -448,12 +498,12 @@ use \error\core\Error;
/* (7) Execute le traitement associe et remplie la reponse
/** (7) Execute le traitement associe et remplie la reponse
*
* @return answer<Response> Retourne une reponse de type <Response> si tout s'est bien passe
* @return Response Retourne une reponse de type <Response> si tout s'est bien passe
*
---------------------------------------------------------*/
public function dispatch(){
public function dispatch() : Response{
/* (1) Vérifications de niveau 0
---------------------------------------------------------*/
@ -516,10 +566,11 @@ use \error\core\Error;
/* (8) Gestion d'un téléchargement HTTP
*
*/
public function download($returned){
/** (8) Gestion d'un téléchargement HTTP
*
* @return Response
*/
public function download($returned) : Response{
/* (1) Vérification des erreurs et paramètres
---------------------------------------------------------*/
@ -556,7 +607,7 @@ use \error\core\Error;
/* (2) On affiche le contenu */
echo $returned['body'];
return true;
return new Response();
}
@ -605,12 +656,13 @@ use \error\core\Error;
/* (9) Getter générique
/** (9) Getter générique
*
* @index<String> Index de l'attribut
* @param String $index Index de l'attribut
*
* @return mixed
---------------------------------------------------------*/
public function get($index=null){
public function get(?String $index=null){
switch($index){

View File

@ -17,31 +17,36 @@
class Response{
// Attributs prives utiles (initialisation)
/** @var array */
private $data;
/** @var Error */
public $error;
/* CONSTRUCTEUR D'UNE REPONSE DE MODULE
/** CONSTRUCTEUR D'UNE REPONSE DE MODULE
*
* @error<ModuleError> Erreur passee par la requete (si existe)
* @param Error $error Erreur passee par la requete (si existe)
*
*/
public function __construct($error=null){
public function __construct(?Error $error=null){
if( !( $error instanceof Error ) )
$error = new Error(Err::Success);
$this->data = [];
$this->error = $error;
}
/* AJOUTE UNE DONNEE A LA REPONSE
/** AJOUTE UNE DONNEE A LA REPONSE
*
* @key<String> Le nom de la valeur a ajouter
* @value<mixed*> La valeur a ajouter
* @param String $key Le nom de la valeur a ajouter
* @param mixed $value La valeur a ajouter
*
* @return Response
*/
public function append($key, $value){
public function append(String $key, $value) : Response{
// Ajoute une entree pour la cle @key et de valeur @value
$this->data[$key] = $value;
@ -49,12 +54,13 @@
}
/* AJOUTE TOUTES LES DONNEES A LA REPONSE
/** AJOUTE TOUTES LES DONNEES A LA REPONSE
*
* @dataset<Array> Le tableau associatif correspondant a la reponse
* @param array $dataset Le tableau associatif correspondant a la reponse
*
* @return Response
*/
public function appendAll($dataset){
public function appendAll(array $dataset) : Response{
// Si ce n'est pas un tableau, on ne fais rien
if( !is_array($dataset) )
return $this;
@ -72,17 +78,16 @@
return $this;
}
/* RECUPERE UNE DONNEE DE LA REPONSE
/** RECUPERE UNE DONNEE DE LA REPONSE
*
* @key<String> Le nom de la valeur a recuperer
* @param String $key Le nom de la valeur a recuperer
*
* @return value<mixed*> La valeur a cette cle
* @return error<null> Retourne NULL si aucune valeur pour cette cle
* @return mixed|null La valeur a cette cle, NULL si aucune valeur pour cette cle
*
*/
public function get($key){
public function get(String $key){
// Si la valeur de cle @key n'existe pas, on retourne NULL
if( !isset($this->data[$key]) )
return null;
@ -92,9 +97,9 @@
}
/* RECUPERE TOUTES LES DONNEES DE LA REPONSE
/** RECUPERE TOUTES LES DONNEES DE LA REPONSE
*
* @return data<Array> Les donnees de la reponse
* @return array Les donnees de la reponse
*
*/
public function getAll(){
@ -103,12 +108,12 @@
}
/* SERIALISATION A PARTIR DES DONNEES
/** SERIALISATION A PARTIR DES DONNEES
*
* @return json<String> Retourne les donnees serialisees
* @return String Retourne les donnees serialisees
*
*/
public function serialize(){
public function serialize() : String{
// Code Http
$this->error->setHttpCode();

View File

@ -19,7 +19,7 @@
class DatabaseDriver{
/* STATIC ATTRIBUTES */
private static function conf(){
private static function conf() : array{
// YOUR CONFIGURATION BEHIND
$path = __CONFIG__.'/database-driver.json';
@ -37,11 +37,10 @@
return $parsed;
}
private static $path; // Databases configurations files
private static $config; // PDO configurations
/** @var DatabaseDriver[] */
private static $instance = []; // Database driver instance list
/** @var Error */
public $error;
/* ATTRIBUTES */
@ -53,15 +52,16 @@
/* CONSTRUCTOR OF A DATABASE DRIVER
/** CONSTRUCTOR OF A DATABASE DRIVER
*
* @host<String> Database Server's host
* @dbname<String> Database name
* @username<String> Database username
* @password<String> Database password
* @param String $host Database Server's host
* @param String $dbname Database name
* @param String $username Database username
* @param String $password Database password
* @param bool $debug
*
*/
private function __construct($host, $dbname, $username, $password, $debug = false){
private function __construct(String $host, String $dbname, String $username, String $password, bool $debug = false){
/* (2) Stores configuration */
$this->host = $host;
$this->dbname = $dbname;
@ -98,22 +98,20 @@
**** Multiton Management (static) ****
************************************************/
/* ADDS A NEW CONNECTION
/** ADDS A NEW CONNECTION
*
* @label<String> [optional] Database Label
* @param String $label [optional] Database Label
*
* @return status<Boolean> If added successfully
* @return boolean If added successfully
*
*/
private static function add($label=null){
private static function add(String $label='default') : bool{
$conf = self::conf();
/* [1] Default values
=========================================================*/
/* (1) If label isn't given */
is_null($label) && ($label = 'default');
/* (2) If label and no path */
/* (1) If label and no path */
if( $label !== 'default' && !isset($conf[$label]) )
return false;
@ -145,22 +143,20 @@
}
/* GET A DATABASE DRIVER INSTANCE
/** GET A DATABASE DRIVER INSTANCE
*
* @label<String> [optional] Driver's label
*
* @return driver<Database> Multiton
* @param String $label [optional] Driver's label
* @throws \Exception
* @return DatabaseDriver Multiton
*
*/
public static function get($label=null){
public static function get(String $label='default') : DatabaseDriver{
$conf = self::conf();
/* [1] Checks arguments
=========================================================*/
/* (1) Label default value */
is_null($label) && ($label = 'default');
/* (2) If no label, or unknown label */
/* (1) If no label, or unknown label */
if( !isset(self::$instance[$label]) ){
/* (2.1) Try to add the configuration if exists */
@ -181,21 +177,31 @@
/** retourne la connection statique
* @param null $label
* @param String|null $label
* @throws \Exception
* @return \PDO
*/
public static function getPDO($label=null){
$instance = self::get($label);
public static function getPDO(?String $label=null) : \PDO{
if(is_string($label)){
$instance = self::get($label);
}else{
$instance = self::get();
}
return $instance->pdo;
}
/**
* @return \PDO
*/
public function pdo(){
return $this->pdo;
}
/**
* @return array
*/
public function getConfig(){
return [
'host' => $this->host,
@ -204,18 +210,30 @@
];
}
/**
* enable request stacking
*/
public function enableStacking(){
$this->pdo->enableStacking();
}
/**
* send all the stacked request and flush the stack
*/
public function flushStack(){
$this->pdo->executeStack();
}
/** get all debug data
* @return array
*/
public function getDebug() : array{
return $this->pdo->getDebug();
}
/**
* @return bool
*/
public function isDebugEnabled() : bool {
return $this->pdo->isDebugEnabled();
}

View File

@ -11,11 +11,21 @@ namespace database\core\PDOWrapper;
class PDOStatementWrapper extends \PDOStatement
{
/** @var String */
private $statement;
/** @var array */
private $parameters;
/** @var PDOWrapper */
private $connexion;
public function __construct($statement, PDOWrapper $connexion)
/**
* PDOStatementWrapper constructor.
* @param String $statement
* @param PDOWrapper $connexion
*/
public function __construct(String $statement, PDOWrapper $connexion)
{
$this->statement = $statement;
$this->connexion = $connexion;
@ -23,7 +33,11 @@ class PDOStatementWrapper extends \PDOStatement
}
public function execute($input_parameters = [])
/**
* @param array $input_parameters
* @return bool
*/
public function execute($input_parameters = []) : bool
{
$this->parameters = $input_parameters;
$this->connexion->stackStatement($this);
@ -33,7 +47,7 @@ class PDOStatementWrapper extends \PDOStatement
/**
* @return string
*/
public function getStatement()
public function getStatement() : String
{
return $this->statement;
}
@ -41,7 +55,7 @@ class PDOStatementWrapper extends \PDOStatement
/**
* @return array
*/
public function getParameters()
public function getParameters() : array
{
return $this->parameters;
}

View File

@ -11,17 +11,36 @@ namespace database\core\PDOWrapper;
class PDOWrapper extends \PDO
{
/** @var PDOStatementWrapper[] */
private $statements = [];
/** @var bool */
private $stacking = false;
/** @var array */
private $debug = [];
/** @var bool */
private $debugEnabled = false;
/**
* PDOWrapper constructor.
* @param String $dsn
* @param String $username
* @param String $passwd
* @param array $options
*/
public function __construct(String $dsn, String $username, String $passwd, array $options = [])
{
parent::__construct($dsn, $username, $passwd, $options);
}
public function prepare($statement, $options = [])
/**
* @param string $statement
* @param array $options
* @return \PDOStatement
*/
public function prepare($statement, $options = []) : \PDOStatement
{
if($this->debugEnabled){
$this->storeDebug();
@ -30,12 +49,16 @@ class PDOWrapper extends \PDO
if($this->stacking){
return new PDOStatementWrapper($statement, $this);
}else{
parent::setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
return parent::prepare($statement, $options);
}
}
/**
* @throws \ReflectionException
*
* @return void
*/
private function storeDebug(){
//get all the debug info about the repo
$prepareStack = debug_backtrace(0,3)[1];
@ -70,30 +93,52 @@ class PDOWrapper extends \PDO
$this->debug[] = $result;
}
/**
* @return array
*/
public function getDebug() : array{
return $this->debug;
}
/**
* Enable request stacking
*/
public function enableStacking(){
$this->stacking = true;
}
/**
* @return bool
*/
public function isDebugEnabled() : bool{
return $this->debugEnabled;
}
/**
* @param PDOStatementWrapper $st
*/
public function stackStatement(PDOStatementWrapper $st){
array_push($this->statements,$st);
}
/**
* Enable repo debug
*/
public function enableDebug(){
$this->debugEnabled = true;
}
/**
* disable repo debug
*/
public function disableDebug(){
$this->debugEnabled = false;
}
/** Execute the stored request stack
* @return bool
*/
public function executeStack(){
//init the statements and the generator of number
$finalStatement = '';
@ -109,20 +154,20 @@ class PDOWrapper extends \PDO
//find the given pattern in the request, then call our function and replace the matched string by the return value of our function
$finalStatement .= rtrim(preg_replace_callback("/(:[a-z_\-0-9]*)/is",function($matches) use (&$i,&$tempParametes){
//get next number
$i++;
//get next number
$i++;
//delete the ':' at the beginning of the string
$tempKey = ltrim($matches[0],':');
//delete the ':' at the beginning of the string
$tempKey = ltrim($matches[0],':');
//copy the parameter with the modified index
$tempParametes[$tempKey.$i] = $tempParametes[$tempKey];
//copy the parameter with the modified index
$tempParametes[$tempKey.$i] = $tempParametes[$tempKey];
//delete the old index
unset($tempParametes[$tempKey]);
//delete the old index
unset($tempParametes[$tempKey]);
//return the modified string for replacement
return $matches[0].$i;
//return the modified string for replacement
return $matches[0].$i;
},$statement),';').';';
$finalExecute = array_merge($finalExecute,$tempParametes);
@ -131,6 +176,9 @@ class PDOWrapper extends \PDO
//disable stacking
$this->stacking = false;
//enable prepare emulation (native prepare do not accept stacked requests
parent::setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
$this->beginTransaction();
$req = $this->prepare($finalStatement);
@ -139,9 +187,11 @@ class PDOWrapper extends \PDO
//as we execute multiple query that we don't fetch, we have to close the cursor if we want to do other requests later
$req->closeCursor();
$this->commit();
//using beginTransaction/commit disable the autocommit, we re-activate it
$this->setAttribute(\PDO::ATTR_AUTOCOMMIT,1);
parent::setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
return $success;
}
}