/** * Send the response back to the client. */ public function send() { if (is_array($this->_body) || $this->_body instanceof JsonSerializable) { // Convert the response to JSON. $this->contentType = array('application/json', 'charset' => 'utf-8'); $this->_body = JSONUtil::encode($this->_body); } echo $this->_body; // Stop doing things once the response was sent. exit; }
/** * Get request data. This method only behaves correctly if the request content-type is * {@link ContentType::APPLICATION_X_WWW_FORM_URLENCODED} or {@link ContentType::APPLICATION_JSON}, or the request * method is POST. * * @param string $name The name of the data to get. * @param mixed $fallback A fallback value to use if the data does not exist. * * @return mixed */ public function data($name = null, $fallback = null) { $stack = $this->memoize('_stack', function () { if ($this->method === 'GET') { return $_GET; } else { $data = array(); if (ContentType::matches($this->contentType, ContentType::APPLICATION_X_WWW_FORM_URLENCODED)) { parse_str($this->body, $data); } else { if (ContentType::matches($this->contentType, ContentType::APPLICATION_JSON)) { $data = JSONUtil::decode($this->body, true); } else { // PHP's $_POST knows what's up with various content-types so we'll have one more crack. if ($this->method === 'POST') { return $_POST; } else { throw new Exception('Cannot extract data from a "' . $this->method . '" request with the content-type "' . $this->contentType . '".'); } } } return $data; } }); if ($name === null) { return $stack; } // TODO: return ObjectUtils::getDeepValue($stack, $name, $fallback) should work but want a chance to test thoroughly. return array_key_exists($name, $stack) ? $stack[$name] : $fallback; }