Pdo.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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) === 1) {
  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 $query
  45. * @param array<int,string> $options
  46. * @return PDOStatement|false
  47. * @phpstan-ignore-next-line
  48. */
  49. #[\ReturnTypeWillChange]
  50. public function prepare($query, $options = []) {
  51. $query = $this->preSql($query);
  52. return parent::prepare($query, $options);
  53. }
  54. // PHP8+: PDO::exec(string $statement): int|false
  55. /**
  56. * @param string $statement
  57. * @return int|false
  58. */
  59. #[\ReturnTypeWillChange]
  60. public function exec($statement) {
  61. $statement = $this->preSql($statement);
  62. return parent::exec($statement);
  63. }
  64. /** @return PDOStatement|false */
  65. #[\ReturnTypeWillChange]
  66. public function query(string $query, ?int $fetch_mode = null, ...$fetch_mode_args) {
  67. $query = $this->preSql($query);
  68. return $fetch_mode === null ? parent::query($query) : parent::query($query, $fetch_mode, ...$fetch_mode_args);
  69. }
  70. }