From d993fea6e16ff5a4cd20be211a75049e95060ef1 Mon Sep 17 00:00:00 2001 From: Yonas Habteab Date: Thu, 19 May 2022 16:56:23 +0200 Subject: [PATCH] Introduce DBUtils class --- library/Icinga/Util/DBUtils.php | 122 ++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 library/Icinga/Util/DBUtils.php diff --git a/library/Icinga/Util/DBUtils.php b/library/Icinga/Util/DBUtils.php new file mode 100644 index 000000000..6410c7ddb --- /dev/null +++ b/library/Icinga/Util/DBUtils.php @@ -0,0 +1,122 @@ +getDb(). + * And as we are using PDO transactions to manage the dashboards, this wouldn't work if $this->getDb() + * is called over again after a transaction has been initiated + * + * @return Connection + */ + public static function getConn(): Connection + { + if (self::$conn === null) { + self::$conn = (new self())->getDb(); + } + + return self::$conn; + } + + /** + * Get whether the DB connection being used is an instance of {@see Pgsql} + * + * @return bool + */ + public static function isPgsql(): bool + { + return self::getConn()->getAdapter() instanceof Pgsql; + } + + /** + * Get hex encoded uuid expression of the given binary data + * + * @param mixed $uuid + * + * @return Expression|string + */ + public static function getBinaryExpr($uuid) + { + if (! self::isPgsql() || ! self::isBinary($uuid)) { + return $uuid; + } + + return new Expression(sprintf("DECODE('%s', 'hex')", bin2hex($uuid))); + } + + /** + * Transform the given binary data into a valid hex format that pgsql can understand + * + * @param mixed $uuid + * + * @return mixed|string + */ + public static function binary2Hex($uuid) + { + if (! self::isPgsql() || ! self::isBinary($uuid)) { + return $uuid; + } + + return sprintf('\\x%s', bin2hex($uuid)); + } + + /** + * Transform boolean types to DB bool enums ('y', 'n') + * + * @param bool $value + * + * @return string + */ + public static function bool2BoolEnum(bool $value): string + { + return $value ? 'y' : 'n'; + } + + /** + * Get whether the given data is a binary string + * + * @param $data + * + * @return bool + */ + public static function isBinary($data): bool + { + // Stolen from php.net + $data = preg_replace('/\s/', '', $data ?? ''); + + return ! empty($data) && ! ctype_print($data); + } + + /** + * Transform binary values to hex format + * + * @param array $values + * + * @return void + */ + public static function transformValues(array &$values): void + { + foreach ($values as &$value) { + $value = DBUtils::binary2Hex($value); + } + } +}