function content_negociation() { //return var_dump($_SERVER['HTTP_ACCEPT']); if (request_accepts('json')) { return "json"; } else { if (request_accepts('html')) { return "<h1>HTML</h1>"; } else { return 'Oops'; } } }
function test_request_accepts() { $env = env(); $env['SERVER']['HTTP_ACCEPT'] = null; assert_true(request_accepts('text/plain')); $env['SERVER']['HTTP_ACCEPT'] = 'text/html'; assert_true(request_accepts('html')); $env['SERVER']['HTTP_ACCEPT'] = 'text/*; application/json'; assert_true(request_accepts('html')); assert_true(request_accepts('text/html')); assert_true(request_accepts('text/plain')); assert_true(request_accepts('application/json')); assert_false(request_accepts('image/png')); assert_false(request_accepts('png')); assert_true(defined('TESTS_DOC_ROOT'), "Undefined 'TESTS_DOC_ROOT' constant"); $response = test_request(TESTS_DOC_ROOT . '05-content_negociation.php', 'GET', false, array(), array("Accept: image/png")); assert_equal("Oops", $response); $response = test_request(TESTS_DOC_ROOT . '05-content_negociation.php', 'GET', false, array(), array("Accept: text/html")); assert_equal("<h1>HTML</h1>", $response); $response = test_request(TESTS_DOC_ROOT . '05-content_negociation.php', 'GET', false, array(), array("Accept: application/json")); assert_equal("json", $response); }
function responds_with($env = null) { if (is_null($env)) { $env = env(); } $request_uri = request_uri(); $userAgent = $_SERVER['HTTP_USER_AGENT']; //return the HTML page for Facebook if (strpos($userAgent, "facebookexternalhit") > -1) { return 'html'; } //return the type if specified in the URL (/foo/bar.png returns png no matter what the header specifies) if (sizeof(explode('.', $request_uri)) >= 2) { return array_pop(explode('.', $request_uri)); } else { if (request_accepts('json')) { return 'json'; } else { return 'html'; } } }