Completed
Push — 16753-fix-pjax ( 954723 )
by Alexander
13:41
created

Pjax::run()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 4.2337

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 3
cts 17
cp 0.1765
rs 9.52
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 4.2337
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\widgets;
9
10
use Yii;
11
use yii\base\Widget;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Html;
14
use yii\helpers\Json;
15
use yii\web\Response;
16
17
/**
18
 * Pjax is a widget integrating the [pjax](https://github.com/yiisoft/jquery-pjax) jQuery plugin.
19
 *
20
 * Pjax only deals with the content enclosed between its [[begin()]] and [[end()]] calls, called the *body content* of the widget.
21
 * By default, any link click or form submission (for those forms with `data-pjax` attribute) within the body content
22
 * will trigger an AJAX request. In responding to the AJAX request, Pjax will send the updated body content (based
23
 * on the AJAX request) to the client which will replace the old content with the new one. The browser's URL will then
24
 * be updated using pushState. The whole process requires no reloading of the layout or resources (js, css).
25
 *
26
 * You may configure [[linkSelector]] to specify which links should trigger pjax, and configure [[formSelector]]
27
 * to specify which form submission may trigger pjax.
28
 *
29
 * You may disable pjax for a specific link inside the container by adding `data-pjax="0"` attribute to this link.
30
 *
31
 * The following example shows how to use Pjax with the [[\yii\grid\GridView]] widget so that the grid pagination,
32
 * sorting and filtering can be done via pjax:
33
 *
34
 * ```php
35
 * use yii\widgets\Pjax;
36
 *
37
 * Pjax::begin();
38
 * echo GridView::widget([...]);
39
 * Pjax::end();
40
 * ```
41
 *
42
 * @author Qiang Xue <[email protected]>
43
 * @since 2.0
44
 */
45
class Pjax extends Widget
46
{
47
    /**
48
     * @var array the HTML attributes for the widget container tag. The following special options are recognized:
49
     *
50
     * - `tag`: string, the tag name for the container. Defaults to `div`
51
     *   This option is available since version 2.0.7.
52
     *   See also [[\yii\helpers\Html::tag()]].
53
     *
54
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
55
     */
56
    public $options = [];
57
    /**
58
     * @var string|false the jQuery selector of the links that should trigger pjax requests.
59
     * If not set, all links within the enclosed content of Pjax will trigger pjax requests.
60
     * If set to false, no code will be registered to handle links.
61
     * Note that if the response to the pjax request is a full page, a normal request will be sent again.
62
     */
63
    public $linkSelector;
64
    /**
65
     * @var string|false the jQuery selector of the forms whose submissions should trigger pjax requests.
66
     * If not set, all forms with `data-pjax` attribute within the enclosed content of Pjax will trigger pjax requests.
67
     * If set to false, no code will be registered to handle forms.
68
     * Note that if the response to the pjax request is a full page, a normal request will be sent again.
69
     */
70
    public $formSelector;
71
    /**
72
     * @var string The jQuery event that will trigger form handler. Defaults to "submit".
73
     * @since 2.0.9
74
     */
75
    public $submitEvent = 'submit';
76
    /**
77
     * @var bool whether to enable push state.
78
     */
79
    public $enablePushState = true;
80
    /**
81
     * @var bool whether to enable replace state.
82
     */
83
    public $enableReplaceState = false;
84
    /**
85
     * @var int pjax timeout setting (in milliseconds). This timeout is used when making AJAX requests.
86
     * Use a bigger number if your server is slow. If the server does not respond within the timeout,
87
     * a full page load will be triggered.
88
     */
89
    public $timeout = 1000;
90
    /**
91
     * @var bool|int how to scroll the page when pjax response is received. If false, no page scroll will be made.
92
     * Use a number if you want to scroll to a particular place.
93
     */
94
    public $scrollTo = false;
95
    /**
96
     * @var array additional options to be passed to the pjax JS plugin. Please refer to the
97
     * [pjax project page](https://github.com/yiisoft/jquery-pjax) for available options.
98
     */
99
    public $clientOptions;
100
    /**
101
     * {@inheritdoc}
102
     * @internal
103
     */
104
    public static $counter = 0;
105
    /**
106
     * {@inheritdoc}
107
     */
108
    public static $autoIdPrefix = 'p';
109
110
111
    /**
112
     * {@inheritdoc}
113
     */
114 3
    public function init()
115
    {
116 3
        parent::init();
117 3
        if (!isset($this->options['id'])) {
118 3
            $this->options['id'] = $this->getId();
119
        }
120
121 3
        if ($this->requiresPjax()) {
122
            ob_start();
123
            ob_implicit_flush(false);
124
            $view = $this->getView();
125
            $view->clear();
126
            $view->beginPage();
127
            $view->head();
128
            $view->beginBody();
129
            if ($view->title !== null) {
130
                return Html::tag('title', Html::encode($view->title));
131
            }
132
        } else {
133 3
            $options = $this->options;
134 3
            $tag = ArrayHelper::remove($options, 'tag', 'div');
135 3
            return Html::beginTag($tag, array_merge([
136 3
                'data-pjax-container' => '',
137 3
                'data-pjax-push-state' => $this->enablePushState,
138 3
                'data-pjax-replace-state' => $this->enableReplaceState,
139 3
                'data-pjax-timeout' => $this->timeout,
140 3
                'data-pjax-scrollto' => $this->scrollTo,
141 3
            ], $options));
142
        }
143
    }
144
145
    /**
146
     * {@inheritdoc}
147
     */
148 1
    public function run()
149
    {
150 1
        if (!$this->requiresPjax()) {
151 1
            $this->registerClientScript();
152
            return Html::endTag(ArrayHelper::remove($this->options, 'tag', 'div'));
153
        }
154
155
        $view = $this->getView();
156
        $view->endBody();
157
158
        $view->endPage(true);
159
160
        $content = ob_get_clean();
161
162
        // only need the content enclosed within this widget
163
        $response = Yii::$app->getResponse();
164
        $response->clearOutputBuffers();
165
        $response->setStatusCode(200);
166
        $response->format = Response::FORMAT_HTML;
167
        $response->content = $content;
168
        $response->headers->setDefault('X-Pjax-Url', Yii::$app->request->url);
169
        $response->send();
170
171
        Yii::$app->end();
172
    }
173
174
    /**
175
     * @return bool whether the current request requires pjax response from this widget
176
     */
177 3
    protected function requiresPjax()
178
    {
179 3
        $headers = Yii::$app->getRequest()->getHeaders();
180
181 3
        return $headers->get('X-Pjax') && explode(' ', $headers->get('X-Pjax-Container'))[0] === '#' . $this->options['id'];
182
    }
183
184
    /**
185
     * Registers the needed JavaScript.
186
     */
187 1
    public function registerClientScript()
188
    {
189 1
        $id = $this->options['id'];
190 1
        $this->clientOptions['push'] = $this->enablePushState;
191 1
        $this->clientOptions['replace'] = $this->enableReplaceState;
192 1
        $this->clientOptions['timeout'] = $this->timeout;
193 1
        $this->clientOptions['scrollTo'] = $this->scrollTo;
194 1
        if (!isset($this->clientOptions['container'])) {
195 1
            $this->clientOptions['container'] = "#$id";
196
        }
197 1
        $options = Json::htmlEncode($this->clientOptions);
198 1
        $js = '';
199 1
        if ($this->linkSelector !== false) {
200 1
            $linkSelector = Json::htmlEncode($this->linkSelector !== null ? $this->linkSelector : '#' . $id . ' a');
201 1
            $js .= "jQuery(document).pjax($linkSelector, $options);";
202
        }
203 1
        if ($this->formSelector !== false) {
204 1
            $formSelector = Json::htmlEncode($this->formSelector !== null ? $this->formSelector : '#' . $id . ' form[data-pjax]');
205 1
            $submitEvent = Json::htmlEncode($this->submitEvent);
206 1
            $js .= "\njQuery(document).on($submitEvent, $formSelector, function (event) {jQuery.pjax.submit(event, $options);});";
207
        }
208 1
        $view = $this->getView();
209 1
        PjaxAsset::register($view);
210
211
        if ($js !== '') {
212
            $view->registerJs($js);
213
        }
214
    }
215
}
216