Pdo.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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, throws.unusedType
  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. * @phpstan-ignore throws.unusedType
  56. */
  57. #[\Override]
  58. public function exec(string $statement): int|false {
  59. $statement = $this->preSql($statement);
  60. return parent::exec($statement);
  61. }
  62. /**
  63. * @throws PDOException if the attribute `PDO::ATTR_ERRMODE` is set to `PDO::ERRMODE_EXCEPTION`
  64. * @phpstan-ignore throws.unusedType
  65. */
  66. #[\Override]
  67. public function query(string $query, ?int $fetch_mode = null, ...$fetch_mode_args): PDOStatement|false {
  68. $query = $this->preSql($query);
  69. return $fetch_mode === null ? parent::query($query) : parent::query($query, $fetch_mode, ...$fetch_mode_args);
  70. }
  71. }