aboutsummaryrefslogtreecommitdiff
path: root/lib/Minz/ModelPdo.php
diff options
context:
space:
mode:
authorGravatar Alexandre Alapetite <alexandre@alapetite.fr> 2023-04-28 14:01:11 +0200
committerGravatar GitHub <noreply@github.com> 2023-04-28 14:01:11 +0200
commitc72914bba2363e436574204b3d6093a6f3cfce89 (patch)
tree377008a7393e4d80e4c8659f27dd42c0ccbab382 /lib/Minz/ModelPdo.php
parent26e2a703125ffe1d0d2746b0e5ea3491b627832c (diff)
PHPStan Level 7 for more DAO PDO (#5328)
* PHPStan Level 7 for more DAO PDO With new function to address common type and check problems * A bit more * PHPStan Level 7 for FreshRSS_Entry
Diffstat (limited to 'lib/Minz/ModelPdo.php')
-rw-r--r--lib/Minz/ModelPdo.php60
1 files changed, 60 insertions, 0 deletions
diff --git a/lib/Minz/ModelPdo.php b/lib/Minz/ModelPdo.php
index dc3d0a42c..49556450e 100644
--- a/lib/Minz/ModelPdo.php
+++ b/lib/Minz/ModelPdo.php
@@ -179,4 +179,64 @@ class Minz_ModelPdo {
self::$sharedPdo = null;
self::$sharedCurrentUser = '';
}
+
+ /**
+ * @param array<string,int|string|null> $values
+ * @phpstan-return ($mode is PDO::FETCH_ASSOC ? array<array<string,int|string|null>>|null : array<int|string|null>|null)
+ * @return array<array<string,int|string|null>>|array<int|string|null>|null
+ */
+ private function fetchAny(string $sql, array $values, int $mode, int $column = 0): ?array {
+ $stm = $this->pdo->prepare($sql);
+ $ok = $stm !== false;
+ if ($ok && !empty($values)) {
+ foreach ($values as $name => $value) {
+ if (is_int($value)) $type = PDO::PARAM_INT;
+ elseif (is_string($value)) $type = PDO::PARAM_STR;
+ elseif (is_null($value)) $type = PDO::PARAM_NULL;
+ else {
+ $ok = false;
+ break;
+ }
+ if (!$stm->bindValue($name, $value, $type)) {
+ $ok = false;
+ break;
+ }
+ }
+ }
+ if ($ok && $stm !== false && $stm->execute()) {
+ switch ($mode) {
+ case PDO::FETCH_COLUMN:
+ $res = $stm->fetchAll(PDO::FETCH_COLUMN, $column);
+ break;
+ case PDO::FETCH_ASSOC:
+ default:
+ $res = $stm->fetchAll(PDO::FETCH_ASSOC);
+ break;
+ }
+ if ($res !== false) {
+ return $res;
+ }
+ }
+
+ $callingFunction = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function'] ?? '??';
+ $info = $stm == null ? $this->pdo->errorInfo() : $stm->errorInfo();
+ Minz_Log::error('SQL error ' . $callingFunction . ' ' . json_encode($info));
+ return null;
+ }
+
+ /**
+ * @param array<string,int|string|null> $values
+ * @return array<array<string,int|string|null>>|null
+ */
+ public function fetchAssoc(string $sql, array $values = []): ?array {
+ return $this->fetchAny($sql, $values, PDO::FETCH_ASSOC);
+ }
+
+ /**
+ * @param array<string,int|string|null> $values
+ * @return array<int|string|null>|null
+ */
+ public function fetchColumn(string $sql, int $column, array $values = []): ?array {
+ return $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, $column);
+ }
}