Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make "respond to" recognize HTTP Accept header request for JSON #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/RequestDispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,10 @@ private function shouldReturnJson()
return (
isset($_GET['json']) ||
$this->outputFormat === 'json' ||
(
! empty( $_SERVER['HTTP_ACCEPT'] ) &&
strtolower( $_SERVER['HTTP_ACCEPT'] ) == 'application/json'
) ||
(
! empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) &&
strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' &&
Expand Down
26 changes: 26 additions & 0 deletions tests/unit/RouterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1380,6 +1380,32 @@ function testHandlerReturningRespondToJsonToXmlHttpRequest()
);
}

function testHandlerReturningRespondToJsonToAcceptJson()
{
$_SERVER['HTTP_ACCEPT'] = 'application/json';

\WP_Mock::wpFunction( 'wp_send_json', array(
'times' => 1,
'return' => 'json data output',
) );

$router = Router::create();

$router->get('users', 'get_users', function(){
return ['respond_to' => [
'json' => 'irrelevant data as wp_send_json return data is mocked above',
'html' => function(){
return 'users view loaded';
}
]];
});

$this->assertEquals(
'json data output',
$router->dispatch('GET', 'users')
);
}

function testHandlerReturningRespondToJsonToRequestWithJsonGetParam()
{
\WP_Mock::wpFunction( 'wp_send_json', array(
Expand Down