AjaxModal::getModalFormId()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
cc 2
nc 2
nop 0
crap 6
1
<?php
2
/**
3
 * HiPanel core package
4
 *
5
 * @link      https://hipanel.com/
6
 * @package   hipanel-core
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2014-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\widgets;
12
13
use Yii;
14
use yii\base\InvalidConfigException;
15
use yii\helpers\Html;
16
use yii\helpers\Json;
17
use yii\helpers\Url;
18
use yii\web\JsExpression;
19
20
/**
21
 * Class AjaxModal.
22
 *
23
 * @property $actionUrl string URL
24
 * @property $modalFormId string ID for modal form
25
 * @property $errorText string The error text for PNotify generation. On set will be processed through [[Yii::t()]]
26
 * @property $successText string The success text for PNotify generation. On set will be processed through [[Yii::t()]]
27
 * @property $loadingText string The text that will be displayed on submit button after press. On set will be processed through [[Yii::t()]]
28
 * @property $loadingHtml string The HTML to be appended to the modal body
29
 */
30
class AjaxModal extends \yii\bootstrap\Modal
31
{
32
    /**
33
     * @var bool
34
     */
35
    public $bulkPage = false;
36
37
    /**
38
     * @var bool
39
     */
40
    public $usePost = false;
41
42
    /**
43
     * @var string
44
     */
45
    public $scenario;
46
47
    /**
48
     * @var string URL
49
     */
50
    protected $_actionUrl;
51
52
    /**
53
     * @var string ID for modal form
54
     */
55
    protected $_modalFormId;
56
57
    /**
58
     * @var string The error text for PNotify generation.
59
     * On set will be processed through [[Yii::t()]]
60
     */
61
    protected $_errorText;
62
63
    /**
64
     * @var string The success text for PNotify generation.
65
     * On set will be processed through [[Yii::t()]]
66
     */
67
    protected $_successText;
68
69
    /**
70
     * @var string The text that will be displayed on submit button after press.
71
     * On set will be processed through [[Yii::t()]]
72
     */
73
    protected $_loadingText;
74
75
    /**
76
     * @var boolean whether to handle the submit of the form in the modal with special AJAX script
77
     * @see registerClientScript
78
     */
79
    public $handleSubmit = true;
80
81
    public function getActionUrl()
82
    {
83
        return $this->_actionUrl ? Url::to($this->_actionUrl) : Url::to($this->scenario);
84
    }
85
86
    public function setActionUrl($url)
87
    {
88
        $this->_actionUrl = $url;
89
    }
90
91
    public function getModalFormId()
92
    {
93
        return $this->_modalFormId ?: $this->scenario . '-form';
94
    }
95
96
    public function setModalFormId($id)
97
    {
98
        $this->_modalFormId = $id;
99
    }
100
101
    public function getErrorText()
102
    {
103
        return $this->_errorText ?: Yii::t('hipanel', 'An error occurred. Try again please.');
104
    }
105
106
    public function setErrorText($text)
107
    {
108
        $this->_errorText = Yii::t('hipanel', $text);
109
    }
110
111
    public function getSuccessText()
112
    {
113
        return $this->_successText ?: Yii::t('hipanel', 'Settings saved');
114
    }
115
116
    public function setSuccessText($text)
117
    {
118
        $this->_successText = Yii::t('hipanel', $text);
119
    }
120
121
    public function getLoadingText()
122
    {
123
        return $this->_loadingText ?: Yii::t('hipanel', 'loading') . '...';
124
    }
125
126
    public function setLoadingText($text)
127
    {
128
        $this->_loadingText = Yii::t('hipanel', $text);
129
    }
130
131
    public function init()
132
    {
133
        if (!$this->scenario) {
134
            throw new InvalidConfigException("Attribute 'scenario' is required");
135
        }
136
137
        Html::addCssClass($this->options['class'], 'text-left');
138
        $this->options['tabindex'] = false;
139
140
        $this->initAdditionalOptions();
141
        if ($this->handleSubmit !== false) {
142
            $this->registerClientScript();
143
        }
144
        parent::init();
145
    }
146
147
    protected function initAdditionalOptions()
148
    {
149
        $quotedHtml = Json::htmlEncode($this->loadingHtml);
0 ignored issues
show
Documentation introduced by
The property loadingHtml does not exist on object<hipanel\widgets\AjaxModal>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
150
        if (!isset($this->clientEvents['show.bs.modal'])) {
151
            if ($this->bulkPage) {
152 View Code Duplication
                if ($this->usePost) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
153
                    $this->clientEvents['show.bs.modal'] = new JsExpression("function(e) {
154
                        if (e.namespace !== 'bs.modal') return true;
155
                        var selection = jQuery('div[role=\"grid\"]').yiiGridView('getSelectedRows');
156
                        $.post('{$this->actionUrl}', {selection: selection}).done(function (data) {
0 ignored issues
show
Bug introduced by
The property actionUrl does not seem to exist. Did you mean _actionUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
157
                            $('#{$this->id} .modal-body').html(data);
158
                        });
159
                    }");
160
                } else {
161
                    $this->clientEvents['show.bs.modal'] = new JsExpression("function(e) {
162
                        if (e.namespace !== 'bs.modal') return true;
163
                        var selection = jQuery('div[role=\"grid\"]').yiiGridView('getSelectedRows');
164
                        $.get('{$this->actionUrl}', {selection: selection}).done(function (data) {
0 ignored issues
show
Bug introduced by
The property actionUrl does not seem to exist. Did you mean _actionUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
165
                            $('#{$this->id} .modal-body').html(data);
166
                        });
167
                    }");
168
                }
169 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
170
                if ($this->usePost) {
171
                    $this->clientEvents['show.bs.modal'] = new JsExpression("function(e) {
172
                        if (e.namespace !== 'bs.modal') return true;
173
                        $.post('{$this->actionUrl}').done(function (data) {
0 ignored issues
show
Bug introduced by
The property actionUrl does not seem to exist. Did you mean _actionUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
174
                            $('#{$this->id} .modal-body').html(data);
175
                        });
176
                    }");
177
                } else {
178
                    $this->clientEvents['show.bs.modal'] = new JsExpression("function(e) {
179
                        if (e.namespace !== 'bs.modal') return true;
180
                        $.get('{$this->actionUrl}').done(function (data) {
0 ignored issues
show
Bug introduced by
The property actionUrl does not seem to exist. Did you mean _actionUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
181
                            $('#{$this->id} .modal-body').html(data);
182
                        });
183
                    }");
184
                }
185
            }
186
        }
187
        if (!isset($this->clientEvents['hidden.bs.modal'])) {
188
            $this->clientEvents['hidden.bs.modal'] = new JsExpression("function() {
189
                jQuery('#{$this->id} .modal-body').html({$quotedHtml});
190
            }");
191
        }
192
    }
193
194
    protected function registerClientScript()
195
    {
196
        $url = is_string($this->handleSubmit) ? $this->handleSubmit : $this->actionUrl;
0 ignored issues
show
Bug introduced by
The property actionUrl does not seem to exist. Did you mean _actionUrl?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
197
        Yii::$app->view->registerJs(<<<JS
198
            jQuery(document).on('submit', '#{$this->modalFormId}', function(event) {
0 ignored issues
show
Bug introduced by
The property modalFormId does not seem to exist. Did you mean _modalFormId?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
199
                event.preventDefault();
200
                var form = jQuery(this);
201
                var btn = jQuery('#{$this->modalFormId} button[type="submit"]').button('{$this->loadingText}');
0 ignored issues
show
Bug introduced by
The property modalFormId does not seem to exist. Did you mean _modalFormId?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The property loadingText does not seem to exist. Did you mean _loadingText?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
202
                jQuery.ajax({
203
                    url: '$url',
204
                    type: 'POST',
205
                    timeout: 0,
206
                    data: form.serialize(),
207
                    error: function(xhr) {
208
                        if (xhr.status > 300 && xhr.status < 400) {
209
                            return; // redirects should not be handled in any manner
210
                        }
211
212
                        form.parent().html(xhr.responseText);
213
                        hipanel.notify.error(xhr.statusText ? xhr.statusText : "{$this->errorText}")
0 ignored issues
show
Bug introduced by
The property errorText does not seem to exist. Did you mean _errorText?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
214
                    },
215
                    success: function() {
216
                        jQuery('#$this->id').modal('hide');
217
                        hipanel.notify.success('{$this->successText}')
0 ignored issues
show
Bug introduced by
The property successText does not seem to exist. Did you mean _successText?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
218
                        btn.button('reset');
219
                    }
220
                });
221
            });
222
JS
223
        );
224
    }
225
226
    public function getLoadingHtml()
227
    {
228
        return <<<HTML
229
        <div class="progress">
230
            <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
231
                <span class="sr-only">{$this->loadingText}</span>
0 ignored issues
show
Bug introduced by
The property loadingText does not seem to exist. Did you mean _loadingText?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
232
            </div>
233
        </div>
234
HTML;
235
    }
236
237
    /**
238
     * {@inheritdoc}
239
     */
240
    protected function renderBodyBegin()
241
    {
242
        return Html::beginTag('div', [
243
            'class' => 'modal-body',
244
            'data-action-url' => $this->getActionUrl(),
245
        ]) . $this->loadingHtml;
0 ignored issues
show
Documentation introduced by
The property loadingHtml does not exist on object<hipanel\widgets\AjaxModal>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
246
    }
247
248
    /**
249
     * {@inheritdoc}
250
     */
251
    protected function registerClientEvents()
252
    {
253
        if (!empty($this->clientEvents)) {
254
            foreach ($this->clientEvents as $event => $handler) {
255
                if ($handler instanceof \Closure) {
256
                    $this->clientEvents[$event] = call_user_func($handler, $this);
257
                }
258
            }
259
        }
260
261
        parent::registerClientEvents();
262
    }
263
}
264