AjaxRouteHandler   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
c 2
b 0
f 0
lcom 0
cbo 5
dl 0
loc 40
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B afterExecuteRoute() 0 29 5
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 beforeDispatchLoop 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
                    // Phalcon 2.0.x requires setting of the content type. Phalcon >= 2.1.x automatically includes
66
                    // this method upon setting of the JSON content.
67
                    $response->setContentType('application/json', 'UTF-8');
68
                }
69
70
                return $response->send();
71
            }
72
        }
73
    }
74
}
75