/** * Renders the current object into JSend (JSON) string * * @param int $encode_options json_encode() options bitmask * @return string JSON representation of current object * @see http://php.net/json_encode#refsect1-function.json-encode-parameters */ public function render($encode_options = NULL) { $data = array(); foreach ($this->_data as $key => $value) { $filter = Arr::get($this->_filters, $key); $data[$key] = $this->run_filter($value, $filter); } $result = array('status' => $this->_status, 'data' => $data); /** * Error response must contain status & message * while code & data are optional */ if ($this->_status === JSend::ERROR) { $result['message'] = $this->_message; if ($this->_code !== NULL) { $result['code'] = $this->_code; } if (empty($result['data'])) { unset($result['data']); } } try { $response = JSend::encode($result, $encode_options); } catch (JSend_Exception $e) { // If encoding failed, create a new JSend error object based on exception return JSend::factory()->message($e)->render(); } $this->protect() and $response = ')]}\',' . PHP_EOL . $response; return $response; }
/** * Tests that JSend::render_into() sets appropriate response headers and body * * @group jsend.render_into * @test */ public function test_render_into() { $response = new Response(); $data = array('foo' => 'bar'); $jsend = JSend::factory($data); $jsend->render_into($response); $decoded = json_decode($response->body(), TRUE); $this->assertSame($decoded['data'], $data); $this->assertTrue($response->headers('content-type') === 'application/json'); $this->assertTrue($response->headers('x-response-format') === 'jsend'); }