_coreCrudController::submission()   C
last analyzed

Complexity

Conditions 11
Paths 21

Size

Total Lines 94
Code Lines 50

Duplication

Lines 3
Ratio 3.19 %

Importance

Changes 0
Metric Value
cc 11
eloc 50
nc 21
nop 2
dl 3
loc 94
rs 5.2653
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Default to extend Ajde_Acl_Controller for enhanced security.
5
 */
6
class _coreCrudController extends Ajde_Acl_Controller
7
{
8
    /************************
9
     * Ajde_Component_Crud
10
     ************************/
11
12
    public function beforeInvoke($allowed = [])
13
    {
14
        // disable cache and auto translations
15
        Ajde_Cache::getInstance()->disable();
16
        Ajde_Lang::getInstance()->disableAutoTranslationOfModels();
17
18
        // try to get the crud instance
19
        $crud = $this->hasCrudInstance() ? $this->getCrudInstance() : false;
0 ignored issues
show
Documentation Bug introduced by
The method hasCrudInstance does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
Documentation Bug introduced by
The method getCrudInstance does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
20
        if (!$crud && Ajde::app()->getRequest()->has('crudId')) {
21
            $session = new Ajde_Session('AC.Crud');
22
            $crud = $session->getModel(Ajde::app()->getRequest()->getParam('crudId'));
23
        }
24
        if ($crud) {
25
            /* @var $crud Ajde_Crud */
26
            $this->setAclParam($crud->getSessionName());
27
        }
28
29
        return parent::beforeInvoke();
30
    }
31
32
    public function listHtml()
33
    {
34
        if (Ajde::app()->getRequest()->has('edit') || Ajde::app()->getRequest()->has('new')) {
35
            return $this->editDefault();
36
        }
37
38
        if (Ajde::app()->getRequest()->has('output') && Ajde::app()->getRequest()->get('output') == 'table') {
39
            Ajde::app()->getDocument()->setLayout(new Ajde_Layout('empty'));
40
        }
41
42
        $crud = $this->getCrudInstance();
0 ignored issues
show
Documentation Bug introduced by
The method getCrudInstance does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
43
        /* @var $crud Ajde_Crud */
44
        if (!$crud) {
45
            Ajde::app()->getResponse()->redirectNotFound();
46
        }
47
48
        $session = new Ajde_Session('AC.Crud');
49
        $session->setModel($crud->getHash(), $crud);
50
51
        // just preload it
52
        $crud->getCollectionView();
53
54
        if (Ajde::app()->getRequest()->has('output') && Ajde::app()->getRequest()->get('output') == 'excel') {
55
            $url = '_core/crud:exportBuffer';
56
57
            $exporter = $crud->export('excel');
58
59
            $exportSession = new Ajde_Session('export');
60
            $exportSession->setModel('exporter', $exporter);
61
62
            $this->redirect($url);
63
64
            return false;
65
        }
66
67
        $view = $crud->getTemplate();
68
        $view->assign('crud', $crud);
69
70
        return $view->render();
71
    }
72
73
    public function revisionsHtml()
74
    {
75
        $this->setAction('edit/revisions');
0 ignored issues
show
Documentation Bug introduced by
The method setAction does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
76
77
        $this->getView()->assign('revisions', $this->getRevisions());
0 ignored issues
show
Documentation Bug introduced by
The method getRevisions does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
78
        $this->getView()->assign('model', $this->getModel());
0 ignored issues
show
Documentation Bug introduced by
The method getModel does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
79
        $this->getView()->assign('crud', $this->getCrudInstance());
0 ignored issues
show
Documentation Bug introduced by
The method getCrudInstance does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
80
81
        return $this->render();
82
    }
83
84
    public function exportBuffer()
85
    {
86
        $exportSession = new Ajde_Session('export');
87
88
        $exporter = $exportSession->getModel('exporter');
89
        /* @var $exporter Ajde_Crud_Export_Interface */
90
        echo $exporter->send();
91
        exit;
92
    }
93
94
    public function editDefault()
95
    {
96
        $this->setAction('edit');
0 ignored issues
show
Documentation Bug introduced by
The method setAction does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
97
98
        $crud = $this->getCrudInstance();
0 ignored issues
show
Documentation Bug introduced by
The method getCrudInstance does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
99
        /* @var $crud Ajde_Crud */
100
        if (!$crud) {
101
            Ajde::app()->getResponse()->redirectNotFound();
102
        }
103
104
        $editOptions = $crud->getOptions('edit');
105
        if ($crud->getOperation() === 'list') {
106
            if (!empty($editOptions) &&
107
                isset($editOptions['action'])
108
            ) {
109
                $crud->setAction($editOptions['action']);
110
            } else {
111
                if ($crud->getOption('edit.layout')) {
112
                    $crud->setAction('edit/layout');
113
                } else {
114
                    // Automatically switch to layouts now
115
                    //					$crud->setAction('edit');
116
117
                    // Insert layout and set action
118
                    $show = $crud->getOption('edit.show');
119
                    $editOptions = new Ajde_Crud_Options_Edit();
120
                    $editOptions->selectLayout()->addRow()->addColumn()->setSpan(12)->addBlock()->setShow($show)->finished();
0 ignored issues
show
Bug introduced by
It seems like $show defined by $crud->getOption('edit.show') on line 118 can also be of type boolean; however, Ajde_Crud_Options_Edit_L...Blocks_Block::setShow() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
121
                    $crud->setOption('edit', $editOptions->getArray());
122
                    $crud->setAction('edit/layout');
123
                }
124
            }
125
        }
126
127
        if (!$crud->hasId()) {
0 ignored issues
show
Documentation Bug introduced by
The method hasId does not exist on object<Ajde_Crud>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
128
            $crud->setId(Ajde::app()->getRequest()->getParam('edit', false));
0 ignored issues
show
Documentation Bug introduced by
The method setId does not exist on object<Ajde_Crud>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
129
        }
130
131
        // get view for crud instance, load from request, but do not persist
132
        $crudView = $crud->getCollectionView();
133
134
        // current mainfilter from view
135
        $mainFilter = $crudView->getMainFilter();
136
137
        if ($mainFilter) {
138
139
            // get current filter
140
            $currentFilter = $crudView->getFilterForField($mainFilter);
141
142
            // update mainfilter for new records
143
            if (Ajde::app()->getRequest()->has('new')) {
144
                $crud->setOption('fields.'.$mainFilter.'.value', $currentFilter);
145
            }
146
147
            // hide mainfilter fields
148
            $crud->setOption('fields.'.$mainFilter.'.hidden', true);
149
        }
150
151
        // Set prefilled, disabled and hidden fields from request
152
        $disable = Ajde::app()->getRequest()->getParam('disable', []);
153
        $hide = Ajde::app()->getRequest()->getParam('hide', []);
154
        $prefill = Ajde::app()->getRequest()->getParam('prefill', []);
155
        foreach ($prefill as $field => $value) {
156
            $crud->setOption('fields.'.$field.'.value', $value);
157
        }
158
        foreach ($disable as $field => $value) {
159
            if ($value) {
160
                $crud->setOption('fields.'.$field.'.readonly', true);
161
            }
162
        }
163
        foreach ($hide as $field => $value) {
164
            if ($value) {
165
                $crud->setOption('fields.'.$field.'.hidden', true);
166
            }
167
        }
168
169
        // Read only entire view?
170
        if ($crud->getOption('edit.readonly', false)) {
171
            $crud->setReadOnlyForAllFields();
172
        }
173
174
        // Reload Crud fields in case they were already loaded
175
        $crud->loadFields();
176
177
        $session = new Ajde_Session('AC.Crud');
178
        $session->setModel($crud->getHash(), $crud);
179
180
        $view = $crud->getTemplate();
181
182
        $view->requireJsFirst('component/shortcut', 'html', MODULE_DIR.'_core/');
0 ignored issues
show
Documentation Bug introduced by
The method requireJsFirst does not exist on object<Ajde_Template>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
183
        $view->assign('crud', $crud);
184
185
        // Editor
186
        if (config('layout.textEditor')) {
187
            $editorClassName = 'Ajde_Crud_Editor_'.ucfirst(config('layout.textEditor'));
188
            $textEditor = new $editorClassName();
189
            /* @var $textEditor Ajde_Crud_Editor */
190
            $textEditor->getResources($view);
191
        }
192
193
        return $view->render();
194
    }
195
196
    public function mainfilterHtml()
197
    {
198
        $crud = $this->getCrudInstance();
0 ignored issues
show
Documentation Bug introduced by
The method getCrudInstance does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
199
        $this->getView()->assign('crud', $crud);
200
        $this->getView()->assign('refresh', $this->getRefresh());
0 ignored issues
show
Documentation Bug introduced by
The method getRefresh does not exist on object<_coreCrudController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
201
202
        return $this->render();
203
    }
204
205
    public function commitJson()
206
    {
207
        $operation = Ajde::app()->getRequest()->getParam('operation');
208
        $crudId = Ajde::app()->getRequest()->getParam('crudId');
209
        $id = Ajde::app()->getRequest()->getPostParam('id', false);
210
        if (Ajde::app()->getRequest()->getPostParam('form_submission', false)) {
211
            $operation = 'submission';
212
        }
213
214
        switch ($operation) {
215
            case 'delete':
216
                return $this->delete($crudId, $id);
217
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
218
            case 'submission':
219
                return $this->submission($crudId, $id);
220
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
221
            case 'save':
222
                return $this->save($crudId, $id);
223
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
224
            case 'sort':
225
                return $this->sort($crudId, $id);
226
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
227
            case 'deleteMultiple':
228
                return $this->deleteMultiple($crudId, $id);
229
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
230
            case 'addMultiple':
231
                return $this->addMultiple($crudId, $id);
232
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
233
            case 'getMultipleRow':
234
                return $this->getMultipleRow($crudId);
235
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
236
            case 'purgeRevisions':
237
                return $this->purgeRevisions($crudId);
238
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
239
            default:
240
                return ['operation' => $operation, 'success' => false];
241
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
242
        }
243
    }
244
245
    private function delete($crudId, $id)
246
    {
247
        $session = new Ajde_Session('AC.Crud');
248
        $crud = $session->getModel($crudId);
249
        $model = $crud->getModel();
250
251
        if (!is_array($id)) {
252
            $id = [$id];
253
        }
254
255
        $success = true;
256
        $deleted = 0;
257
        foreach ($id as $elm) {
258
            $model->loadByPK($elm);
259
            if ($result = $model->delete()) {
260
                $deleted++;
261
            }
262
            $success = $success * $result;
263
        }
264
265
        return [
266
            'operation' => 'delete',
267
            'success'   => (bool) $success,
268
            'message'   => Ajde_Component_String::makePlural($deleted, 'record').' deleted',
269
        ];
270
    }
271
272
    private function sort($crudId, $id)
273
    {
274
        $session = new Ajde_Session('AC.Crud');
275
        /* @var $crud Ajde_Crud */
276
        $crud = $session->getModel($crudId);
277
        $model = $crud->getModel();
278
279
        // Extra careful handling of parameters, as we are baking crude SQL here
280
281
        if (Ajde::app()->getRequest()->hasPostParam('table')) {
282
283
            // Only allow alfanumeric, ., _ and - in table and field names
284
            $sortField = preg_replace("/[^0-9a-zA-Z_\-\.]/i", '', Ajde::app()->getRequest()->getPostParam('field'));
285
            $sortPK = preg_replace("/[^0-9a-zA-Z_\-\.]/i", '', Ajde::app()->getRequest()->getPostParam('pk'));
286
            $sortTable = preg_replace("/[^0-9a-zA-Z_\-\.]/i", '', Ajde::app()->getRequest()->getPostParam('table'));
287
288
            if (!is_array($id)) {
289
                $id = [$id];
290
            }
291
292
            // Make sure ids is a array of integers
293
            $ids = [];
294
            foreach ($id as $elm) {
295
                if ($elm) {
296
                    $ids[] = (int) $elm;
297
                }
298
            }
299
300
            // Get lowest current sort values
301
            $idString = implode(', ', $ids);
302
            $sql = 'SELECT MIN('.$sortField.') AS min FROM '.$sortTable.' WHERE '.$sortPK.' IN ('.$idString.')';
303
304
            $statement = $model->getConnection()->prepare($sql);
305
            $statement->execute();
306
            $result = $statement->fetch(PDO::FETCH_ASSOC);
307 View Code Duplication
            if ($result === false || empty($result)) {
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...
308
                $sortValue = 0;
309
            } else {
310
                $sortValue = $result['min'];
311
            }
312
313
            $success = true;
314
            foreach ($ids as $id) {
315
                $values = [$sortValue, $id];
316
                $sql = 'UPDATE '.$sortTable.' SET '.$sortField.' = ? WHERE '.$sortPK.' = ?';
317
318
                $statement = $model->getConnection()->prepare($sql);
319
                $success = $success * $statement->execute($values);
320
                $sortValue++;
321
            }
322
        } else {
323
            // Get and validate sort field
324
            $sortField = Ajde::app()->getRequest()->getPostParam('field');
325
            $sortTable = (string) $model->getTable();
326
            $field = $crud->getField($sortField); // throws exception when not found
327
328
            if (!is_array($id)) {
329
                $id = [$id];
330
            }
331
332
            // Make sure ids is a array of integers
333
            $ids = [];
334
            foreach ($id as $elm) {
335
                if (!empty($elm)) {
336
                    $ids[] = (int) $elm;
337
                }
338
            }
339
340
            // Get lowest current sort values
341
            $idString = implode(', ', $ids);
342
            $sql = 'SELECT MIN('.$sortField.') AS min FROM '.$sortTable.' WHERE '.$model->getTable()->getPK().' IN ('.$idString.')';
343
344
            $statement = $model->getConnection()->prepare($sql);
345
            $statement->execute();
346
            $result = $statement->fetch(PDO::FETCH_ASSOC);
347 View Code Duplication
            if ($result === false || empty($result)) {
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...
348
                $sortValue = 0;
349
            } else {
350
                $sortValue = $result['min'];
351
            }
352
353
            $success = true;
354
            foreach ($ids as $id) {
355
                $model->loadByPK($id);
356
                $model->set($sortField, $sortValue);
357
                // don't update fields with name 'updated'
358
                $model->set('updated', new Ajde_Db_Function('updated'));
359
                $success = $success * $model->save();
360
                $sortValue++;
361
                if ($field->has('sort_children')) {
362
                    // TODO: implement parent recursive sorting
363
                }
364
            }
365
366
            // Call afterSort once on model
367
            if (method_exists($model, 'afterSort')) {
368
                $model->afterSort();
0 ignored issues
show
Documentation Bug introduced by
The method afterSort does not exist on object<Ajde_Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
369
            }
370
        }
371
372
        return [
373
            'operation' => 'sort',
374
            'success'   => (bool) $success,
375
            'message'   => 'Records sorted',
376
        ];
377
    }
378
379
    private function save($crudId, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
380
    {
381
        $session = new Ajde_Session('AC.Crud');
382
383
        /* @var $crud Ajde_Crud */
384
        $crud = $session->getModel($crudId);
385
386
        // verify that we have a valid crud model
387
        if (!$crud) {
388
            return ['success' => false];
389
        }
390
391
        /* @var $model Ajde_Model */
392
        $model = $crud->getModel();
393
        $model->setOptions($crud->getOptions('model'));
0 ignored issues
show
Documentation Bug introduced by
The method setOptions does not exist on object<Ajde_Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
394
395
        // Get POST params
396
        $post = Ajde_Http_Request::globalPost();
397
        foreach ($post as $key => $value) {
398
            // Include empty values, so we can set them to null if the table structure allows us
399
            //			if (empty($value)) {
400
            //				unset($post[$key]);
401
            //			}
402
        }
403
        $id = issetor($post['id']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $id is correct as issetor($post['id']) (which targets issetor()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
404
        $operation = empty($id) ? 'insert' : 'save';
405
406
        if ($operation === 'save') {
407
            $model->loadByPK($id);
408
        }
409
        $model->populate($post);
410
411
        Ajde_Event::trigger($model, 'beforeCrudSave', [$crud]);
412
413 View Code Duplication
        if (!$model->validate($crud->getOptions('fields'))) {
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...
414
            return ['operation' => $operation, 'success' => false, 'errors' => $model->getValidationErrors()];
415
        }
416
        //		if (!$model->autocorrect($crud->getOptions('fields'))) {
417
        //			return array('operation' => $operation, 'success' => false, 'errors' => $model->getAutocorrectErrors());
418
        //		}
419
420
        $success = $model->{$operation}();
421
422
        Ajde_Event::trigger($model, 'afterCrudSave', [$crud]);
423
424
        // Multiple field SimpleSelector
425
        foreach ($crud->getOption('fields') as $key => $field) {
0 ignored issues
show
Bug introduced by
The expression $crud->getOption('fields') of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
426
            if (isset($field['crossReferenceTable']) && isset($field['simpleSelector']) && $field['simpleSelector'] === true) {
427
                $this->deleteMultiple($crud, null, $model->getPK(), $key, true);
428
                if (isset($post[$key]) && is_array($post[$key])) {
429
                    foreach ($post[$key] as $item) {
430
                        $this->addMultiple($crud, $item, $model->getPK(), $key);
431
                    }
432
                }
433
            }
434
        }
435
436
        if ($success === true) {
437
            if (Ajde::app()->getRequest()->getParam('fromAutoSave', '0') != 1) {
438
439
                // Destroy reference to crud instance
440
                $session->destroy($crudId);
441
442
                if (Ajde::app()->getRequest()->getParam('fromIframe', '0') != 1) {
443
                    // Set flash alert
444
                    Ajde_Session_Flash::alert('Record '.($operation == 'insert' ? 'added' : 'saved').': '.$model->get($model->getDisplayField()));
445
                }
446
            }
447
        }
448
449
        return [
450
            'operation'    => $operation,
451
            'id'           => $model->getPK(),
452
            'displayField' => $model->get($model->getDisplayField()),
453
            'success'      => $success,
454
        ];
455
    }
456
457
    private function submission($crudId, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
458
    {
459
        $session = new Ajde_Session('AC.Crud');
460
461
        /* @var $crud Ajde_Crud */
462
        $crud = $session->getModel($crudId);
463
464
        // verify that we have a valid crud model
465
        if (!$crud) {
466
            return ['success' => false];
467
        }
468
469
        /* @var $model FormModel */
470
        $model = $crud->getModel();
471
        $model->setOptions($crud->getOptions('model'));
0 ignored issues
show
Documentation Bug introduced by
The method setOptions does not exist on object<FormModel>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
472
473
        // Get POST params
474
        $post = Ajde_Http_Request::globalPost();
475
        $id = issetor($post['id']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $id is correct as issetor($post['id']) (which targets issetor()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
476
477
        // verify that we have a valid form model
478
        if (!$id) {
479
            return ['success' => false];
480
        }
481
482
        // load form
483
        $model->loadByPK($id);
484
        $model->populate($post);
485
486
        // validate form
487
        Ajde_Event::trigger($model, 'beforeCrudSave', [$crud]);
488 View Code Duplication
        if (!$model->validate($crud->getOptions('fields'))) {
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...
489
            return ['operation' => 'save', 'success' => false, 'errors' => $model->getValidationErrors()];
490
        }
491
492
        // prepare submission
493
        $values = [];
494
        foreach ($post as $key => $value) {
495
            if (substr($key, 0, 5) === 'meta_') {
496
                $metaId = str_replace('meta_', '', $key);
497
                $metaName = MetaModel::getNameFromId($metaId);
498
                $values[$metaName] = $value;
499
            }
500
        }
501
502
        $entryText = '';
503
        foreach ($values as $k => $v) {
504
            $entryText .= $k.': '.$v.PHP_EOL;
505
        }
506
507
        $submission = new SubmissionModel();
508
        $submission->form = $id;
0 ignored issues
show
Documentation introduced by
The property form does not exist on object<SubmissionModel>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
509
        $submission->ip = $_SERVER['REMOTE_ADDR'];
0 ignored issues
show
Documentation introduced by
The property ip does not exist on object<SubmissionModel>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
510
        $submission->user = Ajde_User::getLoggedIn();
0 ignored issues
show
Documentation introduced by
The property user does not exist on object<SubmissionModel>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
511
        $submission->entry = json_encode($values);
0 ignored issues
show
Documentation introduced by
The property entry does not exist on object<SubmissionModel>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
512
        $submission->entry_text = $entryText;
0 ignored issues
show
Documentation introduced by
The property entry_text does not exist on object<SubmissionModel>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
513
514
        $success = $submission->insert();
515
516
        if ($success === true) {
517
518
            // Destroy reference to crud instance
519
            $session->destroy($crudId);
520
521
            // set message for next page
522
            Ajde_Session_Flash::alert(trans('Form submitted successfully'));
523
524
            $mailer = new Ajde_Mailer();
525
526
            // send email to administrator
527
            $body = 'Form: '.$model->displayField().'<br/><br/>'.nl2br($entryText);
528
            $mailer->SendQuickMail(config('app.email'), config('app.email'), config('app.title'),
529
                'New form submission', $body);
530
531
            // send email to user
532
            $email = $model->getEmail();
533
            /* @var $email EmailModel */
534
            $email_to = $model->getEmailTo();
535
            /* @var $email MetaModel */
536
            $email_address = issetor($post['meta_'.$email_to->getPK()]);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $email_address is correct as issetor($post['meta_' . $email_to->getPK()]) (which targets issetor()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
537
            if ($email->hasLoaded() && $email_to->hasLoaded() && $email_address) {
538
                $mailer->sendUsingModel($email->getIdentifier(), $email_address, $email_address, [
0 ignored issues
show
Documentation Bug introduced by
The method getIdentifier does not exist on object<MetaModel>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
539
                    'entry' => nl2br($entryText),
540
                ]);
541
            }
542
        }
543
544
        return [
545
            'operation'    => 'save',
546
            'id'           => $model->getPK(),
547
            'displayField' => $model->get($model->getDisplayField()),
548
            'success'      => $success,
549
        ];
550
    }
551
552
    private function deleteMultiple($crudId, $id, $parentId = null, $fieldName = null, $all = false)
553
    {
554
        /* @var $crud Ajde_Crud */
555 View Code Duplication
        if ($crudId instanceof Ajde_Crud) {
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...
556
            $crud = $crudId;
557
        } else {
558
            $session = new Ajde_Session('AC.Crud');
559
            $crud = $session->getModel($crudId);
560
        }
561
562
        /* @var $model Ajde_Model */
563
        $model = $crud->getModel();
564
565
        $parentId = isset($parentId) ? $parentId : Ajde::app()->getRequest()->getPostParam('parent_id');
566
        $fieldName = isset($fieldName) ? $fieldName : Ajde::app()->getRequest()->getPostParam('field');
567
568
        // Get field properties
569
        $fieldProperties = $crud->getOption('fields.'.$fieldName);
570
571
        $success = false;
0 ignored issues
show
Unused Code introduced by
$success is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
572
        $modelName = $crud->getOption('fields.'.$fieldName.'.modelName', $fieldName);
573
        if (isset($fieldProperties['crossReferenceTable'])) {
574
            if ($all === true) {
575
                $parentField = (string) $model->getTable();
576
                $sql = 'DELETE FROM '.$fieldProperties['crossReferenceTable'].' WHERE '.$parentField.' = ?';
577
                $values = [$parentId];
578
579
                // Setup constraints
580 View Code Duplication
                if (isset($fieldProperties['crossRefConstraints'])) {
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...
581
                    foreach ($fieldProperties['crossRefConstraints'] as $k => $v) {
582
                        $sql .= ' AND '.$k.' = ?';
583
                        $values[] = $v;
584
                    }
585
                }
586
587
                $statement = $model->getConnection()->prepare($sql);
588
                $success = $statement->execute($values);
589
            } else {
590
                $childField = isset($fieldProperties['childField']) ? $fieldProperties['childField'] : $modelName;
591
                $parentField = (string) $model->getTable();
592
                $sql = 'DELETE FROM '.$fieldProperties['crossReferenceTable'].' WHERE '.$parentField.' = ? AND '.$childField.' = ?';
593
                $values = [$parentId, $id];
594
595
                // Setup constraints
596 View Code Duplication
                if (isset($fieldProperties['crossRefConstraints'])) {
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...
597
                    foreach ($fieldProperties['crossRefConstraints'] as $k => $v) {
598
                        $sql .= ' AND '.$k.' = ?';
599
                        $values[] = $v;
600
                    }
601
                }
602
603
                $sql .= ' LIMIT 1';
604
                $statement = $model->getConnection()->prepare($sql);
605
                $success = $statement->execute($values);
606
            }
607
        } else {
608
            $childClass = ucfirst($modelName).'Model';
609
            $child = new $childClass();
610
            /* @var $child Ajde_Model */
611
            $child->loadByPK($id);
612
            $success = $child->delete();
613
        }
614
615
        return [
616
            'operation' => 'deleteMultiple',
617
            'success'   => $success,
618
            'message'   => ucfirst($modelName).(isset($fieldProperties['crossReferenceTable']) ? ' disconnected' : ' deleted'),
619
        ];
620
    }
621
622
    private function addMultiple($crudId, $id, $parentId = null, $fieldName = null)
623
    {
624
        /* @var $crud Ajde_Crud */
625 View Code Duplication
        if ($crudId instanceof Ajde_Crud) {
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...
626
            $crud = $crudId;
627
        } else {
628
            $session = new Ajde_Session('AC.Crud');
629
            $crud = $session->getModel($crudId);
630
        }
631
632
        /* @var $model Ajde_Model */
633
        $model = $crud->getModel();
634
635
        $parentId = isset($parentId) ? $parentId : Ajde::app()->getRequest()->getPostParam('parent_id');
636
        $fieldName = isset($fieldName) ? $fieldName : Ajde::app()->getRequest()->getPostParam('field');
637
638
        // Get field properties
639
        $fieldProperties = $crud->getOption('fields.'.$fieldName);
640
641
        $success = false;
642
        $modelName = $crud->getOption('fields.'.$fieldName.'.modelName', $fieldName);
643
        if (isset($fieldProperties['crossReferenceTable'])) {
644
            $childField = isset($fieldProperties['childField']) ? $fieldProperties['childField'] : $modelName;
645
646
            // Already in there?
647
            $parentField = (string) $model->getTable();
648
            $values = [$parentId, $id];
649
            $sql = 'SELECT * FROM '.$fieldProperties['crossReferenceTable'];
650
            $sql .= ' WHERE '.$parentField.' = ? AND '.$childField.' = ?';
651 View Code Duplication
            if (isset($fieldProperties['crossRefConstraints'])) {
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...
652
                foreach ($fieldProperties['crossRefConstraints'] as $k => $v) {
653
                    $sql .= ' AND '.$k.' = ?';
654
                    $values[] = $v;
655
                }
656
            }
657
            $sql .= ' LIMIT 1';
658
            $statement = $model->getConnection()->prepare($sql);
659
            $success = $statement->execute($values);
660
            $result = $statement->fetch(PDO::FETCH_ASSOC);
661
            if ($success === true && $result !== false && !empty($result)) {
662
                return [
663
                    'operation' => 'addMultiple',
664
                    'success'   => false,
665
                    'message'   => ucfirst($fieldName).' already connected',
666
                ];
667
            }
668
669
            // Sql to use when no sorting
670
            $fieldList = '';
671
            $valueList = '?, ?';
672
            $values = [$parentId, $id];
673
674
            // Sort fields?
675
            if (isset($fieldProperties['tableFields'])) {
676
                foreach ($fieldProperties['tableFields'] as $extraField) {
677
                    if ($extraField['type'] == 'sort') {
678
                        // Get highest current sort value
679
                        $sql = 'SELECT MAX('.$extraField['name'].') AS max FROM '.$fieldProperties['crossReferenceTable'];
680
681
                        $statement = $model->getConnection()->prepare($sql);
682
                        $statement->execute();
683
                        $result = $statement->fetch(PDO::FETCH_ASSOC);
684 View Code Duplication
                        if ($result === false || empty($result)) {
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...
685
                            $sortValue = 999;
686
                        } else {
687
                            $sortValue = $result['max'] + 1;
688
                        }
689
                        $fieldList .= ', '.$extraField['name'];
690
                        $valueList = '?, ?, ?';
691
                        $values[] = $sortValue;
692
                    }
693
                }
694
            }
695
696
            // Setup constraints
697 View Code Duplication
            if (isset($fieldProperties['crossRefConstraints'])) {
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...
698
                foreach ($fieldProperties['crossRefConstraints'] as $k => $v) {
699
                    $fieldList .= ', '.$k;
700
                    $valueList .= ', ?';
701
                    $values[] = $v;
702
                }
703
            }
704
705
            $sql = 'INSERT INTO '.$fieldProperties['crossReferenceTable'].' ('.$parentField.', '.$childField.$fieldList.') VALUES ('.$valueList.')';
706
            $statement = $model->getConnection()->prepare($sql);
707
            $success = $statement->execute($values);
708
            $lastId = $model->getConnection()->lastInsertId();
709
        } else {
710
            // Not possible
711
        }
712
713
        return [
714
            'operation' => 'addMultiple',
715
            'success'   => $success,
716
            'lastId'    => $lastId,
0 ignored issues
show
Bug introduced by
The variable $lastId does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
717
            'message'   => $success ? ucfirst($modelName).' added' : 'An error occured',
718
        ];
719
    }
720
721
    private function getMultipleRow($crudId)
722
    {
723
        $session = new Ajde_Session('AC.Crud');
724
        /* @var $crud Ajde_Crud */
725
        $crud = $session->getModel($crudId);
726
        /* @var $model Ajde_Model */
727
        $model = $crud->getModel();
0 ignored issues
show
Unused Code introduced by
$model is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
728
729
        // Get field properties
730
        $id = Ajde::app()->getRequest()->getParam('id');
731
        $fieldName = Ajde::app()->getRequest()->getParam('field');
732
        $fieldProperties = $crud->getOption('fields.'.$fieldName);
733
        $modelName = $crud->getOption('fields.'.$fieldName.'.modelName', $fieldName);
734
735
        // Get child model
736
        $className = ucfirst($modelName).'Model';
737
        $child = new $className();
738
        /* @var $child Ajde_Model */
739
        $child->loadByPK($id);
740
741
        $ret = [];
742
        if (isset($fieldProperties['tableFields'])) {
743
            foreach ($fieldProperties['tableFields'] as $extraField) {
744
                $value = $child->has($extraField['name']) ? $child->get($extraField['name']) : false;
745
                $type = $extraField['type'];
746
                $html = false;
747
                if ($type == 'file' && $value) {
748
                    $extension = pathinfo($value, PATHINFO_EXTENSION);
749
                    if ($isImage = in_array(strtolower($extension), ['jpg', 'jpeg', 'png', 'gif'])) {
0 ignored issues
show
Unused Code introduced by
$isImage is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
750
                        $thumbDim = isset($fieldProperties['thumbDim']) ? $fieldProperties['thumbDim'] : ['width'  => 75,
751
                                                                                                          'height' => 75,
752
                        ];
753
                        $html = "<a class='imagePreview img' title='".esc($value)."' href='".$extraField['saveDir'].$value."' target='_blank'>";
754
                        $image = new Ajde_Resource_Image($extraField['saveDir'].$value);
755
                        $image->setWidth($thumbDim['width']);
0 ignored issues
show
Documentation Bug introduced by
The method setWidth does not exist on object<Ajde_Resource_Image>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
756
                        $image->setHeight($thumbDim['height']);
0 ignored issues
show
Documentation Bug introduced by
The method setHeight does not exist on object<Ajde_Resource_Image>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
757
                        $image->setCrop(true);
0 ignored issues
show
Documentation Bug introduced by
The method setCrop does not exist on object<Ajde_Resource_Image>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
758
                        $html = $html."<img src='".$image->getLinkUrl()."' width='".$thumbDim['width']."' height='".$thumbDim['height']."' />";
759
                        $html = $html.'</a>';
760
                    } else {
761
                        $html = "<img class='icon' src='".Ajde_Resource_FileIcon::_($extension)."' />";
762
                        $html = $html." <a class='filePreview preview' href='".$extraField['saveDir'].$value."' target='_blank'>".$value.'</a>';
763
                    }
764
                } else {
765
                    if ($type == 'text') {
766
                        $html = $value;
767
                    }
768
                }
769
                if ($html) {
770
                    $ret[] = $html;
771
                }
772
            }
773
        }
774
775
        $success = true;
776
777
        return [
778
            'operation'    => 'getMultipleRow',
779
            'success'      => $success,
780
            'displayField' => $child->get($child->getDisplayField()),
781
            'data'         => $ret,
782
        ];
783
    }
784
785
    private function purgeRevisions($crudId)
786
    {
787
        $session = new Ajde_Session('AC.Crud');
788
        /* @var $crud Ajde_Crud */
789
        $crud = $session->getModel($crudId);
790
        /* @var $model Ajde_Model */
791
        $model = $crud->getModel();
792
793
        $success = $model->purgeRevisions();
0 ignored issues
show
Documentation Bug introduced by
The method purgeRevisions does not exist on object<Ajde_Model>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
794
795
        return [
796
            'operation' => 'purgeRevisions',
797
            'success'   => $success,
798
            'message'   => 'Revisions purged',
799
        ];
800
    }
801
}
802