Passed
Push — devel-3.0 ( 2fc71e...3e43d6 )
by Rubén
03:39
created

ItemPresetController::saveCreateAction()   A

Complexity

Conditions 4
Paths 14

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 19
nc 14
nop 0
dl 0
loc 29
rs 9.6333
c 0
b 0
f 0
1
<?php
2
/**
3
 * sysPass
4
 *
5
 * @author    nuxsmin
6
 * @link      https://syspass.org
7
 * @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
8
 *
9
 * This file is part of sysPass.
10
 *
11
 * sysPass is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation, either version 3 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * sysPass is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 *  along with sysPass.  If not, see <http://www.gnu.org/licenses/>.
23
 */
24
25
namespace SP\Modules\Web\Controllers;
26
27
use SP\Core\Acl\Acl;
28
use SP\Core\Events\Event;
29
use SP\Core\Events\EventMessage;
30
use SP\Core\Exceptions\ValidationException;
31
use SP\DataModel\ItemPresetData;
32
use SP\Http\JsonResponse;
33
use SP\Modules\Web\Controllers\Helpers\Grid\ItemPresetGrid;
34
use SP\Modules\Web\Controllers\Helpers\ItemPresetHelper;
35
use SP\Modules\Web\Controllers\Traits\ItemTrait;
36
use SP\Modules\Web\Controllers\Traits\JsonTrait;
37
use SP\Modules\Web\Forms\ItemsPresetForm;
38
use SP\Mvc\Controller\CrudControllerInterface;
39
use SP\Services\ItemPreset\ItemPresetInterface;
40
use SP\Services\ItemPreset\ItemPresetService;
41
use SP\Util\Filter;
42
43
/**
44
 * Class AccountDefaultPermissionController
45
 *
46
 * @package SP\Modules\Web\Controllers
47
 */
48
class ItemPresetController extends ControllerBase implements CrudControllerInterface
49
{
50
    use JsonTrait, ItemTrait;
0 ignored issues
show
introduced by
The trait SP\Modules\Web\Controllers\Traits\ItemTrait requires some properties which are not provided by SP\Modules\Web\Controllers\ItemPresetController: $data, $key
Loading history...
51
52
    /**
53
     * @var ItemPresetService
54
     */
55
    protected $itemPresetService;
56
57
    /**
58
     * View action
59
     *
60
     * @param $id
61
     *
62
     * @return bool
63
     */
64
    public function viewAction($id)
65
    {
66
        if (!$this->acl->checkUserAccess(Acl::ITEMPRESET_VIEW)) {
67
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('No tiene permisos para realizar esta operación'));
68
        }
69
70
        $this->view->assign('header', __('Ver Valor'));
71
        $this->view->assign('isView', true);
72
73
        try {
74
            $this->setViewData($id);
75
76
            $this->eventDispatcher->notifyEvent('show.itemPreset', new Event($this));
77
78
            return $this->returnJsonResponseData(['html' => $this->render()]);
79
        } catch (\Exception $e) {
80
            processException($e);
81
82
            return $this->returnJsonResponseException($e);
83
        }
84
    }
85
86
    /**
87
     * Sets view data for displaying permissions' data
88
     *
89
     * @param int    $id
90
     * @param string $type
91
     *
92
     * @throws \SP\Core\Exceptions\ConstraintException
93
     * @throws \SP\Core\Exceptions\NoSuchPropertyException
94
     * @throws \SP\Core\Exceptions\QueryException
95
     * @throws \SP\Repositories\NoSuchItemException
96
     */
97
    protected function setViewData(int $id = null, string $type = null)
98
    {
99
        $this->view->addTemplate('item_preset', 'itemshow');
100
101
        $itemPresetData = $id ? $this->itemPresetService->getById($id) : new ItemPresetData();
102
103
        $itemPresetHelper = $this->dic->get(ItemPresetHelper::class);
104
        $itemPresetHelper->setCommon($itemPresetData);
105
106
        if ($itemPresetData->getType() === null) {
0 ignored issues
show
introduced by
The condition $itemPresetData->getType() === null is always false.
Loading history...
107
            $itemPresetData->setType($type);
108
        }
109
110
        switch ($itemPresetData->getType()) {
111
            case ItemPresetInterface::ITEM_TYPE_ACCOUNT_PERMISSION:
112
                $itemPresetHelper->makeAccountPermissionView($itemPresetData);
113
                break;
114
            case ItemPresetInterface::ITEM_TYPE_ACCOUNT_PRIVATE:
115
                $itemPresetHelper->makeAccountPrivateView($itemPresetData);
116
                break;
117
        }
118
119
        $this->view->assign('preset', $itemPresetData);
120
        $this->view->assign('sk', $this->session->generateSecurityKey());
121
        $this->view->assign('nextAction', Acl::getActionRoute(Acl::ACCESS_MANAGE));
122
123
        if ($this->view->isView === true) {
0 ignored issues
show
introduced by
The condition $this->view->isView === true is always false.
Loading history...
Bug Best Practice introduced by
The property isView does not exist on SP\Mvc\View\Template. Since you implemented __get, consider adding a @property annotation.
Loading history...
124
            $this->view->assign('disabled', 'disabled');
125
            $this->view->assign('readonly', 'readonly');
126
        } else {
127
            $this->view->assign('disabled');
128
            $this->view->assign('readonly');
129
        }
130
    }
131
132
    /**
133
     * Search action
134
     *
135
     * @return bool
136
     * @throws \SP\Core\Exceptions\ConstraintException
137
     * @throws \SP\Core\Exceptions\QueryException
138
     */
139
    public function searchAction()
140
    {
141
        if (!$this->acl->checkUserAccess(Acl::ITEMPRESET_SEARCH)) {
142
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('No tiene permisos para realizar esta operación'));
143
        }
144
145
        $this->view->addTemplate('datagrid-table', 'grid');
146
        $this->view->assign('index', $this->request->analyzeInt('activetab', 0));
147
        $this->view->assign('data', $this->getSearchGrid());
148
149
        return $this->returnJsonResponseData(['html' => $this->render()]);
150
    }
151
152
    /**
153
     * getSearchGrid
154
     *
155
     * @return $this
156
     * @throws \SP\Core\Exceptions\ConstraintException
157
     * @throws \SP\Core\Exceptions\QueryException
158
     */
159
    protected function getSearchGrid()
160
    {
161
        $itemSearchData = $this->getSearchData($this->configData->getAccountCount(), $this->request);
162
163
        $grid = $this->dic->get(ItemPresetGrid::class);
164
165
        return $grid->updatePager(
166
            $grid->getGrid($this->itemPresetService->search($itemSearchData)),
167
            $itemSearchData
168
        );
169
    }
170
171
    /**
172
     * Create action
173
     */
174
    public function createAction()
175
    {
176
        if (!$this->acl->checkUserAccess(Acl::ITEMPRESET_CREATE)) {
177
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('No tiene permisos para realizar esta operación'));
178
        }
179
180
        $args = func_get_args();
181
        $type = null;
182
183
        if (count($args) > 0) {
184
            $type = Filter::getString($args[0]);
185
        }
186
187
        $this->view->assign(__FUNCTION__, 1);
188
        $this->view->assign('header', __('Nuevo Valor'));
189
        $this->view->assign('isView', false);
190
        $this->view->assign('route', 'itemPreset/saveCreate');
191
192
        try {
193
            $this->setViewData(null, $type);
194
195
            $this->eventDispatcher->notifyEvent('show.itemPreset.create', new Event($this));
196
197
            return $this->returnJsonResponseData(['html' => $this->render()]);
198
        } catch (\Exception $e) {
199
            processException($e);
200
201
            return $this->returnJsonResponseException($e);
202
        }
203
    }
204
205
    /**
206
     * Edit action
207
     *
208
     * @param $id
209
     *
210
     * @return bool
211
     */
212
    public function editAction($id)
213
    {
214
        if (!$this->acl->checkUserAccess(Acl::ITEMPRESET_EDIT)) {
215
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('No tiene permisos para realizar esta operación'));
216
        }
217
218
        $this->view->assign('header', __('Editar Valor'));
219
        $this->view->assign('isView', false);
220
        $this->view->assign('route', 'itemPreset/saveEdit/' . $id);
221
222
        try {
223
            $this->setViewData($id);
224
225
            $this->eventDispatcher->notifyEvent('show.itemPreset.edit', new Event($this));
226
227
            return $this->returnJsonResponseData(['html' => $this->render()]);
228
        } catch (\Exception $e) {
229
            processException($e);
230
231
            return $this->returnJsonResponseException($e);
232
        }
233
    }
234
235
    /**
236
     * Delete action
237
     *
238
     * @param $id
239
     *
240
     * @return bool
241
     */
242
    public function deleteAction($id = null)
243
    {
244
        if (!$this->acl->checkUserAccess(Acl::ITEMPRESET_DELETE)) {
245
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('No tiene permisos para realizar esta operación'));
246
        }
247
248
        try {
249
            if ($id === null) {
250
                $this->itemPresetService->deleteByIdBatch($this->getItemsIdFromRequest($this->request));
251
252
                $this->eventDispatcher->notifyEvent('delete.itemPreset',
253
                    new Event($this,
254
                        EventMessage::factory()
255
                            ->addDescription(__u('Valores eliminados')))
256
                );
257
258
                return $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Valores eliminados'));
259
            }
260
261
            $this->itemPresetService->delete($id);
262
263
            $this->eventDispatcher->notifyEvent('delete.itemPreset',
264
                new Event($this,
265
                    EventMessage::factory()
266
                        ->addDescription(__u('Valor eliminado'))
267
                        ->addDetail(__u('ID'), $id))
268
            );
269
270
            return $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Valor eliminado'));
271
        } catch (\Exception $e) {
272
            processException($e);
273
274
            return $this->returnJsonResponseException($e);
275
        }
276
    }
277
278
    /**
279
     * Saves create action
280
     */
281
    public function saveCreateAction()
282
    {
283
        if (!$this->acl->checkUserAccess(Acl::ITEMPRESET_CREATE)) {
284
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('No tiene permisos para realizar esta operación'));
285
        }
286
287
        try {
288
            $form = new ItemsPresetForm($this->dic);
289
            $form->validate(Acl::ITEMPRESET_CREATE);
290
291
            $itemData = $form->getItemData();
292
293
            $id = $this->itemPresetService->create($itemData);
294
295
            $this->eventDispatcher->notifyEvent('create.itemPreset',
296
                new Event($this,
297
                    EventMessage::factory()
298
                        ->addDescription(__u('Valor creado'))
299
                        ->addDetail(__u('Tipo'), $itemData->getItemPresetData()->getType())
300
                        ->addDetail(__u('ID'), $id))
301
            );
302
303
            return $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Valor creado'));
304
        } catch (ValidationException $e) {
305
            return $this->returnJsonResponseException($e);
306
        } catch (\Exception $e) {
307
            processException($e);
308
309
            return $this->returnJsonResponseException($e);
310
        }
311
    }
312
313
    /**
314
     * Saves edit action
315
     *
316
     * @param $id
317
     *
318
     * @return bool
319
     */
320
    public function saveEditAction($id)
321
    {
322
        if (!$this->acl->checkUserAccess(Acl::ITEMPRESET_EDIT)) {
323
            return $this->returnJsonResponse(JsonResponse::JSON_ERROR, __u('No tiene permisos para realizar esta operación'));
324
        }
325
326
        try {
327
            $form = new ItemsPresetForm($this->dic, $id);
328
            $form->validate(Acl::ITEMPRESET_EDIT);
329
330
            $itemData = $form->getItemData();
331
332
            $this->itemPresetService->update($itemData);
333
334
            $this->eventDispatcher->notifyEvent('edit.itemPreset',
335
                new Event($this,
336
                    EventMessage::factory()
337
                        ->addDescription(__u('Valor actualizado'))
338
                        ->addDetail(__u('Tipo'), $itemData->getItemPresetData()->getType())
339
                        ->addDetail(__u('ID'), $id))
340
            );
341
342
            return $this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Valor actualizado'));
343
        } catch (ValidationException $e) {
344
            return $this->returnJsonResponseException($e);
345
        } catch (\Exception $e) {
346
            processException($e);
347
348
            return $this->returnJsonResponseException($e);
349
        }
350
    }
351
352
    /**
353
     * Initialize class
354
     *
355
     * @throws \Psr\Container\ContainerExceptionInterface
356
     * @throws \Psr\Container\NotFoundExceptionInterface
357
     * @throws \SP\Services\Auth\AuthException
358
     */
359
    protected function initialize()
360
    {
361
        $this->checkLoggedIn();
362
363
        $this->itemPresetService = $this->dic->get(ItemPresetService::class);
364
    }
365
}