Ejemplo n.º 1
0
 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);
 }
Ejemplo n.º 2
0
 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()));
 }
 /**
  * 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 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);
 }
Ejemplo n.º 5
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);
 }
Ejemplo n.º 6
0
 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]));
 }
Ejemplo n.º 8
0
 /**
  *
  * @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;
 }
Ejemplo n.º 10
0
 /**
  * @return string
  */
 protected function getMockData()
 {
     $data = (new Service(json_decode(APITest::getMockData())))->getLinkedToService();
     return \Zend\Json\Encoder::encode(array_pop($data));
 }
Ejemplo n.º 11
0
 /**
  * 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;
 }
Ejemplo n.º 12
0
 /**
  * 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);
 }
Ejemplo n.º 14
0
 /**
  * @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</>");
     }
 }
Ejemplo n.º 15
0
 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);
     }
 }
Ejemplo n.º 16
0
 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);
 }
Ejemplo n.º 17
0
    /**
     * 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;
    }
Ejemplo n.º 18
0
 /**
  * @return string
  */
 protected function getMockData()
 {
     $data = (new Container(json_decode(APITest::getMockData())))->getContainerPorts();
     return \Zend\Json\Encoder::encode(array_pop($data));
 }
Ejemplo n.º 19
0
 /**
  * Encode the mixed $valueToEncode into the JSON format
  *
  * Encodes using ext/json's json_encode() if available.
  *
  * NOTE: Object should not contain cycles; the JSON format
  * does not allow object reference.
  *
  * NOTE: Only public variables will be encoded
  *
  * NOTE: Encoding native javascript expressions are possible using Zend\Json\Expr.
  *       You can enable this by setting $options['enableJsonExprFinder'] = true
  *
  * @see Zend\Json\Expr
  *
  * @param  mixed $valueToEncode
  * @param  bool $cycleCheck Optional; whether or not to check for object recursion; off by default
  * @param  array $options Additional options used during encoding
  * @return string JSON encoded object
  */
 public static function encode($valueToEncode, $cycleCheck = false, $options = array())
 {
     if (is_object($valueToEncode)) {
         if (method_exists($valueToEncode, 'toJson')) {
             return $valueToEncode->toJson();
         } elseif (method_exists($valueToEncode, 'toArray')) {
             return static::encode($valueToEncode->toArray(), $cycleCheck, $options);
         }
     }
     // Pre-encoding look for Zend\Json\Expr objects and replacing by tmp ids
     $javascriptExpressions = array();
     if (isset($options['enableJsonExprFinder']) && $options['enableJsonExprFinder'] == true) {
         $valueToEncode = static::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
     }
     // Encoding
     if (function_exists('json_encode') && static::$useBuiltinEncoderDecoder !== true) {
         $encodedResult = json_encode($valueToEncode, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
     } else {
         $encodedResult = Encoder::encode($valueToEncode, $cycleCheck, $options);
     }
     //only do post-processing to revert back the Zend\Json\Expr if any.
     if (count($javascriptExpressions) > 0) {
         $count = count($javascriptExpressions);
         for ($i = 0; $i < $count; $i++) {
             $magicKey = $javascriptExpressions[$i]['magicKey'];
             $value = $javascriptExpressions[$i]['value'];
             $encodedResult = str_replace('"' . $magicKey . '"', $value, $encodedResult);
         }
     }
     return $encodedResult;
 }
Ejemplo n.º 20
0
 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;
     }
 }
Ejemplo n.º 21
0
 /**
  * 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);
 }
 /**
  * Setzt die Session des Requestlogs
  * @param array $session
  * @return Requestlog
  */
 public function setSession(array $session)
 {
     $this->session = \Zend\Json\Encoder::encode($session);
     return $this;
 }
Ejemplo n.º 23
0
 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;
 }
Ejemplo n.º 24
0
 /**
  * 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;
 }
Ejemplo n.º 25
0
 public function toJson()
 {
     $string = \Zend\Json\Encoder::encode($this->getArrayCopy());
     return preg_replace('/"__className[^,]*,/', '', $string);
 }
Ejemplo n.º 26
0
 /**
  * @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);
 }
Ejemplo n.º 27
0
 /**
  * @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);
 }
Ejemplo n.º 28
0
    /**
     * Encode the mixed $valueToEncode into the JSON format
     *
     * Encodes using ext/json's json_encode() if available.
     *
     * NOTE: Object should not contain cycles; the JSON format
     * does not allow object reference.
     *
     * NOTE: Only public variables will be encoded
     *
     * NOTE: Encoding native javascript expressions are possible using Zend_Json_Expr.
     *       You can enable this by setting $options['enableJsonExprFinder'] = true
     *
     * @see Zend_Json_Expr
     *
     * @param  mixed $valueToEncode
     * @param  boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
     * @param  array $options Additional options used during encoding
     * @return string JSON encoded object
     */
    public static function encode($valueToEncode, $cycleCheck = false, $options = array())
    {
        if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
            return $valueToEncode->toJson();
        }

        // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
        $javascriptExpressions = array();
        if(isset($options['enableJsonExprFinder'])
           && ($options['enableJsonExprFinder'] == true)
        ) {
            $valueToEncode = self::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
        }

        // Encoding
        if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
            $encodedResult = json_encode($valueToEncode);
        } else {
            $encodedResult = Encoder::encode($valueToEncode, $cycleCheck, $options);
        }

        //only do post-proccessing to revert back the Zend_Json_Expr if any.
        if (count($javascriptExpressions) > 0) {
            $count = count($javascriptExpressions);
            for($i = 0; $i < $count; $i++) {
                $magicKey = $javascriptExpressions[$i]['magicKey'];
                $value    = $javascriptExpressions[$i]['value'];

                $encodedResult = str_replace(
                    //instead of replacing "key:magicKey", we replace directly magicKey by value because "key" never changes.
                    '"' . $magicKey . '"',
                    $value,
                    $encodedResult
                );
            }
        }

        return $encodedResult;
    }
Ejemplo n.º 29
0
 /**
  * @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);
 }
Ejemplo n.º 30
0
 /**
  * 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;
 }