Pdo.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. /** @param array<int,int|string|bool>|null $options */
  8. public function __construct(string $dsn, ?string $username = null, ?string $passwd = null, ?array $options = null) {
  9. parent::__construct($dsn, $username, $passwd, $options);
  10. $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  11. }
  12. abstract public function dbType(): string;
  13. /** @var string */
  14. private $prefix = '';
  15. public function prefix(): string {
  16. return $this->prefix;
  17. }
  18. public function setPrefix(string $prefix): void {
  19. $this->prefix = $prefix;
  20. }
  21. private function autoPrefix(string $sql): string {
  22. return str_replace('`_', '`' . $this->prefix, $sql);
  23. }
  24. protected function preSql(string $statement): string {
  25. if (preg_match('/^(?:UPDATE|INSERT|DELETE)/i', $statement)) {
  26. invalidateHttpCache();
  27. }
  28. return $this->autoPrefix($statement);
  29. }
  30. // PHP8+: PDO::lastInsertId(?string $name = null): string|false
  31. /**
  32. * @param string|null $name
  33. * @return string|false
  34. */
  35. #[\ReturnTypeWillChange]
  36. public function lastInsertId($name = null) {
  37. if ($name != null) {
  38. $name = $this->preSql($name);
  39. }
  40. return parent::lastInsertId($name);
  41. }
  42. // PHP8+: PDO::prepare(string $query, array $options = []): PDOStatement|false
  43. /**
  44. * @param string $statement
  45. * @param array<int,string>|null $driver_options
  46. * @return PDOStatement|false
  47. */
  48. #[\ReturnTypeWillChange]
  49. public function prepare($statement, $driver_options = []) {
  50. $statement = $this->preSql($statement);
  51. return parent::prepare($statement, $driver_options);
  52. }
  53. // PHP8+: PDO::exec(string $statement): int|false
  54. /**
  55. * @param string $statement
  56. * @return int|false
  57. */
  58. #[\ReturnTypeWillChange]
  59. public function exec($statement) {
  60. $statement = $this->preSql($statement);
  61. return parent::exec($statement);
  62. }
  63. /** @return PDOStatement|false */
  64. #[\ReturnTypeWillChange]
  65. public function query(string $query, ?int $fetch_mode = null, ...$fetch_mode_args) {
  66. $query = $this->preSql($query);
  67. return $fetch_mode ? parent::query($query, $fetch_mode, ...$fetch_mode_args) : parent::query($query);
  68. }
  69. }