/** * Make API request. * * @access public * @param string $path * @param array $options * @param bool $return_status (default: false) * @param string $method (default: 'GET') * @return void */ public function make_request($path, $options = array(), $method = 'GET', $return_key = null) { /* Build request URL. */ $request_url = 'https://' . $this->subdomain . '.campfirenow.com/' . $path . '.json'; /* Setup request arguments. */ $args = array('headers' => array('Accept' => 'application/json', 'Authorization' => 'Basic ' . base64_encode($this->api_token . ':x'), 'Content-Type' => 'application/json'), 'method' => $method, 'sslverify' => $this->verify_ssl); /* Add request options to body of POST and PUT requests. */ if ($method == 'POST' || $method == 'PUT') { $args['body'] = json_encode($options); } /* Execute request. */ $result = wp_remote_request($request_url, $args); /* If WP_Error, throw exception */ if (is_wp_error($result)) { throw new Exception('Request failed. ' . $result->get_error_messages()); } /* Decode JSON. */ $decoded_result = json_decode($result['body'], true); /* If invalid JSON, return original result body. */ if (json_last_error() !== JSON_ERROR_NONE) { return trim($result['body']); } /* If return key is set and exists, return array item. */ if ($return_key && array_key_exists($return_key, $decoded_result)) { return $decoded_result[$return_key]; } return $decoded_result; }
/** * Converts a JSON string to a CFSimpleXML object. * * @param string|array $json (Required) Pass either a valid JSON-formatted string, or an associative array. * @param SimpleXMLElement $xml (Optional) An XML object to add nodes to. Must be an object that is an <code>instanceof</code> a <code>SimpleXMLElement</code> object. If an object is not passed, a new one will be generated using the classname defined for <code>$parser</code>. * @param string $parser (Optional) The name of the class to use to parse the XML. This class should extend <code>SimpleXMLElement</code>. Has a default value of <code>CFSimpleXML</code>. * @return CFSimpleXML An XML representation of the data. */ public static function to_xml($json, SimpleXMLElement $xml = null, $parser = 'CFSimpleXML') { // If there isn't an XML object, create one if (!$xml) { $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?><rootElement/>', $parser); } // If we haven't parsed the JSON, do it if (!is_array($json)) { $json = json_decode($json, true); if (function_exists('json_last_error')) { // Did we encounter an error? switch (json_last_error()) { case JSON_ERROR_DEPTH: throw new JSON_Exception('Maximum stack depth exceeded.'); case JSON_ERROR_CTRL_CHAR: throw new JSON_Exception('Unexpected control character found.'); case JSON_ERROR_SYNTAX: throw new JSON_Exception('Syntax error; Malformed JSON.'); case JSON_ERROR_STATE_MISMATCH: throw new JSON_Exception('Invalid or malformed JSON.'); } } else { throw new JSON_Exception('Unknown JSON error. Be sure to validate your JSON and read the notes on http://php.net/json_decode.'); } } // Hand off for the recursive work self::process_json($json, $xml, $parser); return $xml; }
/** * Decodes the given $encodedValue string which is * encoded in the JSON format * * Uses ext/json's json_decode if available. * * @param string $encodedValue Encoded in JSON format * @param int $objectDecodeType Optional; flag indicating how to decode * objects. See {@link Zend_Json_Decoder::decode()} for details. * @return mixed */ public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY) { $encodedValue = (string) $encodedValue; if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) { $decode = json_decode($encodedValue, $objectDecodeType); // php < 5.3 if (!function_exists('json_last_error')) { if ($decode === $encodedValue) { require_once 'Zend/Json/Exception.php'; throw new Zend_Json_Exception('Decoding failed'); } // php >= 5.3 } elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) { require_once 'Zend/Json/Exception.php'; switch ($jsonLastErr) { case JSON_ERROR_DEPTH: throw new Zend_Json_Exception('Decoding failed: Maximum stack depth exceeded'); case JSON_ERROR_CTRL_CHAR: throw new Zend_Json_Exception('Decoding failed: Unexpected control character found'); case JSON_ERROR_SYNTAX: throw new Zend_Json_Exception('Decoding failed: Syntax error'); default: throw new Zend_Json_Exception('Decoding failed'); } } return $decode; } require_once 'Zend/Json/Decoder.php'; return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType); }
/** * Valida el formato de los datos de entrada. * Verifica que el ContentType sea application/json y que el JSON de entrada * esté bien formado. */ protected function validateInput() { $this->before(function ($request) { if (strtolower($request->contentType) !== "application/json") { throw new Exception("El ContentType debe ser application/json", Response::BADREQUEST); } try { $request->data = json_decode($request->data, true); switch (json_last_error()) { case JSON_ERROR_NONE: break; case JSON_ERROR_SYNTAX: throw new Exception("JSON mal formado", Response::BADREQUEST); case JSON_ERROR_UTF8: throw new Exception("La codificación de caracteres debe ser UTF-8", Response::BADREQUEST); default: throw new Exception("Error en el objeto de entrada.", Response::BADREQUEST); } if (empty($request->data)) { throw new Exception("No hay datos para procesar", Response::BADREQUEST); } } catch (Exception $e) { $response = json_encode($this->getErrorArray($e->getMessage(), $e->getCode())); throw new Exception($response, $e->getCode()); } }); }
/** * Returns an exception describing the last JSON error * * @return Exception */ protected function _createExceptionFromLastError() { if (!function_exists('json_last_error_msg')) { switch (json_last_error()) { case JSON_ERROR_DEPTH: $errorMessage = 'Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $errorMessage = 'Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $errorMessage = 'Unexpected control character found'; break; case JSON_ERROR_SYNTAX: $errorMessage = 'Syntax error, malformed JSON'; break; case JSON_ERROR_UTF8: $errorMessage = 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: $errorMessage = 'Unknown JSON error'; } } else { $errorMessage = json_last_error_msg(); } return new Exception($errorMessage, json_last_error()); }
/** * Return the response payload from the current response. * * @return mixed */ protected function getResponsePayload() { if (!$this->responsePayload) { $json = json_decode($this->getResponse()->getBody(true)); if (json_last_error() !== JSON_ERROR_NONE) { $message = 'Failed to decode JSON body '; switch (json_last_error()) { case JSON_ERROR_DEPTH: $message .= '(Maximum stack depth exceeded).'; break; case JSON_ERROR_STATE_MISMATCH: $message .= '(Underflow or the modes mismatch).'; break; case JSON_ERROR_CTRL_CHAR: $message .= '(Unexpected control character found).'; break; case JSON_ERROR_SYNTAX: $message .= '(Syntax error, malformed JSON).'; break; case JSON_ERROR_UTF8: $message .= '(Malformed UTF-8 characters, possibly incorrectly encoded).'; break; default: $message .= '(Unknown error).'; break; } throw new \Exception($message); } $this->responsePayload = $json; } return $this->responsePayload; }
/** * Get all of the received requests as a RingPHP request structure. * * @return array * @throws \RuntimeException */ public static function received() { if (!self::$started) { return []; } $response = self::send('GET', '/guzzle-server/requests'); $body = Core::body($response); $result = json_decode($body, true); if ($result === false) { throw new \RuntimeException('Error decoding response: ' . json_last_error()); } foreach ($result as &$res) { if (isset($res['uri'])) { $res['resource'] = $res['uri']; } if (isset($res['query_string'])) { $res['resource'] .= '?' . $res['query_string']; } if (!isset($res['resource'])) { $res['resource'] = ''; } // Ensure that headers are all arrays if (isset($res['headers'])) { foreach ($res['headers'] as &$h) { $h = (array) $h; } unset($h); } } unset($res); return $result; }
public function decode($json) { $result = json_decode($json, true); $error = ''; switch (json_last_error()) { case JSON_ERROR_DEPTH: $error = ' - The maximum stack depth has been exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $error = ' - Invalid or malformed JSON'; break; case JSON_ERROR_CTRL_CHAR: $error = ' - Control character error, possibly incorrectly encoded'; break; case JSON_ERROR_SYNTAX: $error = ' - Syntax error'; break; case JSON_ERROR_UTF8: $error = ' - Malformed UTF-8 characters, possibly incorrectly encoded'; break; } if (!empty($error)) { throw new Exception('JSON Error: ' . $error); } return $result; }
/** * @param array $object * @param boolean $allowBinary * @return string * @throws InvalidArgumentException */ protected function encode($object, $allowBinary = true) { $json = @json_encode($object); if ($last = json_last_error()) { switch ($last) { case JSON_ERROR_NONE: break; case JSON_ERROR_DEPTH: throw new InvalidArgumentException('Maximum stack depth exceeded'); case JSON_ERROR_STATE_MISMATCH: throw new InvalidArgumentException('Underflow or the modes mismatch'); case JSON_ERROR_CTRL_CHAR: throw new InvalidArgumentException('Unexpected control character found'); case JSON_ERROR_SYNTAX: throw new InvalidArgumentException('Syntax error, malformed JSON'); case JSON_ERROR_UTF8: if (!$allowBinary) { throw new InvalidArgumentException('Invalid binary string in object to encode; JSON strings must be UTF-8'); } $object = $this->encodeBinary($object); $json = $this->encode($object, false); break; default: throw new InvalidArgumentException('Unknown error in JSON encode'); } } return $json; }
function request($http_method, array $data = array(), array $params = array(), array $option = array()) { static $key_colon_value = null; if (is_null($key_colon_value)) { $key_colon_value = function ($k, $v) { return is_int($k) ? $v : "{$k}: {$v}"; }; } $opt = array_merge(array('space_name' => $this->space, 'header' => array()), $option); $query = array_merge(array('apiKey' => $this->apiKey), $data); $segments = array(); foreach ($this->api as $api) { $segments[] = array_key_exists($api, $params) ? $params[$api] : $api; } $uri = implode('/', $segments); $http_method = strtoupper($http_method); switch ($http_method) { case 'POST': $content = http_build_query($query, '', '&'); $header = array_merge(array('Content-Type' => 'application/x-www-form-urlencoded', 'Content-Length' => strlen($content)), $opt['header']); $query = array('apiKey' => $this->apiKey); break; case 'GET': $header = array_merge(array(), $opt['header']); break; default: $header = array_merge(array(), $opt['header']); } if (!isset($url)) { $url = sprintf(self::URL_TEMPLATE, $opt['space_name'], $uri, http_build_query($query, '', '&')); } $context = array('http' => array('method' => $http_method, 'header' => implode("\r\n", array_map($key_colon_value, array_keys($header), array_values($header))), 'ignore_errors' => true)); if (isset($content)) { $context['http']['content'] = $content; } $response = file_get_contents($url, false, stream_context_create($context)); $type = $this->responseContexType($http_response_header); switch ($type) { case 'application/json': $res = $json = json_decode($response, true); $json_error = json_last_error(); break; case 'application/octet-stream': $res = $response; break; default: $res = $response; } if (isset($json) and isset($json['errors'])) { // error throw new BacklogException($json['errors'][0]['message'], $json['errors'][0]['code'], null, $json); } elseif ('application/json' == $type and JSON_ERROR_NONE !== $json_error and JSON_ERROR_SYNTAX !== $json_error) { // error throw new BacklogException('json error.', $json_error, null, $response); } elseif (empty($response)) { // error throw new BacklogException('Not Found Content', 404); } return $res; }
/** * @param Request $request * @param Application $app * * @return Response * * @throws \Exception */ public function installAction(Request $request, Application $app) { $installer = json_decode($request->getContent(), true); $app['logger']->info('Install Callback'); if (json_last_error()) { $app['logger']->error('Install JSON Error: ' . json_last_error_msg()); throw new \Exception('JSON Error'); } $oauthId = $this->getInstallValue($installer, 'oauthId'); $oauthSecret = $this->getInstallValue($installer, 'oauthSecret'); $groupId = $this->getInstallValue($installer, 'groupId', true); $roomId = $this->getInstallValue($installer, 'roomId', true); if ($oauthId === null || $oauthSecret === null || $groupId === null) { throw new \Exception('Invalid installation request'); } $app['logger']->debug(sprintf('Got oauthId "%s" and oauthSecret "%s"', $oauthId, $oauthSecret)); /* @var Registry $registry */ $registry = $app['hc.api_registry']; $registry->install($oauthId, $oauthSecret, $groupId, $roomId); /** @var \Venyii\HipChatCommander\Api\Client $client */ $client = $app['hc.api_client']($oauthId); try { // fetch auth token $authToken = $client->renewAuthToken($oauthId, $oauthSecret); $app['logger']->debug(sprintf('Got authToken "%s"', $authToken)); } catch (\Exception $e) { $registry->uninstall($oauthId); throw $e; } return new Response(null, 200); }
public function createRequest() { $uri = $_SERVER['REQUEST_URI']; $basePath = $this->configuration->getBasePath(); if ($basePath && strncmp($uri, $basePath, strlen($basePath)) !== 0) { throw new ApiException("Invalid endpoint"); } $uri = substr($uri, strlen($basePath) - 1); if ($this->configuration->getPublicKey() !== trim($_SERVER['HTTP_X_API_KEY'])) { throw new AuthorizationException("Invalid API key"); } $hasBody = $this->hasBody(); $input = $hasBody ? file_get_contents('php://input') : ''; $signature = hash_hmac('sha256', $uri . $input, $this->configuration->getPrivateKey()); if ($signature !== trim($_SERVER['HTTP_X_API_SIGNATURE'])) { throw new AuthorizationException("Invalid signature"); } if ($hasBody) { $parameters = json_decode($input, JSON_OBJECT_AS_ARRAY); if ($parameters === NULL && $input !== '' && strcasecmp(trim($input, " \t\n\r"), 'null') !== 0) { $error = json_last_error(); throw new ApiException('JSON parsing error: ' . $error); } } else { $parameters = filter_input_array(INPUT_GET, FILTER_UNSAFE_RAW); } $name = ($a = strpos($uri, '?')) !== FALSE ? substr($uri, 0, $a) : $uri; return new Request(ltrim($name, '/'), $_SERVER['REQUEST_METHOD'], $parameters); }
protected function parse_json($json_file) { if (is_file($json_file) and is_readable($json_file)) { $data = file_get_contents($json_file); } else { throw new \Exception("The {$json_file} file could not be found or could not be read."); } $data = json_decode($data, true); switch (json_last_error()) { case JSON_ERROR_DEPTH: $error = "The {$json_file} file exceeded maximum stack depth."; break; case JSON_ERROR_STATE_MISMATCH: $error = "The {$json_file} file hit an underflow or the mods mismatched."; break; case JSON_ERROR_CTRL_CHAR: $error = "The {$json_file} file has an unexpected control character."; break; case JSON_ERROR_SYNTAX: $error = "The {$json_file} file has a syntax error, it\\'s JSON is malformed."; break; case JSON_ERROR_UTF8: $error = "The {$json_file} file has malformed UTF-8 characters, it could be incorrectly encoded."; break; case JSON_ERROR_NONE: default: $error = ''; } if (!empty($error)) { throw new \Exception($error); } return $data; }
/** * Loads the request schema from a file. * * @param string $file The full path to the file containing the [WDVSS schema](https://github.com/alexweissman/wdvss). * @throws Exception The file does not exist or is not a valid JSON schema. */ public function __construct($file) { $this->_schema = json_decode(file_get_contents($file), true); if ($this->_schema === null) { throw new \Exception("Either the schema '{$file}' could not be found, or it does not contain a valid JSON document: " . json_last_error()); } }
/** * Reads json file. * * @throws \RuntimeException * * @return mixed */ public function read() { $json = @file_get_contents($this->path); if (false === $json) { throw new \RuntimeException('Could not read ' . $this->path); } $arr = json_decode($json, true); $error = null; switch (json_last_error()) { case JSON_ERROR_NONE: break; case JSON_ERROR_DEPTH: $error = 'Maximum stack depth exceeded.'; break; case JSON_ERROR_STATE_MISMATCH: $error = 'Underflow or the modes mismatch.'; break; case JSON_ERROR_CTRL_CHAR: $error = 'Unexpected control character found.'; break; case JSON_ERROR_SYNTAX: $error = 'Syntax error, malformed JSON.'; break; case JSON_ERROR_UTF8: $error = 'Malformed UTF-8 characters, possibly incorrectly encoded.'; break; default: $error = 'Unknown error'; break; } if ($error) { throw new \RuntimeException($error . ' Path: ' . $this->path); } return $arr; }
/** * Check JSON * * @throws JsonDBException */ protected function checkJson() { $error = ''; switch (json_last_error()) { case JSON_ERROR_NONE: break; case JSON_ERROR_DEPTH: $error = 'Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $error = 'Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $error = 'Unexpected control character found'; break; case JSON_ERROR_SYNTAX: $error = 'Syntax error, malformed JSON'; break; case JSON_ERROR_UTF8: $error = 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: $error = 'Unknown error'; break; } if ($error !== '') { throw new JsonDBException('Invalid JSON: ' . $error); } }
public function send($method, $args = array()) { $options = $this->getOptions(); // Compose the request. $request = array('method' => $method, 'params' => $args, 'id' => 0, 'jsonrpc' => $options['jsonrpc']); $request = json_encode($request); // Send the request. try { $this->transport->connect($this->getHost(), $this->getPort()); $this->transport->write('POST', $options['uri'], null, $request); } catch (\Transport\Exception $e) { throw new Exception('Request failed.', 'REQUEST_FAILED', $e); } // We have a response! Read the response. $response = json_decode($this->transport->read()); // Is it a valid json response? $lastJsonErrorCode = json_last_error(); if ($lastJsonErrorCode) { throw new Exception('Json decode has failed. Code: ' . $lastJsonErrorCode, 'RESPONSE_ERROR'); } if (isset($response->result)) { return $response->result; } else { throw new Exception('The response result is empty.', 'RESPONSE_ERROR'); } }
/** * Retrieve the current version available remotely. * * @param Updater $updater * @return string|bool */ public function getCurrentRemoteVersion(Updater $updater) { /** Switch remote request errors to HttpRequestExceptions */ set_error_handler(array($updater, 'throwHttpRequestException')); $packageUrl = $this->getApiUrl(); $package = json_decode(humbug_get_contents($packageUrl), true); restore_error_handler(); if (null === $package || json_last_error() !== JSON_ERROR_NONE) { throw new JsonParsingException('Error parsing JSON package data' . (function_exists('json_last_error_msg') ? ': ' . json_last_error_msg() : '')); } $versions = array_keys($package['package']['versions']); $versionParser = new VersionParser($versions); if ($this->getStability() === self::STABLE) { $this->remoteVersion = $versionParser->getMostRecentStable(); } elseif ($this->getStability() === self::UNSTABLE) { $this->remoteVersion = $versionParser->getMostRecentUnstable(); } else { $this->remoteVersion = $versionParser->getMostRecentAll(); } /** * Setup remote URL if there's an actual version to download */ if (!empty($this->remoteVersion)) { $this->remoteUrl = $this->getDownloadUrl($package); } return $this->remoteVersion; }
function retrieve($cacheKey) { $conn = new mysqli(self::$servername, self::$username, self::$password, self::$dbname); $sql = "SELECT value FROM cached_data WHERE cache_key = ? order by timestamp desc limit 1"; $stmt = $conn->prepare($sql); $stmt->bind_param('s', $cacheKey); $stmt->execute(); $result = $stmt->get_result(); $return = NULL; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $return = json_decode($row['value'], TRUE); $isValid = json_last_error() === JSON_ERROR_NONE; /// check data un valid json format if ($isValid == FALSE) { $return = FALSE; } // if($cacheKey == 'GetAllLotData-By-8-33-101-102-34-35-106') { // var_dump($row['value']); // } break; } } $stmt->close(); $conn->close(); return $return; }
public static function testJsonError() { // handle possible json errors and throw exceptions switch (json_last_error()) { case JSON_ERROR_NONE: break; case JSON_ERROR_DEPTH: throw new \Exception('The maximum stack depth has been exceeded'); case JSON_ERROR_STATE_MISMATCH: throw new \Exception('Invalid or malformed JSON'); case JSON_ERROR_CTRL_CHAR: throw new \Exception('Control character error, possibly incorrectly encoded'); case JSON_ERROR_SYNTAX: throw new \Exception('Syntax error, malformed JSON'); // PHP >= 5.3.3 // PHP >= 5.3.3 case JSON_ERROR_UTF8: throw new \Exception('Malformed UTF-8 characters, possibly incorrectly encoded'); // PHP >= 5.5.0 // PHP >= 5.5.0 case JSON_ERROR_RECURSION: throw new \Exception('One or more recursive references in the value to be encoded'); // PHP >= 5.5.0 // PHP >= 5.5.0 case JSON_ERROR_INF_OR_NAN: throw new \Exception('One or more NAN or INF values in the value to be encoded'); case JSON_ERROR_UNSUPPORTED_TYPE: throw new \Exception('A value of a type that cannot be encoded was given'); default: throw new \Exception('Unknown JSON error occured'); } return false; }
/** * Safely utf8 encode data * * @param $value * @return string */ public static function encode($value) { if (version_compare(PHP_VERSION, '5.4.0') >= 0) { $encoded = json_encode($value, JSON_PRETTY_PRINT); } else { $encoded = json_encode($value); } switch (json_last_error()) { case JSON_ERROR_NONE: return $encoded; case JSON_ERROR_DEPTH: return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception() // or trigger_error() or throw new Exception() case JSON_ERROR_STATE_MISMATCH: return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception() // or trigger_error() or throw new Exception() case JSON_ERROR_CTRL_CHAR: return 'Unexpected control character found'; case JSON_ERROR_SYNTAX: return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception() // or trigger_error() or throw new Exception() case JSON_ERROR_UTF8: $clean = SafeJson::utf8ize($value); return SafeJson::encode($clean); default: return 'Unknown error'; // or trigger_error() or throw new Exception() } }
public function validateHook() { if(json_last_error() == JSON_ERROR_NONE) { if( $payload['push']['changes'][0]['new']['type'] == 'branch') { $this->_branch_involved = $payload['push']['changes'][0]['new']['type']; //array_key_exists(key, search) if(!in_array($this->_branch_involved, $this->_allowed_branches)) { $this->log('Nothing to Deploy. Branched Info : '.$payload['push']['changes'][0]['new']['type']); //log branch info return false; } } else { $this->log('No Branch specific GIT push.', 'ERROR'); return false; } $this->log('Deployment Initiated.'); return true; } else { $this->log('Payload format error.', 'ERROR'); return false; } }
/** * Decode JSON response as array * * @throws ResponseInvalidException */ private function processJson() { // Decode JSON $this->array = json_decode($this->raw, true); // Check for errors switch (json_last_error()) { case JSON_ERROR_NONE: $error = null; break; case JSON_ERROR_DEPTH: $error = 'Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $error = 'Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $error = 'Unexpected control character found'; break; case JSON_ERROR_SYNTAX: $error = 'Syntax error, malformed JSON'; break; case JSON_ERROR_UTF8: $error = 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: $error = 'Unknown error'; break; } // Throw exception if error occured if (!is_null($error)) { throw new ResponseInvalidException(sprintf("Response (JSON) Invalid: %s", $error)); } }
function wp_all_import_is_json($string) { if (function_exists('json_last_error')) { json_decode($string); switch (json_last_error()) { case JSON_ERROR_NONE: return true; break; case JSON_ERROR_DEPTH: return new WP_Error('broke', __("Maximum stack depth exceeded", "pmxi_plugin")); break; case JSON_ERROR_STATE_MISMATCH: return new WP_Error('broke', __("Underflow or the modes mismatch", "pmxi_plugin")); break; case JSON_ERROR_CTRL_CHAR: return new WP_Error('broke', __("Unexpected control character found", "pmxi_plugin")); break; case JSON_ERROR_SYNTAX: return new WP_Error('broke', __("Syntax error, malformed JSON", "pmxi_plugin")); break; case JSON_ERROR_UTF8: return new WP_Error('broke', __("Malformed UTF-8 characters, possibly incorrectly encoded", "pmxi_plugin")); break; default: return new WP_Error('broke', __("Unknown json error", "pmxi_plugin")); break; } } return true; }
/** * Encodes PHP data to a JSON string * * {@inheritdoc} */ public function encode($data, $format, array $context = array()) { $context = $this->resolveContext($context); $encodedJson = json_encode($data, $context['json_encode_options']); $this->lastError = json_last_error(); return $encodedJson; }
/** * Decodes a JSON string. * @param string * @param int accepts Json::FORCE_ARRAY * @return mixed */ public static function decode($json, $options = 0) { $json = (string) $json; if (!preg_match('##u', $json)) { throw new JsonException('Invalid UTF-8 sequence', 5); // workaround for PHP < 5.3.3 & PECL JSON-C } $forceArray = (bool) ($options & self::FORCE_ARRAY); if (!$forceArray && preg_match('#(?<=[^\\\\]")\\\\u0000(?:[^"\\\\]|\\\\.)*+"\\s*+:#', $json)) { // workaround for json_decode fatal error when object key starts with \u0000 throw new JsonException(static::$messages[JSON_ERROR_CTRL_CHAR]); } $args = array($json, $forceArray, 512); if (PHP_VERSION_ID >= 50400 && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) { // not implemented in PECL JSON-C 1.3.2 for 64bit systems $args[] = JSON_BIGINT_AS_STRING; } $value = call_user_func_array('json_decode', $args); if ($value === NULL && $json !== '' && strcasecmp(trim($json, " \t\n\r"), 'null') !== 0) { // '' is not clearing json_last_error $error = json_last_error(); throw new JsonException(isset(static::$messages[$error]) ? static::$messages[$error] : 'Unknown error', $error); } return $value; }
public function input() { if ($this->input === NULL) { $in = file_get_contents("php://input"); if ($in != "" && $in != NULL) { $this->input = json_decode($in, true); if (json_last_error() != JSON_ERROR_NONE) { // we have to do a raw write here... http_response_code(400); if (config('app.debug') === true) { \Log::debug("Invalid JSON in this request: " . $in); } echo json_encode(["message" => "Error: Malformed JSON"]); exit; } if (isset($this->input['payload']) && !empty($this->input['payload'])) { $this->payload = $this->input['payload']; } if (isset($this->input['meta']) && !empty($this->input['meta'])) { $this->meta = $this->input['meta']; } } else { $this->input = ""; } } return $this->input; }
/** * @param mixed $params * @param bool $isArray * @return JsonRpcClient */ private function getProphetClient($params, $isArray) { $guzzle = $this->prophesize(ClientInterface::class); $self = $this; $guzzle->sendAsync(Argument::type(RequestInterface::class))->will(function ($args) use($self, $params, $isArray) { /** @var RequestInterface $request */ $request = $args[0]; $content = $request->getBody()->getContents(); $data = json_decode($content); if ($isArray) { $self::assertTrue(is_array($data)); $self::assertNotEmpty($data); $data = array_shift($data); } $self::assertEquals(JSON_ERROR_NONE, json_last_error()); $self::assertObjectHasAttribute('id', $data); $self::assertObjectHasAttribute('method', $data); $self::assertObjectHasAttribute('params', $data); $self::assertObjectHasAttribute('jsonrpc', $data); $self::assertEquals('test', $data->id); $self::assertEquals('2.0', $data->jsonrpc); $self::assertEquals('test', $data->method); $self::assertEquals($params, $data->params); return new Promise(function () { }, function () { }); }); return new JsonRpcClient($guzzle->reveal(), new Uri('http://localhost/')); }
private function sync() { if ($this->synchronized) { return; } /** @var ResponseInterface $clientResponse */ $clientResponse = $this->promise->wait(); if (200 !== $clientResponse->getStatusCode()) { throw new RemoteCallFailedException(); } $data = (string) $clientResponse->getBody(); // Null (empty response) is expected if only notifications were sent $rawResponses = []; if ('' !== $data) { $rawResponses = json_decode($data, false); if (json_last_error() !== JSON_ERROR_NONE) { throw ResponseParseException::notAJsonResponse(); } } if (!is_array($rawResponses) && $rawResponses instanceof \stdClass) { $rawResponses = [$rawResponses]; } $this->responses = []; foreach ($rawResponses as $rawResponse) { try { $response = new SyncResponse($rawResponse); } catch (ResponseParseException $exception) { //todo: logging??? (@scaytrase) continue; } $this->responses[$response->getId()] = $response; } $this->synchronized = true; }
protected function checkJsonDecodeErrors() { $res = json_last_error(); if ($res != JSON_ERROR_NONE) { switch ($res) { case JSON_ERROR_DEPTH: $error = 'Maximum stack depth exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $error = 'Underflow or the modes mismatch'; break; case JSON_ERROR_CTRL_CHAR: $error = 'Unexpected control character found'; break; case JSON_ERROR_SYNTAX: $error = 'Syntax error, malformed JSON'; break; case JSON_ERROR_UTF8: $error = 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; default: "Unrecognized error: {$res}"; } throw new Exception\WebAppJsonDecodeException($error); } }