public function respondWithError($args) { // Make args' keys lowercase $args = array_combine(array_map('strtolower', array_keys($args)), array_values($args)); // See if an exception is passed (no default) $exception = null; if (isset($args['exception'])) { $exception = $args['exception']; } // Get the default exception noun if set $exceptionNoun = self::$exception_noun; // Add defaults $args = array_merge(array('code' => 500, 'description' => null, 'body' => null, 'noun' => $exception && $exceptionNoun ? new $exceptionNoun($exception) : null), $args); // Default "response" which we build into. Not returned, because the exception has it's own response $response = new SS_HTTPResponse(); // If there's a formatter if ($args['noun'] && ($formatter = RESTFormatter::get_formatter($this->request))) { // Format the response. Revert back to default response if we got nothing. $response = $formatter->format($args['noun'], array('*')); if (!$response) { $response = new SS_HTTPResponse(); } } else { if ($exception) { $exception = $args['exception']; $response->setBody($exception->getMessage() . "\n"); $response->addHeader('Content-Type', 'text/plain'); } } // If a specific body was provided, use that if ($args['body']) { $response->setBody($args['body']); } // Build an exception with those details $e = new SS_HTTPResponse_Exception($response->getBody(), $args['code'], $args['description']); $exceptionResponse = $e->getResponse(); // Add user specified headers foreach ($response->getHeaders() as $k => $v) { $exceptionResponse->addHeader($k, $v); } throw $e; }
function format($noun, $fields) { $this->document = new DOMDocument(); return parent::format($noun, $fields); }
function testFormattingNestedFields() { $formatter = RESTFormatter::get_formatter('application/json'); $r = $formatter->format(new RESTFormatterTest_A(1), array('Foo', 'Bar', 'B.How', 'B.Items.Zap', 'B.Items.Zing')); $this->assertEquals($r->getHeader('Content-Type'), 'application/json'); $this->assertEquals($r->getBody(), json_encode(array('$type' => 'RESTFormatterTest_A', 'Foo' => 4, 'Bar' => 'Ape', 'B' => array('$type' => 'RESTFormatterTest_Bs', 'How' => 'Why?', 'Items' => array(array('$type' => 'RESTFormatterTest_B', 'Zap' => 5, 'Zing' => 'Bonobo'), array('$type' => 'RESTFormatterTest_B', 'Zap' => 5, 'Zing' => 'Bonobo')))))); }