Пример #1
0
 public function getTestConfig()
 {
     $driverOptions = array();
     if (defined('TESTS_ZEND_QUEUE_DB')) {
         $driverOptions = \Zend\JSON\JSON::decode(TESTS_ZEND_QUEUE_DB);
     }
     return array('options' => array(Select\Select::FOR_UPDATE => true), 'driverOptions' => $driverOptions);
 }
Пример #2
0
 /**
  * Deserialize JSON to PHP value
  * 
  * @param  string $json 
  * @param  array $opts 
  * @return mixed
  */
 public function unserialize($json, array $opts = array())
 {
     $opts = $opts + $this->_options;
     try {
         $ret = ZendJSON::decode($json, $opts['objectDecodeType']);
     } catch (\Exception $e) {
         throw new SerializationException('Unserialization failed by previous error', 0, $e);
     }
     // json_decode returns null for invalid JSON
     if ($ret === null && $json !== 'null') {
         throw new SerializationException('Invalid json data');
     }
     return $ret;
 }
Пример #3
0
 public function testDbAdapterShouldReturnNoMessagesWhenZeroCountRequested()
 {
     if (!constant('TESTS_ZEND_QUEUE_DB_ENABLED')) {
         $this->markTestSkipped('Zend_Queue DB adapter tests are not enabled');
     }
     $driverOptions = array();
     if (defined('TESTS_ZEND_QUEUE_DB')) {
         $driverOptions = \Zend\JSON\JSON::decode(TESTS_ZEND_QUEUE_DB);
     }
     $options = array('name' => '/temp-queue/ZF7650', 'options' => array(\Zend\DB\Select\Select::FOR_UPDATE => true), 'driverOptions' => $driverOptions);
     $queue = new Queue\Queue('Db', $options);
     $queue2 = $queue->createQueue('queue');
     $queue->send('My Test Message 1');
     $queue->send('My Test Message 2');
     $messages = $queue->receive(0);
     $this->assertEquals(0, count($messages));
 }
Пример #4
0
 /**
  * Encode data as JSON, disable layouts, and set response header
  *
  * If $keepLayouts is true, does not disable layouts.
  *
  * @param  mixed $data
  * @param  bool $keepLayouts
  * NOTE:   if boolean, establish $keepLayouts to true|false
  *         if array, admit params for Zend_Json::encode as enableJsonExprFinder=>true|false
  *         this array can contains a 'keepLayout'=>true|false
  *         that will not be passed to Zend_Json::encode method but will be used here
  * @return string|void
  */
 public function direct($data = null, $keepLayouts = false)
 {
     if ($data == null) {
         throw new \InvalidArgumentException('JSON: missing argument. $data is required in json($data, $keepLayouts = false)');
     }
     $options = array();
     if (is_array($keepLayouts)) {
         $options = $keepLayouts;
         $keepLayouts = array_key_exists('keepLayouts', $keepLayouts) ? $keepLayouts['keepLayouts'] : false;
         unset($options['keepLayouts']);
     }
     $data = \Zend\JSON\JSON::encode($data, null, $options);
     if (!$keepLayouts) {
         $layout = LayoutManager::getMvcInstance();
         if ($layout instanceof LayoutManager) {
             $layout->disableLayout();
         }
     }
     $response = \Zend\Controller\Front::getInstance()->getResponse();
     $response->setHeader('Content-Type', 'application/json');
     return $data;
 }
Пример #5
0
 /**
  * Return JSON encoding of service
  *
  * @return string
  */
 public function toJSON()
 {
     $service = array($this->getName() => $this->toArray());
     return \Zend\JSON\JSON::encode($service);
 }
Пример #6
0
 public function testToStringImplementationShouldProxyToJSON()
 {
     $options = $this->getOptions();
     $this->smd->setOptions($options);
     $json = $this->smd->__toString();
     $smd = JSON\JSON::decode($json);
     $this->validateServiceArray($smd, $options);
 }
Пример #7
0
 public function testJsonHelperReturnsJsonEncodedString()
 {
     $data = $this->helper->direct('foobar');
     $this->assertTrue(is_string($data));
     $this->assertEquals('foobar', \Zend\JSON\JSON::decode($data));
 }
Пример #8
0
 public function validateJSON($json, array $options)
 {
     $test = JSON\JSON::decode($json);
     $this->assertTrue(is_array($test), var_export($json, 1));
     $this->assertTrue(array_key_exists('id', $test));
     $this->assertTrue(array_key_exists('method', $test));
     $this->assertTrue(array_key_exists('params', $test));
     $this->assertTrue(is_string($test['id']));
     $this->assertTrue(is_string($test['method']));
     $this->assertTrue(is_array($test['params']));
     $this->assertEquals($options['id'], $test['id']);
     $this->assertEquals($options['method'], $test['method']);
     $this->assertSame($options['params'], $test['params']);
 }
Пример #9
0
    /**
     * xml2json Test 6
     * It tests the conversion of demo application xml into JSON format.
     *
     * XML characteristic to be tested: XML containing a large CDATA.
     *
     */
    public function testUsingXML6()
    {
        // Set the XML contents that will be tested here.
        $xmlStringContents = <<<EOT
<?xml version="1.0"?>
<demo>
    <application>
        <name>Killer Demo</name>
    </application>

    <author>
        <name>John Doe</name>
    </author>

    <platform>
        <name>LAMP</name>
    </platform>

    <framework>
        <name>Zend</name>
    </framework>

    <language>
        <name>PHP</name>
    </language>

    <listing>
        <code>
            <![CDATA[
/*
It may not be a syntactically valid PHP code.
It is used here just to illustrate the CDATA feature of Zend_Xml2JSON
*/
<?php
include 'example.php';
new SimpleXMLElement();
echo(getMovies()->movie[0]->characters->addChild('character'));
getMovies()->movie[0]->characters->character->addChild('name', "Mr. Parser");
getMovies()->movie[0]->characters->character->addChild('actor', "John Doe");
// Add it as a child element.
getMovies()->movie[0]->addChild('rating', 'PG');
getMovies()->movie[0]->rating->addAttribute("type", 'mpaa');
echo getMovies()->asXML();
?>
            ]]>
        </code>
    </listing>
</demo>

EOT;
        // There are not going to be any XML attributes in this test XML.
        // Hence, set the flag to ignore XML attributes.
        $ignoreXmlAttributes = true;
        $jsonContents = "";
        $ex = null;
        // Convert XNL to JSON now.
        // fromXml function simply takes a String containing XML contents as input.
        try {
            $jsonContents = JSON\JSON::fromXml($xmlStringContents, $ignoreXmlAttributes);
        } catch (\Exception $ex) {
        }
        $this->assertSame($ex, null, "Zend_JSON::fromXml returned an exception.");
        // Convert the JSON string into a PHP array.
        $phpArray = JSON\JSON::decode($jsonContents);
        // Test if it is not a NULL object.
        $this->assertNotNull($phpArray, "JSON result for XML input 6 is NULL");
        // Test for one of the expected fields in the JSON result.
        $this->assertContains("Zend", $phpArray['demo']['framework']['name'], "The framework name field converted from XML input 6 is not correct");
        // Test for one of the expected CDATA fields in the JSON result.
        $this->assertContains('echo getMovies()->asXML();', $phpArray['demo']['listing']['code'], "The CDATA code converted from XML input 6 is not correct");
    }
Пример #10
0
 /**
  * Converts an associative array to a string of tag attributes.
  *
  * @access public
  *
  * @param array $attribs From this array, each key-value pair is
  * converted to an attribute name and value.
  *
  * @return string The XHTML for the attributes.
  */
 protected function _htmlAttribs($attribs)
 {
     $xhtml = '';
     foreach ((array) $attribs as $key => $val) {
         $key = $this->view->escape($key);
         if ('on' == substr($key, 0, 2) || 'constraints' == $key) {
             // Don't escape event attributes; _do_ substitute double quotes with singles
             if (!is_scalar($val)) {
                 // non-scalar data should be cast to JSON first
                 $val = \Zend\JSON\JSON::encode($val);
             }
             $val = preg_replace('/"([^"]*)":/', '$1:', $val);
         } else {
             if (is_array($val)) {
                 $val = implode(' ', $val);
             }
             $val = $this->view->escape($val);
         }
         if ('id' == $key) {
             $val = $this->_normalizeId($val);
         }
         if (strpos($val, '"') !== false) {
             $xhtml .= " {$key}='{$val}'";
         } else {
             $xhtml .= " {$key}=\"{$val}\"";
         }
     }
     return $xhtml;
 }
Пример #11
0
 public function testCastingToStringShouldCastToJSON()
 {
     $this->setupError();
     $json = $this->error->__toString();
     $this->validateArray(JSON\JSON::decode($json));
 }
Пример #12
0
 /**
  * Cast request to JSON
  *
  * @return string
  */
 public function toJSON()
 {
     $jsonArray = array('method' => $this->getMethod());
     if (null !== ($id = $this->getId())) {
         $jsonArray['id'] = $id;
     }
     $params = $this->getParams();
     if (!empty($params)) {
         $jsonArray['params'] = $params;
     }
     if ('2.0' == $this->getVersion()) {
         $jsonArray['jsonrpc'] = '2.0';
     }
     return JSON\JSON::encode($jsonArray);
 }
Пример #13
0
 public function testCanPreventDirectSendingResponse()
 {
     $data = $this->helper->direct(array('foobar'), false);
     $this->assertSame(array('foobar'), JSON\JSON::decode($data));
     $this->verifyJsonHeader();
     $response = $this->response->getBody();
     $this->assertTrue(empty($response));
 }
Пример #14
0
 public function testHandleShouldEmitResponseByDefault()
 {
     $this->markTestSkipped('Problems with Zend_Server conversion');
     $this->server->setClass('ZendTest\\JSON\\Foo');
     $request = $this->server->getRequest();
     $request->setMethod('bar')->setParams(array(true, 'foo', 'bar'))->setId('foo');
     ob_start();
     $this->server->handle();
     $buffer = ob_get_clean();
     $decoded = JSON\JSON::decode($buffer);
     $this->assertTrue(is_array($decoded));
     $this->assertTrue(array_key_exists('result', $decoded));
     $this->assertTrue(array_key_exists('id', $decoded));
     $response = $this->server->getResponse();
     $this->assertEquals($response->getResult(), $decoded['result']);
     $this->assertEquals($response->getId(), $decoded['id']);
 }
Пример #15
0
 /**
  * Returns the items of the current page as JSON.
  *
  * @return string
  */
 public function toJson()
 {
     $currentItems = $this->getCurrentItems();
     if ($currentItems instanceof \Zend\DB\Table\Rowset\AbstractRowset) {
         return JSON\JSON::encode($currentItems->toArray());
     } else {
         return JSON\JSON::encode($currentItems);
     }
 }
Пример #16
0
 public function testCastToStringShouldCastToJSON()
 {
     $this->response->setResult(true)->setId('foo');
     $json = $this->response->__toString();
     $test = JSON\JSON::decode($json);
     $this->assertTrue(is_array($test));
     $this->assertTrue(array_key_exists('result', $test));
     $this->assertTrue(array_key_exists('error', $test));
     $this->assertTrue(array_key_exists('id', $test));
     $this->assertFalse(array_key_exists('jsonrpc', $test));
     $this->assertTrue($test['result']);
     $this->assertEquals($this->response->getId(), $test['id']);
 }
Пример #17
0
 public function toJSON()
 {
     $data = array('expr' => new JSON\Expr($this->_expr), 'int' => $this->_int, 'string' => $this->_string);
     return JSON\JSON::encode($data, false, array('enableJSONExprFinder' => true));
 }
Пример #18
0
 public function testJsonContextShouldEncodeViewVariablesByDefaultAndNotRequireRenderingView()
 {
     $this->request->setParam('format', 'json')->setActionName('bar')->setDispatched(true);
     $this->controller->dispatch('barAction');
     $headers = $this->response->getHeaders();
     $found = false;
     foreach ($headers as $header) {
         if ($header['name'] == 'Content-Type') {
             if ($header['value'] == 'application/json') {
                 $found = true;
             }
             break;
         }
     }
     $this->assertTrue($found, 'JSON content type header not found');
     $body = $this->response->getBody();
     $result = \Zend\JSON\JSON::decode($body);
     $this->assertTrue(is_array($result), var_export($body, 1));
     $this->assertTrue(isset($result['foo']));
     $this->assertTrue(isset($result['bar']));
     $this->assertEquals('bar', $result['foo']);
     $this->assertEquals('baz', $result['bar']);
 }
Пример #19
0
 public function testTojsonShouldEmitJSON()
 {
     $this->setupSmdValidationObject();
     $json = $this->service->toJSON();
     $smd = \Zend\JSON\JSON::decode($json);
     $this->assertTrue(array_key_exists('foo', $smd));
     $this->assertTrue(is_array($smd['foo']));
     $this->validateSmdArray($smd['foo']);
 }
Пример #20
0
    /**
     * Get the HTML code for the captcha
     *
     * This method uses the public key to fetch a recaptcha form.
     *
     * @return string
     * @throws \Zend\Service\ReCaptcha\Exception
     */
    public function getHtml()
    {
        if ($this->_publicKey === null) {
            throw new Exception('Missing public key');
        }
        $host = self::API_SERVER;
        if ((bool) $this->_params['ssl'] === true) {
            $host = self::API_SECURE_SERVER;
        }
        $htmlBreak = '<br>';
        $htmlInputClosing = '>';
        if ((bool) $this->_params['xhtml'] === true) {
            $htmlBreak = '<br />';
            $htmlInputClosing = '/>';
        }
        $errorPart = '';
        if (!empty($this->_params['error'])) {
            $errorPart = '&error=' . urlencode($this->_params['error']);
        }
        $reCaptchaOptions = '';
        if (!empty($this->_options)) {
            $encoded = \Zend\JSON\JSON::encode($this->_options);
            $reCaptchaOptions = <<<SCRIPT
<script type="text/javascript">
    var RecaptchaOptions = {$encoded};
</script>
SCRIPT;
        }
        $return = $reCaptchaOptions;
        $return .= <<<HTML
<script type="text/javascript"
   src="{$host}/challenge?k={$this->_publicKey}{$errorPart}">
</script>
HTML;
        $return .= <<<HTML
<noscript>
   <iframe src="{$host}/noscript?k={$this->_publicKey}{$errorPart}"
       height="300" width="500" frameborder="0"></iframe>{$htmlBreak}
   <textarea name="recaptcha_challenge_field" rows="3" cols="40">
   </textarea>
   <input type="hidden" name="recaptcha_response_field"
       value="manual_challenge"{$htmlInputClosing}
</noscript>
HTML;
        return $return;
    }
Пример #21
0
 /**
  * JSON post processing
  *
  * JSON serialize view variables to response body
  *
  * @return void
  */
 public function postJsonContext()
 {
     if (!$this->getAutoJsonSerialization()) {
         return;
     }
     $viewRenderer = HelperBroker\HelperBroker::getStaticHelper('viewRenderer');
     $view = $viewRenderer->view;
     if ($view instanceof View\ViewInterface) {
         if (method_exists($view, 'getVars')) {
             $vars = \Zend\JSON\JSON::encode($view->getVars());
             $this->getResponse()->setBody($vars);
         } else {
             throw new Action\Exception('View does not implement the getVars() method needed to encode the view into JSON');
         }
     }
 }
Пример #22
0
 /**
  * Cast error to JSON
  *
  * @return string
  */
 public function toJSON()
 {
     return \Zend\JSON\JSON::encode($this->toArray());
 }
Пример #23
0
 /**
  * Cast to JSON
  *
  * @return string
  */
 public function toJSON()
 {
     if ($this->isError()) {
         $response = array('result' => null, 'error' => $this->getError()->toArray(), 'id' => $this->getId());
     } else {
         $response = array('result' => $this->getResult(), 'id' => $this->getId(), 'error' => null);
     }
     if (null !== ($version = $this->getVersion())) {
         $response['jsonrpc'] = $version;
     }
     return \Zend\JSON\JSON::encode($response);
 }
Пример #24
0
 public function testDojoHelperSendsResponseByDefault()
 {
     $dojo = new Helper\AutoCompleteDojo();
     $dojo->suppressExit = true;
     $data = array('foo', 'bar', 'baz');
     $encoded = $dojo->direct($data);
     $decoded = JSON\JSON::decode($encoded);
     $test = array();
     foreach ($decoded['items'] as $item) {
         $test[] = $item['name'];
     }
     $this->assertSame($data, $test);
     $body = $this->response->getBody();
     $this->assertSame($encoded, $body);
 }