Pdo.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /**
  3. * MINZ - Copyright 2011 Marien Fressinaud
  4. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  5. */
  6. abstract class Minz_Pdo extends PDO {
  7. public function __construct(string $dsn, $username = null, $passwd = null, $options = null) {
  8. parent::__construct($dsn, $username, $passwd, $options);
  9. $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  10. }
  11. abstract public function dbType();
  12. private $prefix = '';
  13. public function prefix(): string {
  14. return $this->prefix;
  15. }
  16. public function setPrefix(string $prefix) {
  17. $this->prefix = $prefix;
  18. }
  19. private function autoPrefix(string $sql): string {
  20. return str_replace('`_', '`' . $this->prefix, $sql);
  21. }
  22. protected function preSql(string $statement): string {
  23. if (preg_match('/^(?:UPDATE|INSERT|DELETE)/i', $statement)) {
  24. invalidateHttpCache();
  25. }
  26. return $this->autoPrefix($statement);
  27. }
  28. // PHP8+: PDO::lastInsertId(?string $name = null): string|false
  29. #[\ReturnTypeWillChange]
  30. public function lastInsertId($name = null) {
  31. if ($name != null) {
  32. $name = $this->preSql($name);
  33. }
  34. return parent::lastInsertId($name);
  35. }
  36. // PHP8+: PDO::prepare(string $query, array $options = []): PDOStatement|false
  37. #[\ReturnTypeWillChange]
  38. public function prepare(string $statement, array $driver_options = []) {
  39. $statement = $this->preSql($statement);
  40. return parent::prepare($statement, $driver_options);
  41. }
  42. // PHP8+: PDO::exec(string $statement): int|false
  43. #[\ReturnTypeWillChange]
  44. public function exec(string $statement) {
  45. $statement = $this->preSql($statement);
  46. return parent::exec($statement);
  47. }
  48. // PHP8+: PDO::query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs): PDOStatement|false
  49. #[\ReturnTypeWillChange]
  50. public function query($query, $fetch_mode = null, ...$fetch_mode_args) {
  51. $query = $this->preSql($query);
  52. return $fetch_mode ? parent::query($query, $fetch_mode, ...$fetch_mode_args) : parent::query($query);
  53. }
  54. }