예제 #1
0
파일: DBTest.php 프로젝트: bradley-holt/zf2
 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
파일: JSON.php 프로젝트: stunti/zf2
 /**
  * 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
파일: JSON.php 프로젝트: stunti/zf2
 /**
  * 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
파일: Service.php 프로젝트: stunti/zf2
 /**
  * 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
파일: JSONTest.php 프로젝트: stunti/zf2
 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
파일: JSONXMLTest.php 프로젝트: stunti/zf2
    /**
     * 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
파일: HtmlElement.php 프로젝트: stunti/zf2
 /**
  * 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
파일: Request.php 프로젝트: stunti/zf2
 /**
  * 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
파일: JsonTest.php 프로젝트: stunti/zf2
 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
파일: Paginator.php 프로젝트: stunti/zf2
 /**
  * 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
파일: JsonTest.php 프로젝트: stunti/zf2
 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
파일: ReCaptcha.php 프로젝트: stunti/zf2
    /**
     * 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
파일: Error.php 프로젝트: stunti/zf2
 /**
  * Cast error to JSON
  *
  * @return string
  */
 public function toJSON()
 {
     return \Zend\JSON\JSON::encode($this->toArray());
 }
예제 #23
0
파일: Response.php 프로젝트: stunti/zf2
 /**
  * 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);
 }