Make response format more configurable

This commit is contained in:
Vyacheslav Slinko 2012-10-17 15:15:35 +04:00
parent f25c2f1eeb
commit 3540bcfcd8
6 changed files with 87 additions and 82 deletions

View File

@ -28,17 +28,20 @@ class Configuration implements ConfigurationInterface
->children() ->children()
->scalarNode('enabled')->defaultTrue()->end() ->scalarNode('enabled')->defaultTrue()->end()
->scalarNode('endpoint')->defaultValue('/app_dev.php')->end() ->scalarNode('endpoint')->defaultValue('/app_dev.php')->end()
->enumNode('json_declaration_method') ->enumNode('request_format_method')
->values(array('format_param', 'accept_header')) ->values(array('format_param', 'accept_header'))
->defaultValue('format_param') ->defaultValue('format_param')
->end() ->end()
->arrayNode('authentication') ->arrayNode('authentication')
->children() ->children()
->scalarNode('name')->isRequired()->end() ->scalarNode('name')->isRequired()->end()
->enumNode('delivery') ->scalarNode('delivery')
// header|query|request, but only query is implemented for now
->values(array('query'))
->isRequired() ->isRequired()
->validate()
// header|query|request, but only query is implemented for now
->ifNotInArray(array('query'))
->thenInvalid("Unknown authentication delivery type '%s'.")
->end()
->end() ->end()
->end() ->end()
->end() ->end()

View File

@ -31,7 +31,7 @@ class NelmioApiDocExtension extends Extension
$container->setParameter('nelmio_api_doc.api_name', $config['name']); $container->setParameter('nelmio_api_doc.api_name', $config['name']);
$container->setParameter('nelmio_api_doc.sandbox.enabled', $config['sandbox']['enabled']); $container->setParameter('nelmio_api_doc.sandbox.enabled', $config['sandbox']['enabled']);
$container->setParameter('nelmio_api_doc.sandbox.endpoint', $config['sandbox']['endpoint']); $container->setParameter('nelmio_api_doc.sandbox.endpoint', $config['sandbox']['endpoint']);
$container->setParameter('nelmio_api_doc.sandbox.json_declaration_method', $config['sandbox']['json_declaration_method']); $container->setParameter('nelmio_api_doc.sandbox.request_format_method', $config['sandbox']['request_format_method']);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('formatters.xml'); $loader->load('formatters.xml');

View File

@ -43,7 +43,7 @@ class HtmlFormatter extends AbstractFormatter
/** /**
* @var string * @var string
*/ */
private $jsonDeclarationMethod; private $requestFormatMethod;
/** /**
* @param array $authentication * @param array $authentication
@ -88,9 +88,9 @@ class HtmlFormatter extends AbstractFormatter
/** /**
* @param string $method * @param string $method
*/ */
public function setJsonDeclarationMethod($method) public function setRequestFormatMethod($method)
{ {
$this->jsonDeclarationMethod = $method; $this->requestFormatMethod = $method;
} }
/** /**
@ -146,14 +146,14 @@ class HtmlFormatter extends AbstractFormatter
private function getGlobalVars() private function getGlobalVars()
{ {
return array( return array(
'apiName' => $this->apiName, 'apiName' => $this->apiName,
'authentication' => $this->authentication, 'authentication' => $this->authentication,
'endpoint' => $this->endpoint, 'endpoint' => $this->endpoint,
'enableSandbox' => $this->enableSandbox, 'enableSandbox' => $this->enableSandbox,
'jsonDeclarationMethod' => $this->jsonDeclarationMethod, 'requestFormatMethod' => $this->requestFormatMethod,
'date' => date(DATE_RFC822), 'date' => date(DATE_RFC822),
'css' => file_get_contents(__DIR__ . '/../Resources/public/css/screen.css'), 'css' => file_get_contents(__DIR__ . '/../Resources/public/css/screen.css'),
'js' => file_get_contents(__DIR__ . '/../Resources/public/js/all.js'), 'js' => file_get_contents(__DIR__ . '/../Resources/public/js/all.js'),
); );
} }

View File

@ -37,8 +37,8 @@
<call method="setEndpoint"> <call method="setEndpoint">
<argument>%nelmio_api_doc.sandbox.endpoint%</argument> <argument>%nelmio_api_doc.sandbox.endpoint%</argument>
</call> </call>
<call method="setJsonDeclarationMethod"> <call method="setRequestFormatMethod">
<argument>%nelmio_api_doc.sandbox.json_declaration_method%</argument> <argument>%nelmio_api_doc.sandbox.request_format_method%</argument>
</call> </call>
<call method="setAuthentication"> <call method="setAuthentication">
<argument>%nelmio_api_doc.sandbox.authentication%</argument> <argument>%nelmio_api_doc.sandbox.authentication%</argument>

View File

@ -148,9 +148,9 @@ table tbody tr:last-child td {
text-decoration: none; text-decoration: none;
} }
#api_key_wrapper { #sandbox_configuration {
float: right; float: right;
padding: 10px 0 10px 0; padding: 10px 0 10px 0;
} }
#colophon { #colophon {

View File

@ -15,11 +15,16 @@
<body> <body>
<div id="header"> <div id="header">
<a href=""><h1>{{ apiName }}</h1></a> <a href=""><h1>{{ apiName }}</h1></a>
{% if authentication %} <div id="sandbox_configuration">
<div id="api_key_wrapper"> request format:
api key: <input type="text" id="api_key"/> <select id="request_format">
<option value="json">JSON</option>
<option value="xml">XML</option>
</select>
{% if authentication %}
api key: <input type="text" id="api_key"/>
{% endif %}
</div> </div>
{% endif %}
<br style="clear: both;" /> <br style="clear: both;" />
</div> </div>
<div class="container" id="resources_container"> <div class="container" id="resources_container">
@ -37,42 +42,42 @@
{% if enableSandbox %} {% if enableSandbox %}
var toggleButtonText = function ($btn) { var toggleButtonText = function ($btn) {
if ($btn.text() === 'Default') { if ($btn.text() === 'Default') {
$btn.text('Raw'); $btn.text('Raw');
} else { } else {
$btn.text('Default'); $btn.text('Default');
} }
}; };
var renderRawBody = function ($container) { var renderRawBody = function ($container) {
var rawData, $btn; var rawData, $btn;
rawData = $container.data('raw-response'); rawData = $container.data('raw-response');
$btn = $container.parents('.pane').find('.to-raw'); $btn = $container.parents('.pane').find('.to-raw');
$container.addClass('prettyprinted'); $container.addClass('prettyprinted');
$container.html(rawData); $container.html($('<div/>').text(rawData).html());
$btn.removeClass('to-raw'); $btn.removeClass('to-raw');
$btn.addClass('to-prettify'); $btn.addClass('to-prettify');
toggleButtonText($btn); toggleButtonText($btn);
}; };
var renderPrettifiedBody = function ($container) { var renderPrettifiedBody = function ($container) {
var rawData, $btn; var rawData, $btn;
rawData = $container.data('raw-response'); rawData = $container.data('raw-response');
$btn = $container.parents('.pane').find('.to-prettify'); $btn = $container.parents('.pane').find('.to-prettify');
$container.removeClass('prettyprinted'); $container.removeClass('prettyprinted');
$container.html(prettifyResponse(rawData)); $container.html(prettifyResponse(rawData));
prettyPrint && prettyPrint(); prettyPrint && prettyPrint();
$btn.removeClass('to-prettify'); $btn.removeClass('to-prettify');
$btn.addClass('to-raw'); $btn.addClass('to-raw');
toggleButtonText($btn); toggleButtonText($btn);
}; };
$('.tabs li').click(function() { $('.tabs li').click(function() {
@ -88,7 +93,7 @@
var prettifyResponse = function(text) { var prettifyResponse = function(text) {
try { try {
var data = typeof text === 'string' ? JSON.parse(text) : text; var data = typeof text === 'string' ? JSON.parse(text) : text;
text = JSON.stringify(data, undefined, ' '); text = JSON.stringify(data, undefined, ' ');
} catch (err) { } catch (err) {
} }
@ -105,11 +110,7 @@
container.data('raw-response', data); container.data('raw-response', data);
if ('<' === data[0]) { renderPrettifiedBody(container);
renderRawBody(container);
} else {
renderPrettifiedBody(container);
}
container.parents('.pane').find('.to-prettify').text('Raw'); container.parents('.pane').find('.to-prettify').text('Raw');
container.parents('.pane').find('.to-raw').text('Raw'); container.parents('.pane').find('.to-raw').text('Raw');
@ -136,45 +137,46 @@
self = this, self = this,
params = {}, params = {},
headers = {}, headers = {},
content = $(this).find('textarea.content').val(); content = $(this).find('textarea.content').val(),
result_container = $('.result', $(this).parent()); result_container = $('.result', $(this).parent());
var jsonDeclarationMethod = '{{ jsonDeclarationMethod }}'; var requestFormat = $('#request_format').val();
if (jsonDeclarationMethod == 'format_param') { var requestFormatMethod = '{{ requestFormatMethod }}';
params['_format'] = 'json'; if (requestFormatMethod == 'format_param') {
} else if (jsonDeclarationMethod == 'accept_header') { params['_format'] = requestFormat;
headers['Accept'] = 'application/json'; } else if (requestFormatMethod == 'accept_header') {
headers['Accept'] = 'application/' + requestFormat;
} }
// retrieve all the parameters to send // retrieve all the parameters to send
$('.parameters .tuple', $(this)).each(function() { $('.parameters .tuple', $(this)).each(function() {
var key, value; var key, value;
key = $('.key', $(this)).val(); key = $('.key', $(this)).val();
value = $('.value', $(this)).val(); value = $('.value', $(this)).val();
if (value) { if (value) {
params[key] = value; params[key] = value;
} }
}); });
// retrieve the additional headers to send // retrieve the additional headers to send
$('.headers .tuple', $(this)).each(function() { $('.headers .tuple', $(this)).each(function() {
var key, value; var key, value;
key = $('.key', $(this)).val(); key = $('.key', $(this)).val();
value = $('.value', $(this)).val(); value = $('.value', $(this)).val();
if (value) { if (value) {
headers[key] = value; headers[key] = value;
} }
}); });
// fix parameters in URL // fix parameters in URL
for (var key in $.extend({}, params)) { for (var key in $.extend({}, params)) {
if (url.indexOf('{' + key + '}') !== -1) { if (url.indexOf('{' + key + '}') !== -1) {
url = url.replace('{' + key + '}', params[key]); url = url.replace('{' + key + '}', params[key]);
delete params[key]; delete params[key];
} }
}; };
@ -189,16 +191,16 @@
// and trigger the API call // and trigger the API call
$.ajax({ $.ajax({
url: '{{ endpoint }}' + url, url: '{{ endpoint }}' + url,
type: method, type: method,
data: content.length ? content : params, data: content.length ? content : params,
headers: headers, headers: headers,
complete: function(xhr) { complete: function(xhr) {
displayResponse(xhr, method, url, result_container); displayResponse(xhr, method, url, result_container);
// and enable them back // and enable them back
$('input:not(.content-type), button', $(self)).removeAttr('disabled'); $('input:not(.content-type), button', $(self)).removeAttr('disabled');
} }
}); });
return false; return false;