Pdo.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  6. */
  7. abstract class Minz_Pdo extends PDO {
  8. /**
  9. * @param array<int,int|string|bool>|null $options
  10. * @throws PDOException
  11. */
  12. public function __construct(string $dsn, ?string $username = null, ?string $passwd = null, ?array $options = null) {
  13. parent::__construct($dsn, $username, $passwd, $options);
  14. $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  15. }
  16. abstract public function dbType(): string;
  17. private string $prefix = '';
  18. public function prefix(): string {
  19. return $this->prefix;
  20. }
  21. public function setPrefix(string $prefix): void {
  22. $this->prefix = $prefix;
  23. }
  24. private function autoPrefix(string $sql): string {
  25. return str_replace('`_', '`' . $this->prefix, $sql);
  26. }
  27. protected function preSql(string $statement): string {
  28. if (preg_match('/^(?:UPDATE|INSERT|DELETE)/i', $statement) === 1) {
  29. invalidateHttpCache();
  30. }
  31. return $this->autoPrefix($statement);
  32. }
  33. /**
  34. * @throws PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`
  35. */
  36. #[\Override]
  37. public function lastInsertId(?string $name = null): string|false {
  38. if ($name != null) {
  39. $name = $this->preSql($name);
  40. }
  41. return parent::lastInsertId($name);
  42. }
  43. /**
  44. * @param array<int,string> $options
  45. * @throws PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`
  46. * @phpstan-ignore method.childParameterType
  47. */
  48. #[\Override]
  49. public function prepare(string $query, array $options = []): PDOStatement|false {
  50. $query = $this->preSql($query);
  51. return parent::prepare($query, $options);
  52. }
  53. /**
  54. * @throws PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`
  55. */
  56. #[\Override]
  57. public function exec(string $statement): int|false {
  58. $statement = $this->preSql($statement);
  59. return parent::exec($statement);
  60. }
  61. /**
  62. * @throws PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`
  63. */
  64. #[\Override]
  65. public function query(string $query, ?int $fetch_mode = null, ...$fetch_mode_args): PDOStatement|false {
  66. $query = $this->preSql($query);
  67. return $fetch_mode === null ? parent::query($query) : parent::query($query, $fetch_mode, ...$fetch_mode_args);
  68. }
  69. }