From ab2fa56afed3e72378ef39cc1fb25f8ad9820cef Mon Sep 17 00:00:00 2001 From: "Matthew Wire (MJW Consulting)" Date: Tue, 18 Jun 2019 11:51:12 +0100 Subject: [PATCH] Remove some duplication in CRM_Utils_Type::escape/validate --- CRM/Utils/Type.php | 73 +++++++++------------------------------------- 1 file changed, 13 insertions(+), 60 deletions(-) diff --git a/CRM/Utils/Type.php b/CRM/Utils/Type.php index ef066db8f0..483e5629b1 100644 --- a/CRM/Utils/Type.php +++ b/CRM/Utils/Type.php @@ -233,19 +233,22 @@ class CRM_Utils_Type { * * @return mixed * The data, escaped if necessary. + * @throws \Exception */ public static function escape($data, $type, $abort = TRUE) { switch ($type) { case 'Integer': case 'Int': - if (CRM_Utils_Rule::integer($data)) { - return (int) $data; - } - break; - case 'Positive': - if (CRM_Utils_Rule::positiveInteger($data)) { - return (int) $data; + case 'Float': + case 'Money': + case 'Date': + case 'Timestamp': + case 'ContactReference': + case 'MysqlOrderByDirection': + $validatedData = self::validate($data, $type, $abort); + if (isset($validatedData)) { + return $validatedData; } break; @@ -287,43 +290,10 @@ class CRM_Utils_Type { } break; - case 'Float': - case 'Money': - if (CRM_Utils_Rule::numeric($data)) { - return $data; - } - break; - case 'String': case 'Memo': case 'Text': - return CRM_Core_DAO::escapeString($data); - - case 'Date': - case 'Timestamp': - // a null date or timestamp is valid - if (strlen(trim($data)) == 0) { - return trim($data); - } - - if ((preg_match('/^\d{8}$/', $data) || - preg_match('/^\d{14}$/', $data) - ) && - CRM_Utils_Rule::mysqlDate($data) - ) { - return $data; - } - break; - - case 'ContactReference': - if (strlen(trim($data)) == 0) { - return trim($data); - } - - if (CRM_Utils_Rule::validContact($data)) { - return (int) $data; - } - break; + return CRM_Core_DAO::escapeString(self::validate($data, $type, $abort)); case 'MysqlColumnNameOrAlias': if (CRM_Utils_Rule::mysqlColumnNameOrAlias($data)) { @@ -335,12 +305,6 @@ class CRM_Utils_Type { } break; - case 'MysqlOrderByDirection': - if (CRM_Utils_Rule::mysqlOrderByDirection($data)) { - return strtolower($data); - } - break; - case 'MysqlOrderBy': if (CRM_Utils_Rule::mysqlOrderBy($data)) { $parts = explode(',', $data); @@ -387,6 +351,7 @@ class CRM_Utils_Type { // @todo Use exceptions instead of CRM_Core_Error::fatal(). if ($abort) { $data = htmlentities($data); + CRM_Core_Error::fatal("$data is not of the type $type"); } return NULL; @@ -470,18 +435,6 @@ class CRM_Utils_Type { return $data; case 'Date': - // a null date is valid - if (strlen(trim($data)) == 0) { - return trim($data); - } - - if (preg_match('/^\d{8}$/', $data) && - CRM_Utils_Rule::mysqlDate($data) - ) { - return $data; - } - break; - case 'Timestamp': // a null timestamp is valid if (strlen(trim($data)) == 0) { @@ -504,7 +457,7 @@ class CRM_Utils_Type { } if (CRM_Utils_Rule::validContact($data)) { - return $data; + return (int) $data; } break; -- 2.25.1