From aeae4721cdc46699200bb15db0140a34e36a67f1 Mon Sep 17 00:00:00 2001 From: Ondrej Hlavacek Date: Thu, 18 Feb 2016 13:58:25 +0100 Subject: [PATCH] switch from static class functions to namespaced functions --- composer.json | 24 +- .../Utils/{Exception => }/Exception.php | 2 +- .../Utils/Exception/EvalStringException.php | 7 - .../Utils/Exception/JsonDecodeException.php | 2 + .../Utils/Exception/NoDataFoundException.php | 2 + src/Keboola/Utils/Utils.php | 456 ------------------ src/Keboola/Utils/arrayToObject.php | 16 + src/Keboola/Utils/buildUrl.php | 45 ++ src/Keboola/Utils/camelize.php | 16 + src/Keboola/Utils/flattenArray.php | 24 + src/Keboola/Utils/formatDateTime.php | 16 + src/Keboola/Utils/getDataFromPath.php | 38 ++ src/Keboola/Utils/httpBuildUrl.php | 42 ++ src/Keboola/Utils/isEmptyObject.php | 25 + src/Keboola/Utils/isValidDateTimeString.php | 28 ++ src/Keboola/Utils/jsonDecode.php | 64 +++ src/Keboola/Utils/objectToArray.php | 20 + src/Keboola/Utils/replaceDates.php | 21 + src/Keboola/Utils/replaceDatesInArray.php | 18 + src/Keboola/Utils/returnBytes.php | 27 ++ src/Keboola/Utils/sanitizeUtf8.php | 12 + tests/Keboola/Utils/ArrayToObjectTest.php | 38 ++ tests/Keboola/Utils/BuildUrlTest.php | 12 + tests/Keboola/Utils/CamelizeTest.php | 16 + tests/Keboola/Utils/FlattenArrayTest.php | 27 ++ tests/Keboola/Utils/FormatDateTimeTest.php | 13 + tests/Keboola/Utils/GetDataFromPathTest.php | 43 ++ tests/Keboola/Utils/HttpBuildUrlTest.php | 21 + tests/Keboola/Utils/IsEmptyObjectTest.php | 14 + .../Utils/IsValidDateTimeStringTest.php | 20 + tests/Keboola/Utils/JsonDecodeTest.php | 26 + tests/Keboola/Utils/ObjectToArrayTest.php | 37 ++ .../Keboola/Utils/ReplaceDatesInArrayTest.php | 36 ++ tests/Keboola/Utils/ReplaceDatesTest.php | 13 + tests/Keboola/Utils/ReturnBytesTest.php | 23 + tests/Keboola/Utils/SanitizeUtf8Test.php | 13 + tests/Keboola/Utils/UtilsTest.php | 213 -------- 37 files changed, 791 insertions(+), 679 deletions(-) mode change 100755 => 100644 composer.json rename src/Keboola/Utils/{Exception => }/Exception.php (91%) delete mode 100755 src/Keboola/Utils/Exception/EvalStringException.php delete mode 100755 src/Keboola/Utils/Utils.php create mode 100644 src/Keboola/Utils/arrayToObject.php create mode 100644 src/Keboola/Utils/buildUrl.php create mode 100644 src/Keboola/Utils/camelize.php create mode 100644 src/Keboola/Utils/flattenArray.php create mode 100644 src/Keboola/Utils/formatDateTime.php create mode 100644 src/Keboola/Utils/getDataFromPath.php create mode 100644 src/Keboola/Utils/httpBuildUrl.php create mode 100644 src/Keboola/Utils/isEmptyObject.php create mode 100644 src/Keboola/Utils/isValidDateTimeString.php create mode 100644 src/Keboola/Utils/jsonDecode.php create mode 100644 src/Keboola/Utils/objectToArray.php create mode 100644 src/Keboola/Utils/replaceDates.php create mode 100644 src/Keboola/Utils/replaceDatesInArray.php create mode 100644 src/Keboola/Utils/returnBytes.php create mode 100644 src/Keboola/Utils/sanitizeUtf8.php create mode 100755 tests/Keboola/Utils/ArrayToObjectTest.php create mode 100755 tests/Keboola/Utils/BuildUrlTest.php create mode 100755 tests/Keboola/Utils/CamelizeTest.php create mode 100755 tests/Keboola/Utils/FlattenArrayTest.php create mode 100755 tests/Keboola/Utils/FormatDateTimeTest.php create mode 100755 tests/Keboola/Utils/GetDataFromPathTest.php create mode 100755 tests/Keboola/Utils/HttpBuildUrlTest.php create mode 100755 tests/Keboola/Utils/IsEmptyObjectTest.php create mode 100755 tests/Keboola/Utils/IsValidDateTimeStringTest.php create mode 100755 tests/Keboola/Utils/JsonDecodeTest.php create mode 100755 tests/Keboola/Utils/ObjectToArrayTest.php create mode 100755 tests/Keboola/Utils/ReplaceDatesInArrayTest.php create mode 100755 tests/Keboola/Utils/ReplaceDatesTest.php create mode 100755 tests/Keboola/Utils/ReturnBytesTest.php create mode 100755 tests/Keboola/Utils/SanitizeUtf8Test.php delete mode 100755 tests/Keboola/Utils/UtilsTest.php diff --git a/composer.json b/composer.json old mode 100755 new mode 100644 index 57f3b72..c719441 --- a/composer.json +++ b/composer.json @@ -6,12 +6,15 @@ "authors": [ { "name": "Ondrej Vana", - "email": "kachna@keboola.cz" + "email": "kachna@keboola.com" + }, + { + "name": "Ondrej Hlavacek", + "email": "ondrej.hlavacek@keboola.com" } ], "require": { "keboola/php-temp": "~0.1.0", - "keboola/php-csvtable": "~0.1.1", "php": ">=5.5.0", "seld/jsonlint": "^1.4" }, @@ -22,6 +25,23 @@ }, "autoload": { + "files": [ + "src/Keboola/Utils/jsonDecode.php", + "src/Keboola/Utils/sanitizeUtf8.php", + "src/Keboola/Utils/objectToArray.php", + "src/Keboola/Utils/formatDateTime.php", + "src/Keboola/Utils/replaceDates.php", + "src/Keboola/Utils/replaceDatesInArray.php", + "src/Keboola/Utils/buildUrl.php", + "src/Keboola/Utils/httpBuildUrl.php", + "src/Keboola/Utils/returnBytes.php", + "src/Keboola/Utils/camelize.php", + "src/Keboola/Utils/getDataFromPath.php", + "src/Keboola/Utils/isValidDateTimeString.php", + "src/Keboola/Utils/flattenArray.php", + "src/Keboola/Utils/arrayToObject.php", + "src/Keboola/Utils/isEmptyObject.php" + ], "psr-0": { "Keboola\\Utils": "src/" } diff --git a/src/Keboola/Utils/Exception/Exception.php b/src/Keboola/Utils/Exception.php similarity index 91% rename from src/Keboola/Utils/Exception/Exception.php rename to src/Keboola/Utils/Exception.php index 1a2987e..f22cb90 100755 --- a/src/Keboola/Utils/Exception/Exception.php +++ b/src/Keboola/Utils/Exception.php @@ -1,5 +1,5 @@ lint($json); - - $errData['errDetail'] = $errLint instanceof ParsingException - ? $errLint->getMessage() - : null; - } - - if (!empty($errData)) { - $e->setData($errData); - } - - throw $e; - } - - /** - * @brief Convert an array, object or a JSON string to associative array. - * - * @param mixed $data Data to convert - * @return array - * @throws JsonDecodeException - * @throws \Exception - * @deprecated - */ - public static function to_assoc($data) - { - if (is_string($data)) { // TODO expand for XML - return self::json_decode($data, true); - } elseif (is_object($data) || is_array($data)) { - $data = (array) $data; - foreach ($data as $key => $value) { - if (is_object($value) || is_array($value)) { - $data[$key] = self::to_assoc($value); - } - } - return $data; - } else { - $type = gettype($data); - throw new \Exception("Data to parse has to be either an array, object or a JSON string. {$type} provided."); - } - } - - /** - * Convert an object to associative array - * - * @param object $object - * @return array - */ - public static function objectToArray($object) - { - $data = (array) $object; - foreach ($data as $key => $value) { - if (is_object($value) || is_array($value)) { - $data[$key] = self::objectToArray($value); - } - } - return $data; - } - - /** - * @brief Create a CSV file in application's temp folder, and optionally set its header - * - * @param \Keboola\Temp\Temp $temp - * @param string $fileName File name Suffix - * @param array $header A header line to write into created file - * @return \Keboola\Csv\Table - * @deprecated Use \Keboola\CsvTable\Table::create($fileName, $header, $temp); - */ - public static function createCsv(Temp $temp, $fileName, array $header = array()) - { - return Table::create($fileName, $header, $temp); - } - - /** - * @param $dateTime - * @param string $format - * @param null $timezone - * @return string - */ - public static function formatDateTime($dateTime, $format = DATE_W3C, $timezone = null) - { - $dtzObj = $timezone ? new \DateTimeZone($timezone) : null; - $dtObj = new \DateTime($dateTime, $dtzObj); - return $dtObj->format($format); - } - - /** - * @param $string - * @param string $tag - * @param string $format - * @param null $timezone - * @return mixed - */ - public static function replaceDates($string, $tag = '%%', $format = DATE_W3C, $timezone = null) - { - return preg_replace_callback( - '/'.preg_quote($tag).'(.*?)'.preg_quote($tag).'/', - function ($matches) use ($format, $timezone) { - return self::formatDateTime($matches[1], $format, $timezone); - }, - $string - ); - } - - /** - * @param $array - * @param string $tag - * @param string $format - * @param null $timezone - * @return mixed - */ - public static function replaceDatesInArray($array, $tag = '%%', $format = DATE_W3C, $timezone = null) - { - array_walk_recursive($array, function (&$string, $key, $settings) { - $string = self::replaceDates($string, $settings['tag'], $settings['format'], $settings['timezone']); - }, ['tag' => $tag, 'format' => $format, 'timezone' => $timezone]); - return $array; - } - - /** - * @brief Inject query into an URL string - * - * @param string $url - * @param array $query Associative array containing query - * @return string Altered URL - */ - public static function buildUrl($url, array $query = null) - { - if (!empty($query)) { - // Cleanup the input array to prevent empty Keys - foreach ($query as $k => $v) { - if (empty($k)) { - unset($query[$k]); - } - } - - # Parse the url to get a query string - $parsed = parse_url($url); - - # If a query string is set, parse it into an associative array (..&key=value => array("key" => "value")) - if (isset($parsed["query"]) && strlen($parsed["query"]) > 0) { - $newQuery = array(); - $pairs = explode("&", $parsed["query"]); - foreach ($pairs as $pair) { - list($key, $val) = explode("=", $pair, 2); - $newQuery[$key] = urldecode($val); - } - # Add/Replace parameters from $query - $newQuery = array_replace($newQuery, $query); - } else { - $newQuery = $query; - } - $parsed["query"] = http_build_query($newQuery); - - # Rebuild the query back - $url = self::http_build_url($parsed); - } - - return $url; - } - - /** - * @brief PECL http_build_query() replacement. - * Takes an array containing information about a parsed URL and rebuilds the URL from it. - * See http://php.net/manual/en/function.http-build-url.php - * - * @param array parse_url Array containing the parsed URL (i.e. result of http://ca1.php.net/manual/en/function.parse-url.php) - * @return string - **/ - public static function http_build_url(array $parse_url) - { - // Skip if the URL is relative - if (!empty($parse_url["scheme"]) && !empty($parse_url["host"])) { - // scheme - e.g. http - $url = isset($parse_url["scheme"]) ? $parse_url["scheme"] : "http"; - $url .= "://"; - // user - if (isset($parse_url["user"])) { - $url .= $parse_url["user"]; - // pass - $url .= isset($parse_url["pass"]) ? ":{$parse_url["pass"]}" : ""; - $url .= "@"; - } - // host - $url .= isset($parse_url["host"]) ? $parse_url["host"] : ""; - // port - $url .= isset($parse_url["port"]) ? ":{$parse_url["port"]}" : ""; - } else { - $url = ""; - } - - // path - $url .= isset($parse_url["path"]) ? $parse_url["path"] : ""; - // query - after the question mark ? - $url .= isset($parse_url["query"]) ? "?{$parse_url["query"]}" : ""; - // fragment - after the hashmark # - $url .= isset($parse_url["fragment"]) ? "#{$parse_url["fragment"]}" : ""; - return $url; - } - - /** - * @param $val - * @return int|string - */ - public static function return_bytes($val) - { - $val = trim($val); - $last = strtolower($val[strlen($val) - 1]); - switch ($last) { - // The 'G' modifier is available since PHP 5.1.0 - case 'g': - $val *= 1024; - break; - case 'm': - $val *= 1024; - break; - case 'k': - $val *= 1024; - break; - } - - return $val; - } - - /** - * @param $string - * @param bool $ucfirst - * @return mixed|string - */ - public static function camelize($string, $ucfirst = false) - { - $string = str_replace(["_", "-"], " ", $string); - $string = ucwords($string); - $string = str_replace(" ", "", $string); - return $ucfirst ? $string : lcfirst($string); - } - - /** - * Returns associative array or string of data stored in $path in the $data array - * - * @param string $path path/to/interesting/data - * @param array|object $data The object containing data - * @param string $separator - * @param bool $ignoreEmpty - * @return mixed - * @throws NoDataFoundException - */ - public static function getDataFromPath($path, $data, $separator = "/", $ignoreEmpty = true) - { - if (!empty($path) && $path != $separator) { - // TODO possibly add functions in the $path? Such as path/to/join(data) would do a join on that data..likely belongs to EX/(sub)Parser/TR - $str = explode($separator, $path); - // Step down into the $data object, iterate until the desired path is reached (if not empty) - foreach ($str as $key) { - if (is_object($data) && property_exists($data, $key)) { - $data = $data->{$key}; - } elseif (is_array($data) && isset($data[$key])) { - $data = $data[$key]; - } else { - if ($ignoreEmpty == true) { // return if empty and ignore == true - $data = null; - break; - } else { - throw new NoDataFoundException("Error parsing data. {$path} not found."); - } - } - } - } - - return $data; - } - - /** - * Check if a string is a valid date(time) - * - * @link http://www.pontikis.net/tip/?id=21 - * - * @param string $dateStr - * @param string $dateFormat - * @param string $timezone (If timezone is invalid, php will throw an exception) - * @return bool - */ - public static function isValidDateTimeString($dateStr, $dateFormat, $timezone = null) - { - if ($timezone) { - $date = \DateTime::createFromFormat( - $dateFormat, - $dateStr, - new \DateTimeZone($timezone) - ); - } else { - $date = \DateTime::createFromFormat($dateFormat, $dateStr); - } - - return $date && \DateTime::getLastErrors()["warning_count"] == 0 && \DateTime::getLastErrors()["error_count"] == 0; - } - - /** - * Create a safe validated string to evaluate. - * md5(attr[Some_attribute] . "string") - * date("Y-m-d", strtotime(attr[whateverDate])) - * Nested arrays shall be accessed as attr[nested.value] - * @todo TEST harder! - * - * @param string $definition of the query field - * @param array $attributes The current ex's config - * @param array $allowedFns List of allowed function names - * @return string An eval "function" - * @deprecated - */ - public static function buildEvalString( - $definition, - array $attributes = [], - array $allowedFns = [ - "md5", "sha1", "time", "date", "strtotime", "base64_encode" - ] - ) { - // Cleanup unwanted methods - $definition = preg_replace_callback("/([\w]*)[\s]*\(/i", function ($matches) use ($allowedFns, $definition) { - if (!in_array($matches[1], $allowedFns)) { - $e = new EvalStringException("Function '{$matches[1]}' is not allowed!"); - $e->setData(['string' => $definition, 'allowed' => $allowedFns]); - throw $e; - } - - return $matches[1] . "("; - }, $definition); - - $attributes = self::flattenArray($attributes); - - $definition = preg_replace_callback("/attr\[([\w\.]*)]/", function ($matches) use ($attributes) { - if (!isset($attributes[$matches[1]])) { - throw new EvalStringException("Attribute {$matches[1]} not found in the configuration table!"); - } - return "'{$attributes[$matches[1]]}'"; - }, $definition); - - return "return " . $definition . ";"; - } - - /** - * Take a multidimensional array and return a singledimensional one - * Array keys are concatenated by "." - * @param array $array - * @param string $prefix Prefix the array key - * @param string $glue - * @return array - */ - public static function flattenArray(array $array, $prefix = "", $glue = '.') - { - $result = []; - foreach ($array as $key => $value) { - if (is_array($value)) { - $result = array_merge($result, self::flattenArray($value, $prefix . $key . $glue)); - } else { - $result[$prefix . $key] = $value; - } - } - return $result; - } - - /** - * Recursively convert an associative array to object - * - * If the $array is not associative, an array is returned - * @param array $array - * @return \stdClass|array - */ - public static function arrayToObject(array $array) - { - // This isn't the most efficient way! - return json_decode(json_encode($array)); - } - - /** - * Recursively scans $object for non-empty objects - * Returns true if the object contains no scalar nor array - * @param \stdClass $object - * @return bool - */ - public static function isEmptyObject(\stdClass $object) - { - $vars = get_object_vars($object); - if ($vars == []) { - return true; - } else { - foreach ($vars as $var) { - if (!is_object($var)) { - return false; - } else { - return self::isEmptyObject((object) $var); - } - } - } - } -} diff --git a/src/Keboola/Utils/arrayToObject.php b/src/Keboola/Utils/arrayToObject.php new file mode 100644 index 0000000..f5158d9 --- /dev/null +++ b/src/Keboola/Utils/arrayToObject.php @@ -0,0 +1,16 @@ + $v) { + if (empty($k)) { + unset($query[$k]); + } + } + + # Parse the url to get a query string + $parsed = parse_url($url); + + # If a query string is set, parse it into an associative array (..&key=value => array("key" => "value")) + if (isset($parsed["query"]) && strlen($parsed["query"]) > 0) { + $newQuery = array(); + $pairs = explode("&", $parsed["query"]); + foreach ($pairs as $pair) { + list($key, $val) = explode("=", $pair, 2); + $newQuery[$key] = urldecode($val); + } + # Add/Replace parameters from $query + $newQuery = array_replace($newQuery, $query); + } else { + $newQuery = $query; + } + $parsed["query"] = http_build_query($newQuery); + + # Rebuild the query back + $url = httpBuildUrl($parsed); + } + + return $url; +} diff --git a/src/Keboola/Utils/camelize.php b/src/Keboola/Utils/camelize.php new file mode 100644 index 0000000..f53ed35 --- /dev/null +++ b/src/Keboola/Utils/camelize.php @@ -0,0 +1,16 @@ + $value) { + if (is_array($value)) { + $result = array_merge($result, flattenArray($value, $prefix . $key . $glue)); + } else { + $result[$prefix . $key] = $value; + } + } + return $result; +} diff --git a/src/Keboola/Utils/formatDateTime.php b/src/Keboola/Utils/formatDateTime.php new file mode 100644 index 0000000..c5d467d --- /dev/null +++ b/src/Keboola/Utils/formatDateTime.php @@ -0,0 +1,16 @@ +format($format); +} diff --git a/src/Keboola/Utils/getDataFromPath.php b/src/Keboola/Utils/getDataFromPath.php new file mode 100644 index 0000000..358aa02 --- /dev/null +++ b/src/Keboola/Utils/getDataFromPath.php @@ -0,0 +1,38 @@ +{$key}; + } elseif (is_array($data) && isset($data[$key])) { + $data = $data[$key]; + } else { + if ($ignoreEmpty == true) { // return if empty and ignore == true + $data = null; + break; + } else { + throw new Exception\NoDataFoundException("Error parsing data. {$path} not found."); + } + } + } + } + + return $data; +} diff --git a/src/Keboola/Utils/httpBuildUrl.php b/src/Keboola/Utils/httpBuildUrl.php new file mode 100644 index 0000000..ba05ea2 --- /dev/null +++ b/src/Keboola/Utils/httpBuildUrl.php @@ -0,0 +1,42 @@ +lint($json); + + $errData['errDetail'] = $errLint instanceof \Seld\JsonLint\ParsingException + ? $errLint->getMessage() + : null; + } + + if (!empty($errData)) { + $e->setData($errData); + } + + throw $e; +} diff --git a/src/Keboola/Utils/objectToArray.php b/src/Keboola/Utils/objectToArray.php new file mode 100644 index 0000000..70bed36 --- /dev/null +++ b/src/Keboola/Utils/objectToArray.php @@ -0,0 +1,20 @@ + $value) { + if (is_object($value) || is_array($value)) { + $data[$key] = objectToArray($value); + } + } + return $data; +} diff --git a/src/Keboola/Utils/replaceDates.php b/src/Keboola/Utils/replaceDates.php new file mode 100644 index 0000000..44a3fb3 --- /dev/null +++ b/src/Keboola/Utils/replaceDates.php @@ -0,0 +1,21 @@ + $tag, 'format' => $format, 'timezone' => $timezone]); + return $array; +} diff --git a/src/Keboola/Utils/returnBytes.php b/src/Keboola/Utils/returnBytes.php new file mode 100644 index 0000000..dc7a716 --- /dev/null +++ b/src/Keboola/Utils/returnBytes.php @@ -0,0 +1,27 @@ + 'string', + 'arr' => ['a','b','c'], + 'obj' => [ + 'd' => 'dee', + 'e' => 'eh?' + ], + 'arrOfObj' => [ + ['f' => 'g'], + ['h' => 'i'] + ] + ]; + + $object = (object) [ + 'str' => 'string', + 'arr' => ['a','b','c'], + 'obj' => (object) [ + 'd' => 'dee', + 'e' => 'eh?' + ], + 'arrOfObj' => [ + (object) ['f' => 'g'], + (object) ['h' => 'i'] + ] + ]; + + $this->assertEquals($object, arrayToObject($array)); + } +} diff --git a/tests/Keboola/Utils/BuildUrlTest.php b/tests/Keboola/Utils/BuildUrlTest.php new file mode 100755 index 0000000..8aa1306 --- /dev/null +++ b/tests/Keboola/Utils/BuildUrlTest.php @@ -0,0 +1,12 @@ +assertEquals("endpoint?key=value&another=weird%3D%3Dthing&third=val", buildUrl($url, ['third' => 'val'])); + } +} diff --git a/tests/Keboola/Utils/CamelizeTest.php b/tests/Keboola/Utils/CamelizeTest.php new file mode 100755 index 0000000..e98b098 --- /dev/null +++ b/tests/Keboola/Utils/CamelizeTest.php @@ -0,0 +1,16 @@ +assertEquals("oneTwoThreeFour", camelize("one_two-three four")); + } + + public function testCamelizeLowerFirst() + { + $this->assertEquals("OneTwoThreeFour", camelize("one_two-three four", true)); + } +} diff --git a/tests/Keboola/Utils/FlattenArrayTest.php b/tests/Keboola/Utils/FlattenArrayTest.php new file mode 100755 index 0000000..b5f08e8 --- /dev/null +++ b/tests/Keboola/Utils/FlattenArrayTest.php @@ -0,0 +1,27 @@ + 'b', + 'c' => [ + 'd' => 'e', + 'f' => [ + 'g' => 'h' + ] + ] + ]; + + $single = [ + 'a' => 'b', + 'c.d' => 'e', + 'c.f.g' => 'h' + ]; + + $this->assertEquals($single, flattenArray($multi)); + } +} diff --git a/tests/Keboola/Utils/FormatDateTimeTest.php b/tests/Keboola/Utils/FormatDateTimeTest.php new file mode 100755 index 0000000..78f5c29 --- /dev/null +++ b/tests/Keboola/Utils/FormatDateTimeTest.php @@ -0,0 +1,13 @@ +assertEquals(formatDateTime("15.2.2014 16:00", "Y-m-d H:i"), "2014-02-15 16:00"); + $this->assertEquals(formatDateTime("now"), date(DATE_W3C)); + } +} diff --git a/tests/Keboola/Utils/GetDataFromPathTest.php b/tests/Keboola/Utils/GetDataFromPathTest.php new file mode 100755 index 0000000..16f4bf8 --- /dev/null +++ b/tests/Keboola/Utils/GetDataFromPathTest.php @@ -0,0 +1,43 @@ + array( + "a" => array( + "t" => array( + "h" => "Hello world!" + ) + ) + ) + ); + $slash = getDataFromPath("p/a/t/h", $data); + $this->assertEquals($slash, $data["p"]["a"]["t"]["h"]); + $dot = getDataFromPath("p.a.t.h", $data, "."); + $this->assertEquals($dot, $data["p"]["a"]["t"]["h"]); + $null = getDataFromPath("p/a/t/g", $data); + $this->assertEquals($null, ""); + } + + /** + * @expectedException \Keboola\Utils\Exception\NoDataFoundException + */ + public function testGetDataFromPathException() + { + $data = array( + "p" => array( + "a" => array( + "t" => array( + "h" => "Hello world!" + ) + ) + ) + ); + getDataFromPath("a/b/c", $data, "/", false); + } + +} diff --git a/tests/Keboola/Utils/HttpBuildUrlTest.php b/tests/Keboola/Utils/HttpBuildUrlTest.php new file mode 100755 index 0000000..557752a --- /dev/null +++ b/tests/Keboola/Utils/HttpBuildUrlTest.php @@ -0,0 +1,21 @@ + "https", + "user" => "user", + "pass" => "pass", + "host" => "test.com", + "port" => 8080, + "path" => "path", + "query" => "var1=val1&var2=val2", + "fragment" => "fragment" + ]; + $this->assertEquals("https://user:pass@test.com:8080path?var1=val1&var2=val2#fragment", httpBuildUrl($parts)); + } +} diff --git a/tests/Keboola/Utils/IsEmptyObjectTest.php b/tests/Keboola/Utils/IsEmptyObjectTest.php new file mode 100755 index 0000000..14422ef --- /dev/null +++ b/tests/Keboola/Utils/IsEmptyObjectTest.php @@ -0,0 +1,14 @@ +assertTrue(isEmptyObject(new \stdClass)); + $this->assertTrue(isEmptyObject((object) ['item' => new \stdClass])); + $this->assertFalse(isEmptyObject((object) ['item' => 'value'])); + } +} diff --git a/tests/Keboola/Utils/IsValidDateTimeStringTest.php b/tests/Keboola/Utils/IsValidDateTimeStringTest.php new file mode 100755 index 0000000..125783e --- /dev/null +++ b/tests/Keboola/Utils/IsValidDateTimeStringTest.php @@ -0,0 +1,20 @@ +assertEquals(isValidDateTimeString("Fri, 31 Dec 1999 23:59:59 GMT", DATE_RFC1123), true); + $this->assertEquals(isValidDateTimeString("Fri, 31 Dec 1999 23:59:59 +0000", DATE_RFC1123), true); + $this->assertEquals(isValidDateTimeString("2005-08-15T15:52:01+00:00", DATE_W3C), true); + } + + + public function testIsInvalidDateTimeString() + { + $this->assertEquals(isValidDateTimeString("abcd", DATE_RFC1123), false); + } +} diff --git a/tests/Keboola/Utils/JsonDecodeTest.php b/tests/Keboola/Utils/JsonDecodeTest.php new file mode 100755 index 0000000..a3e849b --- /dev/null +++ b/tests/Keboola/Utils/JsonDecodeTest.php @@ -0,0 +1,26 @@ +getData()['errDetail']); + $err = $e; + } + + self::assertInstanceOf('Keboola\Utils\Exception\JsonDecodeException', $err); + } + +} diff --git a/tests/Keboola/Utils/ObjectToArrayTest.php b/tests/Keboola/Utils/ObjectToArrayTest.php new file mode 100755 index 0000000..13f71b0 --- /dev/null +++ b/tests/Keboola/Utils/ObjectToArrayTest.php @@ -0,0 +1,37 @@ + 'string', + 'arr' => ['a','b','c'], + 'obj' => [ + 'd' => 'dee', + 'e' => 'eh?' + ], + 'arrOfObj' => [ + ['f' => 'g'], + ['h' => 'i'] + ] + ]; + + $object = (object) [ + 'str' => 'string', + 'arr' => ['a','b','c'], + 'obj' => (object) [ + 'd' => 'dee', + 'e' => 'eh?' + ], + 'arrOfObj' => [ + (object) ['f' => 'g'], + (object) ['h' => 'i'] + ] + ]; + + $this->assertEquals($array, objectToArray($object)); + } +} diff --git a/tests/Keboola/Utils/ReplaceDatesInArrayTest.php b/tests/Keboola/Utils/ReplaceDatesInArrayTest.php new file mode 100755 index 0000000..0bbd347 --- /dev/null +++ b/tests/Keboola/Utils/ReplaceDatesInArrayTest.php @@ -0,0 +1,36 @@ + [ + 'key' => 'something deeper from ~~-6 days~~' + ], + 'another' => [ + 'oh hi' => [ + 'deep as adele! ~~20071231~~' + ] + ] + ]; + + $parsed = [ + 'some ' . formatDateTime('yesterday') . ' thing', + 'arr' => [ + 'key' => 'something deeper from ' . formatDateTime('-6 days'), + ], + 'another' => [ + 'oh hi' => [ + 0 => 'deep as adele! 2007-12-31T00:00:00+00:00', + ], + ], + ]; + + $this->assertEquals(replaceDatesInArray($array, '~~'), $parsed); + } +} diff --git a/tests/Keboola/Utils/ReplaceDatesTest.php b/tests/Keboola/Utils/ReplaceDatesTest.php new file mode 100755 index 0000000..c209198 --- /dev/null +++ b/tests/Keboola/Utils/ReplaceDatesTest.php @@ -0,0 +1,13 @@ +assertEquals(replaceDates("@@now@@", "@@"), date(DATE_W3C)); + $this->assertEquals(replaceDates("%%now%%"), date(DATE_W3C)); + } +} diff --git a/tests/Keboola/Utils/ReturnBytesTest.php b/tests/Keboola/Utils/ReturnBytesTest.php new file mode 100755 index 0000000..746db28 --- /dev/null +++ b/tests/Keboola/Utils/ReturnBytesTest.php @@ -0,0 +1,23 @@ +assertEquals(1024, returnBytes("1K")); + } + + public function testMega() + { + $this->assertEquals(1024*1024, returnBytes("1M")); + } + + public function testGiga() + { + $this->assertEquals(1024*1024*1024, returnBytes("1G")); + } + +} diff --git a/tests/Keboola/Utils/SanitizeUtf8Test.php b/tests/Keboola/Utils/SanitizeUtf8Test.php new file mode 100755 index 0000000..9984393 --- /dev/null +++ b/tests/Keboola/Utils/SanitizeUtf8Test.php @@ -0,0 +1,13 @@ +assertEquals("SQLSTATE[XX000]: ? abcd", $sanitized); + } +} diff --git a/tests/Keboola/Utils/UtilsTest.php b/tests/Keboola/Utils/UtilsTest.php deleted file mode 100755 index 461f386..0000000 --- a/tests/Keboola/Utils/UtilsTest.php +++ /dev/null @@ -1,213 +0,0 @@ -assertEquals(Utils::formatDateTime("15.2.2014 16:00", "Y-m-d H:i"), "2014-02-15 16:00"); - $this->assertEquals(Utils::formatDateTime("now"), date(DATE_W3C)); - } - - public function testReplaceDatesInArray() - { - $array = [ - 'some ~~yesterday~~ thing', - 'arr' => [ - 'key' => 'something deeper from ~~-6 days~~' - ], - 'another' => [ - 'oh hi' => [ - 'deep as adele! ~~20071231~~' - ] - ] - ]; - - $parsed = [ - 'some ' . Utils::formatDateTime('yesterday') . ' thing', - 'arr' => [ - 'key' => 'something deeper from ' . Utils::formatDateTime('-6 days'), - ], - 'another' => [ - 'oh hi' => [ - 0 => 'deep as adele! 2007-12-31T00:00:00+00:00', - ], - ], - ]; - - $this->assertEquals(Utils::replaceDatesInArray($array, '~~'), $parsed); - } - - public function testReplaceDates() - { - $this->assertEquals(Utils::replaceDates("@@now@@", "@@"), date(DATE_W3C)); - $this->assertEquals(Utils::replaceDates("%%now%%"), date(DATE_W3C)); - } - - public function testGetDataFromPath() - { - $data = array( - "p" => array( - "a" => array( - "t" => array( - "h" => "Hello world!" - ) - ) - ) - ); - $slash = Utils::getDataFromPath("p/a/t/h", $data); - $this->assertEquals($slash, $data["p"]["a"]["t"]["h"]); - $dot = Utils::getDataFromPath("p.a.t.h", $data, "."); - $this->assertEquals($dot, $data["p"]["a"]["t"]["h"]); - $null = Utils::getDataFromPath("p/a/t/g", $data); - $this->assertEquals($null, ""); - } - - public function testIsValidDateTimeString() - { - $this->assertEquals(Utils::isValidDateTimeString("Fri, 31 Dec 1999 23:59:59 GMT", DATE_RFC1123), true); - $this->assertEquals(Utils::isValidDateTimeString("Fri, 31 Dec 1999 23:59:59 +0000", DATE_RFC1123), true); - $this->assertEquals(Utils::isValidDateTimeString("2005-08-15T15:52:01+00:00", DATE_W3C), true); - } - - public function testBuildEvalString() - { - $this->assertEquals(Utils::buildEvalString('md5(attr[hello])', ['hello' => 'world']), 'return md5(\'world\');'); - $this->assertEquals(eval(Utils::buildEvalString('md5(attr[hello] . "Me!")', ['hello' => 'world'])), md5("worldMe!")); - } - - /** - * @expectedException \Keboola\Utils\Exception\EvalStringException - * @expectedExceptionMessage Function 'die' is not allowed! - */ - public function testBuildEvalStringIllegalFunction() - { - Utils::buildEvalString('die("mf")'); - } - - public function testBuildEvalStringIllegalFunctionInAttr() - { - $something = "very secret server data!"; - $this->assertEquals(eval(Utils::buildEvalString('attr[test]', ['test' => 'var_dump($something)'])), 'var_dump($something)'); - } - - public function testFlattenArray() - { - $multi = [ - 'a' => 'b', - 'c' => [ - 'd' => 'e', - 'f' => [ - 'g' => 'h' - ] - ] - ]; - - $single = [ - 'a' => 'b', - 'c.d' => 'e', - 'c.f.g' => 'h' - ]; - - $this->assertEquals($single, Utils::flattenArray($multi)); - } - - public function testBuildUrl() - { - $url = "endpoint?key=value&another=weird==thing"; - $this->assertEquals("endpoint?key=value&another=weird%3D%3Dthing&third=val", Utils::buildUrl($url, ['third' => 'val'])); - } - - public function testArrayToObject() - { - $array = [ - 'str' => 'string', - 'arr' => ['a','b','c'], - 'obj' => [ - 'd' => 'dee', - 'e' => 'eh?' - ], - 'arrOfObj' => [ - ['f' => 'g'], - ['h' => 'i'] - ] - ]; - - $object = (object) [ - 'str' => 'string', - 'arr' => ['a','b','c'], - 'obj' => (object) [ - 'd' => 'dee', - 'e' => 'eh?' - ], - 'arrOfObj' => [ - (object) ['f' => 'g'], - (object) ['h' => 'i'] - ] - ]; - - $this->assertEquals($object, Utils::arrayToObject($array)); - } - - public function testObjectToArray() - { - $array = [ - 'str' => 'string', - 'arr' => ['a','b','c'], - 'obj' => [ - 'd' => 'dee', - 'e' => 'eh?' - ], - 'arrOfObj' => [ - ['f' => 'g'], - ['h' => 'i'] - ] - ]; - - $object = (object) [ - 'str' => 'string', - 'arr' => ['a','b','c'], - 'obj' => (object) [ - 'd' => 'dee', - 'e' => 'eh?' - ], - 'arrOfObj' => [ - (object) ['f' => 'g'], - (object) ['h' => 'i'] - ] - ]; - - $this->assertEquals($array, Utils::objectToArray($object)); - } - - public function testIsEmptyObject() - { - $this->assertTrue(Utils::isEmptyObject(new \stdClass)); - $this->assertTrue(Utils::isEmptyObject((object) ['item' => new \stdClass])); - $this->assertFalse(Utils::isEmptyObject((object) ['item' => 'value'])); - } - - public function testJsonDecodeLint() - { - $expected = <<getData()['errDetail']); - $err = $e; - } - - self::assertInstanceOf('Keboola\Utils\Exception\JsonDecodeException', $err); - } -}