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. private string $prefix = '';
  14. public function prefix(): string {
  15. return $this->prefix;
  16. }
  17. public function setPrefix(string $prefix): void {
  18. $this->prefix = $prefix;
  19. }
  20. private function autoPrefix(string $sql): string {
  21. return str_replace('`_', '`' . $this->prefix, $sql);
  22. }
  23. protected function preSql(string $statement): string {
  24. if (preg_match('/^(?:UPDATE|INSERT|DELETE)/i', $statement) === 1) {
  25. invalidateHttpCache();
  26. }
  27. return $this->autoPrefix($statement);
  28. }
  29. // PHP8+: PDO::lastInsertId(?string $name = null): string|false
  30. /**
  31. * @param string|null $name
  32. * @return string|false
  33. */
  34. #[\ReturnTypeWillChange]
  35. public function lastInsertId($name = null) {
  36. if ($name != null) {
  37. $name = $this->preSql($name);
  38. }
  39. return parent::lastInsertId($name);
  40. }
  41. // PHP8+: PDO::prepare(string $query, array $options = []): PDOStatement|false
  42. /**
  43. * @param string $query
  44. * @param array<int,string> $options
  45. * @return PDOStatement|false
  46. * @phpstan-ignore-next-line
  47. */
  48. #[\ReturnTypeWillChange]
  49. public function prepare($query, $options = []) {
  50. $query = $this->preSql($query);
  51. return parent::prepare($query, $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 === null ? parent::query($query) : parent::query($query, $fetch_mode, ...$fetch_mode_args);
  68. }
  69. }