public function process() { $result = \Zend\Json\Encoder::encode($this->_vars); $this->_response->setContent($result); $headers = $this->_response->getHeaders(); $headers->addHeaderLine('Content-Type', 'application/json'); $this->_response->setHeaders($headers); }
/** * Gibt das Device der übergebenen Deviceverknüpfung zurück * @param string $platform * @param array $credentials * @param boolean $throwException * @return \DragonJsonServerDevice\Entity\Device|null * @throws \DragonJsonServer\Exception */ public function getDeviceByPlatformAndCredentials($platform, array $credentials, $throwException = true) { $credentials = $this->getCredentials($platform, $credentials); $entityManager = $this->getEntityManager(); $device = $entityManager->getRepository('\\DragonJsonServerDevice\\Entity\\Device')->findOneBy(['platform' => $platform, 'credentials' => \Zend\Json\Encoder::encode($credentials)]); if (null === $device && $throwException) { throw new \DragonJsonServer\Exception('invalid credentials', ['platform' => $platform, 'credentials' => $credentials]); } return $device; }
public function find($collectionName, $query, array $fields = array()) { $this->_connect(); $request = $this->_buildRequest($collectionName, $query, $fields); $response = $this->_connection->restPost('/mapred', \Zend\Json\Encoder::encode($request)); if ($response->isError()) { return null; } return new DbDocument\Cursor\Riak($this->getCollection($collectionName), \Zend\Json\Decoder::decode($response->getBody())); }
public function testWaitForStateTimeOut() { $Facker = Factory::create(); $MockedModel = new Model(json_decode(ServiceTest::getMockData(), true)); $this->mockResponses([new Response(200, ['Content-Type' => 'application/json'], Encoder::encode($MockedModel->setState(Model::STATE_NOT_RUNNING)->getArrayCopy())), new Response(200, ['Content-Type' => 'application/json'], Encoder::encode($MockedModel->setState(Model::STATE_STARTING)->getArrayCopy()))]); $API = new API(); $Model = $API->get($Facker->uuid); $this->expectException(Exception::class); $this->expectExceptionMessageRegExp('/.*timed out.*/'); $API->waitForState($Model, Model::STATE_RUNNING, 0.1, 0); }
/** * @return array */ public function __invoke(array $props) { array_walk($props, function (&$item, $key) { if (is_array($item) || is_object($item)) { $item = \Zend\Json\Encoder::encode($item); } else { $item = addcslashes($item, "'\""); $item = sprintf('%s', trim(\Zend\Json\Encoder::encode($item), '{}')); } $item = sprintf('"%s": %s', $key, $item); }); return join(",\n", $props); }
public function onBootstrap(MvcEvent $e) { $serviceLocator = $e->getApplication()->getServiceManager(); GlobalEventManager::attach(EVENT_LOG_ERROR, function (Event $event) use($serviceLocator) { $message = Encoder::encode($event->getParams()); $serviceLocator->get('LogMongodbService')->addRecord(Logger::ERROR, $message, array()); return true; }); GlobalEventManager::attach(EVENT_LOG_DEBUG, function (Event $event) use($serviceLocator) { $message = Encoder::encode($event->getParams()); $serviceLocator->get('LogMongodbService')->addRecord(Logger::DEBUG, $message, array()); return true; }); }
/** * @param $status * @param string|AbstractModel|AbstractModel[] $body * @param null|MetaData $MetaData * * @return AbstractAPITest */ protected function mockGetListResponse($status = 200, $body = null, $MetaData = null) { if (is_string($body)) { $body = json_decode($body); } if ($body instanceof AbstractModel) { $body = [$body->getArrayCopy()]; } if (!is_array($body) && null !== $body) { $body = [$body]; } if (!$MetaData) { $MetaData = new MetaData(); $MetaData->setLimit(25)->setTotalCount(count($body)); } return $this->mockResponse($status, Encoder::encode(['meta' => $MetaData->getArrayCopy(), 'objects' => $body])); }
/** * * @param Options $options * @return \Zend\View\Model\JsonModel */ public function getData(Options $options = null) { if ($options === null) { // Take store global/default options $options = $this->store->getOptions(); // By default formatters are disabled in JSON $options->getHydrationOptions()->disableFormatters(); } $data = $this->store->getData($options); $d = array('success' => true, 'total' => $data->getTotalRows(), 'start' => $data->getSource()->getOptions()->getOffset(), 'limit' => $data->getSource()->getOptions()->getLimit(), 'data' => $data->toArray()); if ($this->options['debug']) { $source = $data->getSource(); if ($source instanceof QueryableSourceInterface) { $d['query'] = $source->getQueryString(); } } return Encoder::encode($d); }
/** * Setzt die Daten der Accountclientmessage * @param array $data * @return Accountclientmessage */ public function setData(array $data) { $this->data = \Zend\Json\Encoder::encode($data); return $this; }
/** * @return string */ protected function getMockData() { $data = (new Service(json_decode(APITest::getMockData())))->getLinkedToService(); return \Zend\Json\Encoder::encode(array_pop($data)); }
/** * Encode a value to JSON using the Encoder class. * * Passes the value, cycle check flag, and options to Encoder::encode(). * * Once the result is returned, determines if pretty printing is required, * and, if so, returns the result of that operation, otherwise returning * the encoded value. * * @param mixed $valueToEncode * @param bool $cycleCheck * @param array $options * @param bool $prettyPrint * @return string */ private static function encodeViaEncoder($valueToEncode, $cycleCheck, array $options, $prettyPrint) { $encodedResult = Encoder::encode($valueToEncode, $cycleCheck, $options); if ($prettyPrint) { return self::prettyPrint($encodedResult, ['indent' => ' ']); } return $encodedResult; }
/** * Create a json response based on the data * @param $data * @return \Zend\Stdlib\ResponseInterface */ private function jsonResponse($data) { $response = $this->getResponse(); $json = Encoder::encode($data); $response->setContent($json); return $response; }
/** * @return string */ protected function getMockData() { $data = (new NodeCluster(json_decode(APITest::getMockData())))->getProviderOptions(); return \Zend\Json\Encoder::encode($data); }
/** * @return string */ protected function getMockData() { $data = (new Container(json_decode(APITest::getMockData())))->getContainerPorts(); return \Zend\Json\Encoder::encode(array_pop($data)); }
/** * @return string */ protected function getMockData() { $data = new Model(json_decode('{"limit":25,"next":"next","offset":1,"previous":"previouse","total_count":1}', true)); return \Zend\Json\Encoder::encode($data); }
/** * @group ZF-4437 */ public function testKommaDecimalIsConvertedToCorrectJSONWithDot() { $localeInfo = localeconv(); if ($localeInfo['decimal_point'] != ",") { $this->markTestSkipped("This test only works for platforms where , is the decimal point separator."); } JSON\JSON::$useBuiltinEncoderDecoder = true; $this->assertEquals("[1.20, 1.68]", JSON\Encoder::encode(array((double) "1,20", (double) "1,68"))); }
/** * Prepare formatter and attach standard buttons for every row, as well as custom buttons, if needed * Code partially taken from jquery.jqGrid.src.js and must be updated if switching to next jqGrid verison * * @return string */ public function renderActionsFormatter() { $btns = $this->grid->getRowActionButtons() ?: new \stdClass(); $btns = Encoder::encode($btns); $formatterCode = <<<ACTION ;function {$this->getActionFunctioName()}(cellval,opts, rwd) { var rowid = opts.rowId ; if(rowid === undefined || \$.fmatter.isEmpty(rowid)) { return ""; } var ctm = {$btns}; var str = \$.fn.fmatter.actions(cellval,opts) ; var res = \$(str); if(ctm){ var saveBtn = res.find('[id^="jSaveButton"]'); var addStr = ''; for(var b in ctm){ addStr += "<div title='"+ctm[b]['name']+"' style='float:left;cursor:pointer;' class='"+ctm[b]['class']+"' id='jButton_"+rowid+"' onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); onclick="+ctm[b]['action']+" data-rowid='"+rowid+"'><span class='"+ctm[b]['icon']+"'></span></div>" } saveBtn.before(addStr); } return res.wrap('<div />').html() ; } ACTION; return $formatterCode; }
public function postDispatch() { $response = $this->getResponse(); $request = $this->getRequest(); /** * @var /App/Mvs/View/View */ $view = $this->getView(); // Если обработка остановлена в контроллере if ($this->stopProcessing || $this->withoutLayout) { $response->setBody($view->content); return $response; } $controller = $request->getParam('controller'); $action = $request->getParam('action'); $viewScript = $controller . '/' . $action . '.phtml'; $view->content = $view->render($viewScript); if ($request->getPost('ajaxForm')) { $title = $view->ajaxTitle ?: $view->metaTitle; $jsonData = array('status' => $view->responseStatus ?: 'ok', 'data' => array('title' => $title, 'content' => $view->content)); $response->setBody(\Zend\Json\Encoder::encode($jsonData)); } else { $response->setBody($view->renderLayout()); } return $response; //$content = $view->render($viewScript); //$this->getResponse()->setBody($content); }
/** * Check & Replace Zend\Json\Expr for tmp ids in the valueToEncode * * Check if the value is a Zend\Json\Expr, and if replace its value * with a magic key and save the javascript expression in an array. * * NOTE this method is recursive. * * NOTE: This method is used internally by the encode method. * * @see encode * @param mixed $value a string - object property to be encoded * @param array $javascriptExpressions * @param null|string|int $currentKey * @return mixed */ protected static function _recursiveJsonExprFinder(&$value, array &$javascriptExpressions, $currentKey = null) { if ($value instanceof Expr) { // TODO: Optimize with ascii keys, if performance is bad $magicKey = "____" . $currentKey . "_" . count($javascriptExpressions); $javascriptExpressions[] = array("magicKey" => is_int($currentKey) ? $magicKey : Encoder::encodeUnicodeString($magicKey), "value" => $value->__toString()); $value = $magicKey; } elseif (is_array($value)) { foreach ($value as $k => $v) { $value[$k] = static::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k); } } elseif (is_object($value)) { foreach ($value as $k => $v) { $value->{$k} = static::_recursiveJsonExprFinder($value->{$k}, $javascriptExpressions, $k); } } return $value; }
public function find($collectionName, $query, array $fields = array()) { $this->_connect(); $response = $this->_connection->restPost($this->_generatePath(self::PATH_TEMPORARY_VIEW) . '?limit=10&descending=true', \Zend\Json\Encoder::encode($this->_buildQuery($query))); try { return new DbDocument\Cursor\Couch($this->getCollection($collectionName), $this->_parseResponse($response)); } catch (\Exception $e) { return null; } }
/** * Publish message to queue. * * @param mixed $message (array or string) * @param Queue $queue * * @return bool|null */ public function send($message, Queue $queue = null) { if ($queue === null) { $queue = $this->_queue; } if (is_array($message)) { $message = \Zend\Json\Encoder::encode($message); } $this->exchangeName = 'router'; /* name: $exchange type: direct passive: false durable: true // the exchange will survive server restarts auto_delete: false //the exchange won't be deleted once the channel is closed. */ $this->channel->exchange_declare($this->exchangeName, 'direct', false, true, false); $this->channel->queue_bind($queue->getName(), $this->exchangeName); $amqpMessage = new AMQPMessage($message, ['content_type' => 'text/plain', 'delivery_mode' => 2]); $this->channel->basic_publish($amqpMessage, $this->exchangeName); }
/** * @param array $args * @param int $priority */ public function push(array $args) { if (!is_null($this->queue)) { if (class_exists('Zend\\Json\\Encoder')) { $body = \Zend\Json\Encoder::encode($args); } else { $body = json_encode($args); } $this->queue->send($body); $this->output->writeLn("<fg=green> [x] [{$this->queue->getName()}] {$args['command']} sent</>"); } }
protected function push($methodName, array $params = array()) { array_unshift($params, self::METHOD_PREFIX . $methodName); $jsArray = Encoder::encode($params); $output = sprintf('_gaq.push(%s);' . "\n", $jsArray); return $output; }
/** * Get Payload JSON * * @return string */ public function getPayloadJson() { $payload = $this->getPayload(); // don't escape utf8 payloads unless json_encode does not exist. if (defined('JSON_UNESCAPED_UNICODE')) { $payload = json_encode($payload, JSON_UNESCAPED_UNICODE); } else { $payload = JsonEncoder::encode($payload); } $length = strlen($payload); return pack('CNNnH*', 1, $this->id, $this->expire, 32, $this->token) . pack('n', $length) . $payload; }
public function toJson() { $string = \Zend\Json\Encoder::encode($this->getArrayCopy()); return preg_replace('/"__className[^,]*,/', '', $string); }
public function testPayloadJsonFormedCorrectly() { $text = 'hi=привет'; $this->message->setAlert($text); $this->message->setId(1); $this->message->setExpire(100); $this->message->setToken('0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'); $payload = $this->message->getPayload(); $this->assertEquals($payload, array('aps' => array('alert' => 'hi=привет'))); if (defined('JSON_UNESCAPED_UNICODE')) { $payloadJson = json_encode($payload, JSON_UNESCAPED_UNICODE); $this->assertEquals($payloadJson, '{"aps":{"alert":"hi=привет"}}'); $length = 35; // 23 + (2 * 6) because UTF-8 (Russian) "привет" contains 2 bytes per letter $result = pack('CNNnH*', 1, $this->message->getId(), $this->message->getExpire(), 32, $this->message->getToken()) . pack('n', $length) . $payloadJson; $this->assertEquals($this->message->getPayloadJson(), $result); } else { $payloadJson = JsonEncoder::encode($payload); $this->assertEquals($payloadJson, '{"aps":{"alert":"hi=\\u043f\\u0440\\u0438\\u0432\\u0435\\u0442"}}'); $length = 59; // (23 + (6 * 6) because UTF-8 (Russian) "привет" converts into 6 bytes per letter constructions $result = pack('CNNnH*', 1, $this->message->getId(), $this->message->getExpire(), 32, $this->message->getToken()) . pack('n', $length) . $payloadJson; $this->assertEquals($this->message->getPayloadJson(), $result); } }
/** * @group ZF-9521 */ public function testWillEncodeArrayOfObjectsEachWithToJsonMethod() { $array = array('one' => new ToJsonClass()); $expected = '{"one":{"__className":"ZendTest\\\\Json\\\\ToJSONClass","firstName":"John","lastName":"Doe","email":"*****@*****.**"}}'; Json\Json::$useBuiltinEncoderDecoder = true; $json = Json\Encoder::encode($array); $this->assertEquals($expected, $json); }
/** * Setzt die Session des Requestlogs * @param array $session * @return Requestlog */ public function setSession(array $session) { $this->session = \Zend\Json\Encoder::encode($session); return $this; }
/** * @group ZF-9416 * Encoding an iterator using the internal encoder should handle undefined keys */ public function testIteratorWithoutDefinedKey() { $inputValue = new \ArrayIterator(array('foo')); $encoded = Json\Encoder::encode($inputValue); $expectedDecoding = '{"__className":"ArrayIterator",0:"foo"}'; $this->assertEquals($expectedDecoding, $encoded); }
/** * Gets a valid OAuth2.0 access token * * @param bool $forceNewToken * @return string */ public function getToken($forceNewToken = false) { if ($this->session->offsetExists('accessToken') && $this->session->offsetExists('expiryTime') && is_string($this->session->accessToken) && $this->session->expiryTime > time() && !$forceNewToken) { return $this->session->accessToken; } $code = $this->getCode(); if ($code instanceof Response) { return $code; } $httpClient = new HttpClient($this->options->vendorOptions->tokenEntryUri); $httpClient->setMethod('POST'); $params = array(); foreach ($this->options->stage2->toArray() as $key => $param) { if ($key === 'code') { $param = urlencode($code); } if (empty($param)) { $param = $this->getDefaultParam($key); } $params[$key] = $param; } $httpClient->setParameterPost($params); if (is_array($this->options->vendorOptions->headers)) { $httpClient->setHeaders($this->options->vendorOptions->headers); } $content = $httpClient->send()->getContent(); if ($this->options->vendorOptions->responseFormat === 'urlencode') { try { $response = Json\Decoder::decode($content); } catch (\Zend\Json\Exception\RuntimeException $e) { if ($e->getMessage() !== 'Illegal Token') { throw new OAuth2Exception('Error decoding Json: ' . $e->getMessage()); } parse_str($content, $response); } } else { $response = Json\Decoder::decode($httpClient->send()->getContent()); } if ($this->isInResponse($response, 'error')) { $error = $this->getFromResponse($response, 'error'); if (is_object($error) && method_exists($error, 'type') && method_exists($error, 'code') && method_exists($error, 'message')) { throw new OAuth2Exception("{$error->type} ({$error->code}): {$error->message}"); } else { if (!is_string($error)) { $error = Json\Encoder::encode($error); } throw new OAuth2Exception("Error returned from vendor: {$error}"); } } $expires = $this->getFromResponse($response, 'expiresIn'); $token = $this->getFromResponse($response, 'accessToken'); $this->session->expiryTime = $expires + time(); $this->session->accessToken = $token; return $token; }