|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TechPivot\Phalcon\Enterprise\Dispatcher\Plugins; |
|
4
|
|
|
|
|
5
|
|
|
use Phalcon\Events\Event; |
|
6
|
|
|
use Phalcon\Mvc\Dispatcher; |
|
7
|
|
|
use Phalcon\Mvc\User\Plugin; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* AjaxRouteHandler. |
|
11
|
|
|
* |
|
12
|
|
|
* This plugin provides consistent behavior for handling return content for AJAX requests by using |
|
13
|
|
|
* the return value from the route's action. |
|
14
|
|
|
* |
|
15
|
|
|
* Routes simply need to return data that should be returned as json. For example: |
|
16
|
|
|
* |
|
17
|
|
|
* <code> |
|
18
|
|
|
* public function ajaxAction() |
|
19
|
|
|
* { |
|
20
|
|
|
* return [ |
|
21
|
|
|
* 'ok' => true |
|
22
|
|
|
* ]; |
|
23
|
|
|
* } |
|
24
|
|
|
* </code> |
|
25
|
|
|
* |
|
26
|
|
|
* Will result in the actual response that contains the formatted JSON: |
|
27
|
|
|
* |
|
28
|
|
|
* <pre>{"ok":true}</pre> |
|
29
|
|
|
* |
|
30
|
|
|
* Note: Automatic view disabling is appropriately handled. |
|
31
|
|
|
* |
|
32
|
|
|
* Note: If the response is AJAX and the return value is <tt>null</tt>, the HTTP response will be an empty |
|
33
|
|
|
* response with status code 204. |
|
34
|
|
|
*/ |
|
35
|
|
|
class AjaxRouteHandler extends Plugin |
|
36
|
|
|
{ |
|
37
|
|
|
/** |
|
38
|
|
|
* Automatically handle ajax return data. |
|
39
|
|
|
* |
|
40
|
|
|
* @param \Phalcon\Events\Event $event The afterExecuteRoute event. |
|
41
|
|
|
* @param \Phalcon\Mvc\Dispatcher $dispatcher The application dispatcher instance. |
|
42
|
|
|
* |
|
43
|
|
|
* @return \Phalcon\Http\Response|void |
|
44
|
|
|
*/ |
|
45
|
|
|
public function afterExecuteRoute(Event $event, Dispatcher $dispatcher) |
|
|
|
|
|
|
46
|
|
|
{ |
|
47
|
|
|
/** @var \Phalcon\Http\Request $request */ |
|
48
|
|
|
$request = $this->getDI()->getShared('request'); |
|
49
|
|
|
|
|
50
|
|
|
if ($request->isAjax()) { |
|
51
|
|
|
/** @var \Phalcon\Mvc\View $view */ |
|
52
|
|
|
$view = $this->getDI()->getShared('view'); |
|
53
|
|
|
$view->disable(); |
|
54
|
|
|
|
|
55
|
|
|
/** @var \Phalcon\Http\Response $response */ |
|
56
|
|
|
$response = $this->getDI()->getShared('response'); |
|
57
|
|
|
if ($response->isSent() === false && $response->getStatusCode() === false) { |
|
58
|
|
|
$data = $dispatcher->getReturnedValue(); |
|
59
|
|
|
|
|
60
|
|
|
if ($data === null) { |
|
61
|
|
|
$response->setStatusCode(204); |
|
62
|
|
|
} else { |
|
63
|
|
|
$response->setJsonContent($data); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $response->send(); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.