ptut-vhost/build/database/core/PDOWrapper/PDOWrapper.php

91 lines
2.5 KiB
PHP
Raw Normal View History

<?php
/**
* Created by PhpStorm.
* User: lucas
* Date: 30/08/16
* Time: 17:26
*/
namespace database\core\PDOWrapper;
class PDOWrapper extends \PDO
{
private $statements = [];
private $stacking = false;
public function __construct(String $dsn, String $username, String $passwd, array $options = [])
{
parent::__construct($dsn, $username, $passwd, $options);
}
public function prepare($statement, $options = [])
{
if($this->stacking){
return new PDOStatementWrapper($statement, $this);
}else{
parent::setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
return parent::prepare($statement, $options);
}
}
public function enableStacking(){
$this->stacking = true;
}
public function stackStatement(PDOStatementWrapper $st){
array_push($this->statements,$st);
}
public function executeStack(){
//init the statements and the generator of number
$finalStatement = '';
$finalExecute = [];
$i = 0;
//for each request stacked
foreach ($this->statements as $request){
$statement = $request->getStatement();
// we have to modify the parameters index at the same time that we modify the request, so we use static class attribute
$tempParametes = $request->getParameters();
//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++;
//delete the ':' at the beginning of the string
$tempKey = ltrim($matches[0],':');
//copy the parameter with the modified index
$tempParametes[$tempKey.$i] = $tempParametes[$tempKey];
//delete the old index
unset($tempParametes[$tempKey]);
//return the modified string for replacement
return $matches[0].$i;
},$statement),';').';';
$finalExecute = array_merge($finalExecute,$tempParametes);
}
//disable stacking
$this->stacking = false;
$this->beginTransaction();
$req = $this->prepare($finalStatement);
$success = $req->execute($finalExecute);
//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;
}
}