Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17002 | Rev 17253 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
17002 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
7
use Laminas\Db\Adapter\AdapterInterface;
8
 
9
 
10
use Laminas\Mvc\Controller\AbstractActionController;
11
use Laminas\Log\LoggerInterface;
12
 
13
use Laminas\View\Model\ViewModel;
14
use Laminas\View\Model\JsonModel;
15
use LeadersLinked\Library\Functions;
16
use LeadersLinked\Mapper\MediaCategoryMapper;
17
use LeadersLinked\Form\Media\CategoryForm;
18
use LeadersLinked\Model\MediaCategory;
19
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
20
 
21
 
22
class MediaCategoryController extends AbstractActionController
23
{
24
    /**
25
     *
26
     * @var \Laminas\Db\Adapter\AdapterInterface
27
     */
28
    private $adapter;
17251 ariadna 29
 
17002 efrain 30
    /**
31
     *
32
     * @var \LeadersLinked\Cache\CacheInterface
33
     */
34
    private $cache;
17251 ariadna 35
 
36
 
17002 efrain 37
    /**
38
     *
39
     * @var \Laminas\Log\LoggerInterface
40
     */
41
    private $logger;
17251 ariadna 42
 
17002 efrain 43
    /**
44
     *
45
     * @var array
46
     */
47
    private $config;
17251 ariadna 48
 
49
 
17002 efrain 50
    /**
51
     *
52
     * @var \Laminas\Mvc\I18n\Translator
53
     */
54
    private $translator;
17251 ariadna 55
 
56
 
17002 efrain 57
    /**
58
     *
59
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
60
     * @param \LeadersLinked\Cache\CacheInterface $cache
61
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
62
     * @param array $config
63
     * @param \Laminas\Mvc\I18n\Translator $translator
64
     */
65
    public function __construct($adapter, $cache, $logger, $config, $translator)
66
    {
67
        $this->adapter      = $adapter;
68
        $this->cache        = $cache;
69
        $this->logger       = $logger;
70
        $this->config       = $config;
71
        $this->translator   = $translator;
72
    }
73
 
74
    public function indexAction()
75
    {
17251 ariadna 76
        // Obtiene el plugin del usuario actual y la compañía
17002 efrain 77
        $currentUserPlugin = $this->plugin('currentUserPlugin');
78
        $currentUser = $currentUserPlugin->getUser();
79
        $currentCompany = $currentUserPlugin->getCompany();
80
 
17251 ariadna 81
        // Obtiene la solicitud actual
17002 efrain 82
        $request = $this->getRequest();
17251 ariadna 83
        // Verifica si la solicitud es de tipo GET
17002 efrain 84
        if ($request->isGet()) {
85
 
17251 ariadna 86
            // Obtiene los encabezados de la solicitud
17002 efrain 87
            $headers  = $request->getHeaders();
88
 
17251 ariadna 89
            // Determina si la respuesta debe ser JSON
17002 efrain 90
            $isJson = false;
91
            if ($headers->has('Accept')) {
92
                $accept = $headers->get('Accept');
93
 
94
                $prioritized = $accept->getPrioritized();
95
 
96
                foreach ($prioritized as $key => $value) {
97
                    $raw = trim($value->getRaw());
98
 
99
                    if (!$isJson) {
100
                        $isJson = strpos($raw, 'json');
101
                    }
102
                }
103
            }
104
 
17251 ariadna 105
            // Si la respuesta debe ser JSON
17002 efrain 106
            if ($isJson) {
17251 ariadna 107
                // Obtiene y sanitiza los parámetros de la consulta
17002 efrain 108
                $search = $this->params()->fromQuery('search');
109
                $search = empty($search['value']) ? '' : Functions::sanitizeFilterString($search['value']);
110
 
111
                $page               = intval($this->params()->fromQuery('start', 1), 10);
112
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
113
                $order =  $this->params()->fromQuery('order', []);
114
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
115
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : Functions::sanitizeFilterString(filter_var($order[0]['dir']));
116
 
17251 ariadna 117
                // Define los campos de ordenación
17002 efrain 118
                $fields =  ['name'];
119
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
120
 
121
                if (!in_array($order_direction, ['ASC', 'DESC'])) {
122
                    $order_direction = 'ASC';
123
                }
124
 
17251 ariadna 125
                // Obtiene el mapeador de categorías de medios y los datos paginados
17002 efrain 126
                $mediaCategoryMapper = MediaCategoryMapper::getInstance($this->adapter);
127
                $paginator = $mediaCategoryMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
128
 
17251 ariadna 129
                // Construye la lista de elementos
17002 efrain 130
                $items = [];
131
                $records = $paginator->getCurrentItems();
132
                foreach ($records as $record) {
133
                    $item = [
134
                        'name' => $record->name,
135
                        'actions' => [
136
                            'link_edit' => $this->url()->fromRoute('media/categories/edit', ['id' => $record->uuid]),
137
                            'link_delete' => $this->url()->fromRoute('media/categories/delete', ['id' => $record->uuid])
138
                        ],
139
                    ];
140
 
141
                    array_push($items, $item);
142
                }
143
 
17251 ariadna 144
                // Devuelve un modelo JSON con los datos
17002 efrain 145
                return new JsonModel([
146
                    'success' => true,
147
                    'data' => [
148
                        'items' => $items,
149
                        'total' => $paginator->getTotalItemCount(),
150
                    ]
151
                ]);
152
            } else {
17251 ariadna 153
                // Si no es JSON, devuelve el formulario y la vista
17002 efrain 154
                $form = new CategoryForm();
155
 
156
                $this->layout()->setTemplate('layout/layout-backend');
157
                $viewModel = new ViewModel();
158
                $viewModel->setTemplate('leaders-linked/media/categories.phtml');
159
                $viewModel->setVariable('form', $form);
160
                return $viewModel;
161
            }
162
        } else {
17251 ariadna 163
            // Si la solicitud no es GET, devuelve un error
17002 efrain 164
            return new JsonModel([
165
                'success' => false,
166
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
167
            ]);;
168
        }
169
    }
170
 
171
    public function addAction()
172
    {
173
        $currentUserPlugin = $this->plugin('currentUserPlugin');
174
        $currentUser = $currentUserPlugin->getUser();
175
        $currentCompany = $currentUserPlugin->getCompany();
176
 
177
        $request = $this->getRequest();
178
        if ($request->isPost()) {
179
            $form = new  CategoryForm();
180
            $dataPost = $request->getPost()->toArray();
181
 
182
            $form->setData($dataPost);
183
 
184
            if ($form->isValid()) {
185
                $dataPost = (array) $form->getData();
17251 ariadna 186
 
17002 efrain 187
                $hydrator = new ObjectPropertyHydrator();
188
                $mediaCategory = new MediaCategory();
189
                $mediaCategory->company_id = $currentCompany->id;
190
                $hydrator->hydrate($dataPost, $mediaCategory);
191
 
192
 
193
 
17251 ariadna 194
 
17002 efrain 195
                $mediaCategoryMapper = MediaCategoryMapper::getInstance($this->adapter);
196
                $result = $mediaCategoryMapper->insert($mediaCategory);
197
 
198
                if ($result) {
199
                    $this->logger->info('Se agrego la categoría de media ' . $mediaCategory->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
200
 
201
                    $data = [
202
                        'success'   => true,
203
                        'data'   => 'LABEL_RECORD_ADDED'
204
                    ];
205
                } else {
206
                    $data = [
207
                        'success'   => false,
208
                        'data'      => $mediaCategoryMapper->getError()
209
                    ];
210
                }
211
 
212
                return new JsonModel($data);
213
            } else {
214
                $messages = [];
215
                $form_messages = (array) $form->getMessages();
216
                foreach ($form_messages  as $fieldname => $field_messages) {
217
 
218
                    $messages[$fieldname] = array_values($field_messages);
219
                }
220
 
221
                return new JsonModel([
222
                    'success'   => false,
223
                    'data'   => $messages
224
                ]);
225
            }
226
        } else {
227
            $data = [
228
                'success' => false,
229
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
230
            ];
231
 
232
            return new JsonModel($data);
233
        }
234
 
235
        return new JsonModel($data);
236
    }
237
 
238
    public function editAction()
239
    {
240
        $currentUserPlugin = $this->plugin('currentUserPlugin');
241
        $currentUser = $currentUserPlugin->getUser();
242
        $currentCompany = $currentUserPlugin->getCompany();
243
 
244
        $request = $this->getRequest();
245
        $uuid = $this->params()->fromRoute('id');
246
 
247
 
248
        if (!$uuid) {
249
            $data = [
250
                'success'   => false,
251
                'data'   => 'ERROR_INVALID_PARAMETER'
252
            ];
253
 
254
            return new JsonModel($data);
255
        }
256
 
257
        $mediaCategoryMapper = MediaCategoryMapper::getInstance($this->adapter);
258
        $mediaCategory = $mediaCategoryMapper->fetchOneByUuid($uuid);
259
        if (!$mediaCategory) {
260
            $data = [
261
                'success'   => false,
262
                'data'   => 'ERROR_RECORD_NOT_FOUND'
263
            ];
17251 ariadna 264
 
17002 efrain 265
            return new JsonModel($data);
266
        }
17251 ariadna 267
 
268
        if ($mediaCategory->company_id != $currentCompany->id) {
17002 efrain 269
            return new JsonModel([
270
                'success' => false,
271
                'data' => 'ERROR_UNAUTHORIZED'
272
            ]);
273
        }
274
 
17251 ariadna 275
 
17002 efrain 276
        if ($request->isPost()) {
277
            $form = new  CategoryForm();
278
            $dataPost = $request->getPost()->toArray();
279
 
280
            $form->setData($dataPost);
281
 
282
            if ($form->isValid()) {
283
                $dataPost = (array) $form->getData();
284
 
285
                $hydrator = new ObjectPropertyHydrator();
286
                $hydrator->hydrate($dataPost, $mediaCategory);
287
                $result = $mediaCategoryMapper->update($mediaCategory);
288
 
289
                if ($result) {
290
                    $this->logger->info('Se actualizo la categoría de media ' . $mediaCategory->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
291
 
292
                    $data = [
293
                        'success' => true,
294
                        'data' => 'LABEL_RECORD_UPDATED'
295
                    ];
296
                } else {
297
                    $data = [
298
                        'success'   => false,
299
                        'data'      => $mediaCategoryMapper->getError()
300
                    ];
301
                }
302
 
303
                return new JsonModel($data);
304
            } else {
305
                $messages = [];
306
                $form_messages = (array) $form->getMessages();
307
                foreach ($form_messages  as $fieldname => $field_messages) {
308
                    $messages[$fieldname] = array_values($field_messages);
309
                }
310
 
311
                return new JsonModel([
312
                    'success'   => false,
313
                    'data'   => $messages
314
                ]);
315
            }
316
        } else if ($request->isGet()) {
317
            $hydrator = new ObjectPropertyHydrator();
318
 
319
            $data = [
320
                'success' => true,
321
                'data' => $hydrator->extract($mediaCategory)
322
            ];
323
 
324
            return new JsonModel($data);
325
        } else {
326
            $data = [
327
                'success' => false,
328
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
329
            ];
330
 
331
            return new JsonModel($data);
332
        }
333
 
334
        return new JsonModel($data);
335
    }
336
 
337
    public function deleteAction()
338
    {
339
        $currentUserPlugin = $this->plugin('currentUserPlugin');
340
        $currentUser = $currentUserPlugin->getUser();
341
        $currentCompany = $currentUserPlugin->getCompany();
342
 
343
        $request = $this->getRequest();
344
        $uuid = $this->params()->fromRoute('id');
345
 
346
        if (!$uuid) {
347
            $data = [
348
                'success'   => false,
349
                'data'   => 'ERROR_INVALID_PARAMETER'
350
            ];
351
 
352
            return new JsonModel($data);
353
        }
354
 
355
        $mediaCategoryMapper = MediaCategoryMapper::getInstance($this->adapter);
356
        $mediaCategory = $mediaCategoryMapper->fetchOneByUuid($uuid);
357
        if (!$mediaCategory) {
358
            $data = [
359
                'success'   => false,
360
                'data'   => 'ERROR_RECORD_NOT_FOUND'
361
            ];
362
 
363
            return new JsonModel($data);
364
        }
17251 ariadna 365
 
366
 
367
        if ($mediaCategory->company_id != $currentCompany->id) {
17002 efrain 368
            return new JsonModel([
369
                'success' => false,
370
                'data' => 'ERROR_UNAUTHORIZED'
371
            ]);
372
        }
373
 
17251 ariadna 374
 
17002 efrain 375
        if ($request->isPost()) {
17251 ariadna 376
 
17002 efrain 377
            $mediaFileMapper = \LeadersLinked\Mapper\MediaFileMapper::getInstance($this->adapter);
378
            $total = $mediaFileMapper->fetchTotalCountByCategoryid($mediaCategory->id);
17251 ariadna 379
 
380
            if ($total > 0) {
17002 efrain 381
                return new JsonModel([
382
                    'success' => false,
383
                    'data' => 'ERROR_SQL_CANNOT_DELETE_OR_UPDATE_A_PARENT_ROW'
384
                ]);
385
            }
17251 ariadna 386
 
387
 
388
 
17002 efrain 389
            $result = $mediaCategoryMapper->delete($mediaCategory);
390
            if ($result) {
391
                $this->logger->info('Se borro la categoría de media ' . $mediaCategory->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
392
 
393
                $data = [
394
                    'success' => true,
395
                    'data' => 'LABEL_RECORD_DELETED'
396
                ];
397
            } else {
398
 
399
                $data = [
400
                    'success'   => false,
401
                    'data'      => $mediaCategoryMapper->getError()
402
                ];
403
 
404
                return new JsonModel($data);
405
            }
406
        } else {
407
            $data = [
408
                'success' => false,
409
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
410
            ];
411
 
412
            return new JsonModel($data);
413
        }
414
 
415
        return new JsonModel($data);
416
    }
417
}