Skip to content

Commit 2b99757

Browse files
committed
Merge pull request #54 from tomvo/master
Simple JSONP Middleware class
2 parents 4db71c8 + 46d5d47 commit 2b99757

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Middleware/Jsonp.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
/**
3+
* JSONP Middleware Class for the Slim Framework
4+
*
5+
* @author Tom van Oorschot <[email protected]>
6+
* @since 17-12-2012
7+
*
8+
* Simple class to wrap the response of the application in a JSONP callback function.
9+
* The class is triggered when a get parameter of callback is found
10+
*
11+
* Usage
12+
* ====
13+
*
14+
* $app = new \Slim\Slim();
15+
* $app->add(new \Slim\Extras\Middleware\JSONPMiddleware());
16+
*
17+
*/
18+
19+
namespace Slim\Extras\Middleware;
20+
21+
class JSONPMiddleware extends \Slim\Middleware
22+
{
23+
public function call()
24+
{
25+
$callback = $this->app->request()->get('callback');
26+
27+
//Fetch the body first
28+
$this->next->call();
29+
30+
//If the JSONP callback parameter is set then wrap the response body in the original
31+
//callback string.
32+
if(!empty($callback)){
33+
//The response becomes a javascript response
34+
$this->app->contentType('application/javascript');
35+
36+
$jsonp_response = htmlspecialchars($callback) . "(" .$this->app->response()->body() . ")";
37+
$this->app->response()->body($jsonp_response);
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)