From c72914bba2363e436574204b3d6093a6f3cfce89 Mon Sep 17 00:00:00 2001 From: Alexandre Alapetite Date: Fri, 28 Apr 2023 14:01:11 +0200 Subject: 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 --- lib/Minz/ModelPdo.php | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'lib/Minz/ModelPdo.php') 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 $values + * @phpstan-return ($mode is PDO::FETCH_ASSOC ? array>|null : array|null) + * @return array>|array|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 $values + * @return array>|null + */ + public function fetchAssoc(string $sql, array $values = []): ?array { + return $this->fetchAny($sql, $values, PDO::FETCH_ASSOC); + } + + /** + * @param array $values + * @return array|null + */ + public function fetchColumn(string $sql, int $column, array $values = []): ?array { + return $this->fetchAny($sql, $values, PDO::FETCH_COLUMN, $column); + } } -- cgit v1.2.3