/** * Call this function with the JSON in parameter. * * @param String $JSON The JSON string to parse. * @return array The array of the JSON element or null if there is an error. */ public static function parseJSON($JSON) { if (!InputValidator::isJSON($JSON)) { return array(); } $result = json_decode($JSON, true); if (!InputValidator::isArray($result)) { Logger::warning("There is an error with parsing the follwing JSON: <strong>" . json_last_error() . ": " . json_last_error_msg() . "</strong><br/>\n" . "<pre>" . $JSON . "</pre>"); return array(); } return $result; }
/** * Call this function to create a JSON string from a array. * * @author David Pauli <*****@*****.**> * @since 0.0.0 * @param mixed[] $array The array to make a JSON. * @return String The JSON string. */ public static function createJSON($array) { if (!InputValidator::isArray($array)) { return null; } $result = json_encode($array); if (!InputValidator::isJSON($result)) { Logger::warning("There is an error with creating a JSON with the following array: <strong>" . json_last_error() . ": " . json_last_error_msg() . "</strong><br/>\n" . "<pre>" . $array . "</pre>"); return null; } return $result; }
/** * Call this function with the JSON in parameter. * * @author David Pauli <*****@*****.**> * @param String $JSON The JSON string to parse. * @return mixed[] The array of the JSON element or null if there is an error. * @since 0.0.0 * @since 0.1.2 Better the warnings. * @since 0.1.2 Add error reporting. */ public static function parseJSON($JSON) { self::errorReset(); if (!InputValidator::isJSON($JSON)) { Logger::warning("ep6\\JSONHandler\nJSON string (" . $JSON . ") is not valid."); self::errorSet("JSONH-1"); return array(); } $result = json_decode($JSON, true); if (!InputValidator::isArray($result)) { Logger::warning("ep6\\JSONHandler\nThere is an error with parsing the follwing JSON (" . $JSON . "): " . json_last_error() . ": " . json_last_error_msg()); self::errorSet("JSONH-2"); return array(); } return $result; }
/** * @group utility */ function testIsJSON() { $this->assertFalse(InputValidator::isJSON("Some String")); $this->assertTrue(InputValidator::isJSON(3)); $this->assertFalse(InputValidator::isJSON(null)); $this->assertTrue(InputValidator::isJSON(1.2)); $this->assertTrue(InputValidator::isJSON("{}")); }