-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathapi.php
More file actions
56 lines (47 loc) · 1.46 KB
/
api.php
File metadata and controls
56 lines (47 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
/**
* API Middleware Class for the Slim Framework
*
* @author Montana Flynn <montana@montanaflynn.me>
* @since 3/10/13
*
* Simple class to make building API's easier
*
* Usage
* ====
*
* $api = new \Slim\slim();
* $api->add(new \Slim\Extras\Middleware\API());
*
*/
namespace Slim\Extras\Middleware;
class API extends \Slim\Middleware
{
public function call()
{
// Just to make things easy, we can avoid the 404 page and override with
// helpful error messages. May extend later to find all registered endpoints
$app = $this->app;
// Change to json
$response = $app->response();
$response['Content-Type'] = 'application/json';
// No Endpoint Specified?
$app->get('/', function() use ($app) {
$app->halt(400, json_encode(array('error'=>'You must specify an endpoint!')));
});
// Cannot Find Endpoint?
$app->get('/:method', function($method) use ($app) {
$app->halt(400, json_encode(array('error'=>'There is no endpoint named '.$method.'!')));
})->conditions(array('method' => '.+'));
// Move along to next call
$this->next->call();
// But wait! Let's add support for jsonp callbacks
$request = $app->request();
$callback = $request->params('callback');
if(!empty($callback)){
$app->contentType('application/javascript');
$jsonp_response = $callback . "(" .$app->response()->body() . ")";
$app->response()->body($jsonp_response);
}
}
}