Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15371 | Autoría | Ultima modificación | Ver Log |

<?php

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\ViewModel;
use Laminas\View\Model\JsonModel;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\TopicMapper;
use LeadersLinked\Mapper\FeedMapper;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Form\TopicForm;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Db\ResultSet\HydratingResultSet;
use LeadersLinked\Model\Topic;
use LeadersLinked\Mapper\CompanyMapper;
use LeadersLinked\Model\Company;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;

class DevelopmentContentCategoryController extends AbstractActionController {

    /**
     *
     * @var AdapterInterface
     */
    private $adapter;

    /**
     *
     * @var AbstractAdapter
     */
    private $cache;

    /**
     *
     * @var  LoggerInterface
     */
    private $logger;

    /**
     *
     * @var array
     */
    private $config;

    /**
     *
     * @param AdapterInterface $adapter
     * @param AbstractAdapter $cache
     * @param LoggerInterface $logger
     * @param array $config
     */
    public function __construct($adapter, $cache, $logger, $config) {
        $this->adapter = $adapter;
        $this->cache = $cache;
        $this->logger = $logger;
        $this->config = $config;
    }

    public function indexAction() {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();

        
        $request = $this->getRequest();
        if ($request->isGet()) {

            $headers = $request->getHeaders();

            $isJson = false;
            if ($headers->has('Accept')) {
                $accept = $headers->get('Accept');

                $prioritized = $accept->getPrioritized();

                foreach ($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());

                    if (!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                }
            }

            if ($isJson) {
                $search = $this->params()->fromQuery('search', []);
                $search = empty($search['value']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);

                $start = intval($this->params()->fromQuery('start', 0), 10);
                $records_x_page = intval($this->params()->fromQuery('length', 10), 10);
                $page =  intval($start / $records_x_page);
                $page++;
                
                $order = $this->params()->fromQuery('order', []);
                $order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
                $order_direction = empty($order[0]['dir']) ? 'ASC' : strtoupper(filter_var($order[0]['dir'], FILTER_SANITIZE_STRING));

                $fields = ['title'];
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'title';

                if (!in_array($order_direction, ['ASC', 'DESC'])) {
                    $order_direction = 'ASC';
                }

                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'development-and-content/category/edit');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'development-and-content/category/delete');

                $items = [];
                $topicMapper = TopicMapper::getInstance($this->adapter);
                
                $paginator = $topicMapper->fetchAllDevelopment();
                
              
                foreach ($paginator as $record) {
                    
                    $item = [
                        'id' => $record->id,
                        'title' => $record->title,
                        'description' => $record->description,
                        'status' => $record->status,
                        'actions' => [
                            'link_edit' => ($allowEdit)? $this->url()->fromRoute('development-and-content/category/edit', ['id' => $record->uuid]):'',
                            'link_delete' =>($allowDelete)? $this->url()->fromRoute('development-and-content/category/delete', ['id' => $record->uuid]):'',
                        ]
                    ];

                    array_push($items, $item);
                }

                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'items' => $items,
                    ]
                ]);
            } else {

                $form = new TopicForm($this->adapter, $currentCompany->id);

                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/development-content-category/index.phtml');
                $viewModel->setVariable('form', $form);
                return $viewModel;
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }

    }

    public function addAction() { 
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
        $currentCompany     = $currentUserPlugin->getCompany(); 
        $currentUser        = $currentUserPlugin->getUser();
        
        $request    = $this->getRequest();

        
        if($request->isPost()) {
            $form = new  TopicForm($this->adapter, $currentCompany->id);
            
            $dataPost = $request->getPost()->toArray();
            
            $form->setData($dataPost);
            
            if($form->isValid()) {
               
                $dataPost = (array) $form->getData();
                
                $hydrator = new ObjectPropertyHydrator();
                $categories = new Topic();
                $hydrator->hydrate($dataPost, $categories);
               
                $categories->type='dc';

                $categoriesMapper = TopicMapper::getInstance($this->adapter);

                if($categoriesMapper->insert($categories)) {
                     $categories = $categoriesMapper->fetchOne($categories->id);                 

                    $this->logger->info('Se agrego la categoria ' . $categories->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $categoriesMapper->getError()
                    ];
                    
                }
                
                return new JsonModel($data);
                
            } else {
                $messages = [];
                $form_messages = (array) $form->getMessages();
                foreach($form_messages  as $fieldname => $field_messages)
                {
                    
                    $messages[$fieldname] = array_values($field_messages);
                }
                
                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
                
            }
            
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);

    }

    public function editAction() {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        $uuid = $this->params()->fromRoute('id');
        
        if (!$uuid) {
            $data = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($data);
        }

        $categoriesMapper = TopicMapper::getInstance($this->adapter);
        $categories = $categoriesMapper->fetchOneByUuid($uuid);
        
        if (!$categories) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }


        if ($request->isPost()) {
            $form = new TopicForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

            if ($form->isValid()) {
                $dataPost = (array) $form->getData();

                $hydrator = new ObjectPropertyHydrator();
                $hydrator->hydrate($dataPost, $categories);

                if($categoriesMapper->update($categories)) {
                    $categories = $categoriesMapper->fetchOne($categories->id);                 

                   $this->logger->info('Se modifico la categoria ' . $categories->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                   
                   $data = [
                       'success'   => true,
                       'data'   => 'LABEL_RECORD_UPDATED'
                   ];
               } else {
                   $data = [
                       'success'   => false,
                       'data'      => $categoriesMapper->getError()
                   ];
                   
               }

                return new JsonModel($data);
                
            } else {
                $messages = [];
                $form_messages = (array) $form->getMessages();
                foreach($form_messages  as $fieldname => $field_messages)
                {
                    
                    $messages[$fieldname] = array_values($field_messages);
                }
                
                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
            }
        } else if ($request->isGet()) {

            $hydrator = new ObjectPropertyHydrator();

            $data = [
                'success' => true,
                'data' => [
                    'id' => $categories->uuid,
                    'title' => $categories->title,
                    'description' => $categories->description,
                    'status' => $categories->status
                ]
            ];

            return new JsonModel($data);
            
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

    }

    public function deleteAction() 
    {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        $uuid = $this->params()->fromRoute('id');

        if (!$uuid) {
            $data = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($data);
        }

        $categoriesMapper = TopicMapper::getInstance($this->adapter);
        $categories = $categoriesMapper->fetchOneByUuid($uuid);
        if (!$categories) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }

        if ($request->isPost()) {

            $feedMapper = FeedMapper::getInstance($this->adapter);
            $feeds = $feedMapper->fetchAllByDevelopAndCategoryIdCount($categories->id);
            if($feeds > 0){

                $data = [
                    'success' => false,
                    'data' => 'Esta categoria posee contenidos asociados no puede ser eliminada'
                ];
                return new JsonModel($data);
                
            } else {
                $result = $categoriesMapper->delete($categories->id);
                if ($result) {
                    $this->logger->info('Se borro la categoria ' . $categories->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    $data = [
                        'success' => true,
                        'data' => 'LABEL_RECORD_DELETED'
                    ];
                } else {

                    $data = [
                        'success' => false,
                        'data' => $categoriesMapper->getError()
                    ];

                    return new JsonModel($data);
                }
            }


        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }
}