gabriel %!s(int64=8) %!d(string=hai) anos
pai
achega
525853f2ec

+ 165 - 16
Controller/RESTController.php

@@ -2,12 +2,14 @@
 
 namespace WebserviceBundle\Controller;
 
+use ClientBundle\Form\ClientType;
 use FOS\RestBundle\Controller\Annotations\QueryParam;
 use FOS\RestBundle\Controller\Annotations\RouteResource;
 use FOS\RestBundle\Controller\Annotations\View;
 use FOS\RestBundle\Request\ParamFetcherInterface;
 use FOS\RestBundle\Util\Codes;
 use FOS\RestBundle\View\View as FOSView;
+use ReflectionClass;
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
 use Symfony\Component\Form\Form;
@@ -16,10 +18,26 @@ use Symfony\Component\HttpFoundation\Response;
 
 use Voryx\RESTGeneratorBundle\Controller\VoryxController;
 
-class RESTController extends VoryxController
+abstract class RESTController extends VoryxController
 {
-    var $repository = 'ClientBundle:Client';
-    
+
+    /**
+     * @return string Retorna el nombre de la Entity de trabajo.
+     */
+    abstract public function getRepository();
+
+    /**
+     * @return string Retorna el tipo de la clase.
+     */
+//    abstract public function getFormEntityType();
+    /**
+     * @return string Retorna el tipo de la clase.
+     */
+    public function getFormEntityType()
+    {
+        return get_class(new ClientType());
+    }
+
     /**
      * Get all entities.
      *
@@ -39,52 +57,61 @@ class RESTController extends VoryxController
     public function cgetAction(ParamFetcherInterface $paramFetcher)
     {
         $em = $this->getDoctrine()->getManager();
-        
         $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array();
-        if(isset($filters['qb-criteria'])) {
+        if (isset($filters['tenancyId'])) {
+            // tengo que buscar por tenencia.
+            $tenancyService = $this->container->get('base_tenancy.tenancy_service');
+            $tenancyService->setTenancy($filters['tenancyId']);
+            unset($filters['tenancyId']);
+        }
+        if (isset($filters['qb-criteria'])) {
             try {
 
                 unset($filters['qb-criteria']);
                 $criteria = new \Doctrine\Common\Collections\Criteria();
 
-                foreach($filters as $field => $value) {
+                foreach ($filters as $field => $value) {
                     $criteria->andWhere($criteria->expr()->contains("$field", "$value"));
                 }
 
-                if(!is_null($paramFetcher->get('offset'))) {
+                if (!is_null($paramFetcher->get('offset'))) {
                     $criteria->setFirstResult($paramFetcher->get('offset'));
                 }
 
-                if(!is_null($paramFetcher->get('limit'))) {
+                if (!is_null($paramFetcher->get('limit'))) {
                     $criteria->setMaxResults($paramFetcher->get('limit'));
                 }
 
-                if($paramFetcher->get('order_by')) {
+                if ($paramFetcher->get('order_by')) {
                     $order_by = $paramFetcher->get('order_by');
                     $orderBy = array();
-                    foreach($order_by as $field => $order) {
+                    foreach ($order_by as $field => $order) {
                         $orderBy[$field] = $order;
                     }
                     $criteria->orderBy($orderBy);
                 }
 
-                $repo = $em->getRepository($this->repository);
+                $repo = $em->getRepository($this->getRepository());
                 $entities = $repo->matching($criteria)->toArray();
 
+                if($disableTenancy) $tenancyService->enableFilter();
+
                 if ($entities) {
                     return $entities;
                 }
-            
+
             } catch (\Exception $e) {
                 return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
             }
-            
+
         } else {
             try {
                 $offset = $paramFetcher->get('offset');
                 $limit = $paramFetcher->get('limit');
                 $order_by = $paramFetcher->get('order_by');
-                $entities = $em->getRepository($this->repository)->findBy($filters, $order_by, $limit, $offset);
+                $entities = $em->getRepository($this->getRepository())->findBy($filters, $order_by, $limit, $offset);
+
+                if($disableTenancy) $tenancyService->enableFilter();
 
                 if ($entities) {
                     return $entities;
@@ -96,7 +123,129 @@ class RESTController extends VoryxController
 
         }
 
-         return array();
+        return array();
+    }
+
+    /**
+     * @return object Retorna el nombre de la Entity de trabajo.
+     */
+    public function getObject()
+    {
+        $obj = $this->getDoctrine()->getManager()->getMetadataFactory()->getMetadataFor($this->getRepository())->getName();
+        $rc = new ReflectionClass($obj);
+        return $rc->newInstance();
+    }
+
+    /**
+     * Create a Client entity.
+     *
+     * @View(statusCode=201, serializerEnableMaxDepthChecks=true)
+     *
+     * @param Request $request Contiene el request.
+     *
+     * @return FOSView|mixed Retorna el FOSView o la entidad.
+     *
+     */
+    public function postAction(Request $request)
+    {
+//        file_put_contents("/tmp/t", "LLEGO\n",8);
+        $entity = $this->getObject();
+        $form = $this->createForm($this->getFormEntityType(), $entity, array("method" => $request->getMethod()));
+        $this->removeExtraFields($request, $form);
+        $form->handleRequest($request);
+
+        if ($form->isSubmitted() && $form->isValid()) {
+            $em = $this->getDoctrine()->getManager();
+            $em->persist($entity);
+            $em->flush();
+
+            return $entity;
+        }
+        return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
+    }
+
+    /**
+     * Update a Client entity.
+     *
+     * @View(serializerEnableMaxDepthChecks=true)
+     *
+     * @param Request $request Contiene el request.
+     * @param mixed $entity Contiene la entidad
+     *
+     * @return FOSView|mixed Retorna el FOSView o la entidad.
+     */
+    public function putAction(Request $request, $entity = null)
+    {
+        try {
+            $em = $this->getDoctrine()->getManager();
+            $request->setMethod('PATCH'); //Treat all PUTs as PATCH
+            $form = $this->createForm($this->getFormEntityType(), $entity, array("method" => $request->getMethod()));
+            $this->removeExtraFields($request, $form);
+            $form->handleRequest($request);
+            if ($form->isValid()) {
+                $em->flush();
+
+                return $entity;
+            }
+
+            return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
+        } catch (\Exception $e) {
+            return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
+        }
+    }
+
+    /**
+     * Partial Update to a Client entity.
+     *
+     * @View(serializerEnableMaxDepthChecks=true)
+     *
+     * @param Request $request Contiene el request.
+     * @param mixed $entity Contiene la entidad.
+     *
+     * @return Response Retorna un response.
+     */
+    public function patchAction(Request $request, $entity)
+    {
+        return $this->putAction($request, $entity);
     }
-    
+
+    /**
+     * Delete a Client entity.
+     *
+     * @View(statusCode=204)
+     *
+     * @param Request $request Contiene el request.
+     * @param mixed $entity Contiene la entidad a borrar.
+     *
+     * @return FOSView Retorna el FSOView.
+     */
+    public function deleteAction(Request $request, $entity)
+    {
+        try {
+            $em = $this->getDoctrine()->getManager();
+            $em->remove($entity);
+            $em->flush();
+
+            return null;
+        } catch (\Exception $e) {
+            return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
+        }
+    }
+
+    /**
+     * Get a Client entity
+     *
+     * @View(serializerEnableMaxDepthChecks=true)
+     *
+     * @param mixed $entity Contiene la entidad.
+     *
+     * @return Response
+     *
+     */
+    public function getAction($entity)
+    {
+        return $entity;
+    }
+
+
 }

+ 39 - 14
Form/ChoiceList/Loader/ClientChoiceLoader.php

@@ -2,6 +2,7 @@
 
 namespace WebserviceBundle\Form\ChoiceList\Loader;
 
+use Base\AdminBundle\Controller\TenancyService;
 use Symfony\Component\Form\ChoiceList\ArrayChoiceList;
 use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
 use Symfony\Component\Form\FormBuilderInterface;
@@ -10,22 +11,40 @@ use Symfony\Component\Form\FormEvents;
 
 class ClientChoiceLoader implements ChoiceLoaderInterface
 {
-    
+
     /**
      * @var Webservice
      */
     protected $webservice;
+    /**
+     * @var TenancyService
+     */
+    protected $tenancyService;
 
     // Currently selected choices
     protected $selected = [];
 
+    /**
+     * @var string
+     */
+    protected $webserviceParameter;
+
+    /**
+     * @var boolean
+     */
+    protected $filterTenancy;
     
+
     /**
      * @param Webservice $webservice
+     * @param TenancyService $tenancyService Contiene el servicio de tenencias.
      */
-    public function __construct($webservice)
+    public function __construct($webservice, $tenancyService, $webserviceParameter = 'client', $filterTenancy = true)
     {
         $this->webservice = $webservice;
+        $this->tenancyService = $tenancyService;
+        $this->webserviceParameter = $webserviceParameter;
+        $this->filterTenancy = $filterTenancy;
     }
     
     /**
@@ -74,9 +93,9 @@ class ClientChoiceLoader implements ChoiceLoaderInterface
     public function loadChoiceList($value = null)
     {
         $choices = $this->getChoicesList(false);
-
+        
         $missing_choices = array_flip($this->selected);
-
+        
         foreach ($choices as $label => $id) {
             if (isset($missing_choices[$id])) {
                 unset($missing_choices[$id]);
@@ -93,7 +112,7 @@ class ClientChoiceLoader implements ChoiceLoaderInterface
 
             $choices[$label] = $id;
         }
-        
+
         return new ArrayChoiceList($choices);
     }
 
@@ -119,7 +138,7 @@ class ClientChoiceLoader implements ChoiceLoaderInterface
 
     /**
      * Turn choices from other datatypes into strings (HTML option
-     * values) if needed - we can simply return the choices as 
+     * values) if needed - we can simply return the choices as
      * they're strings already.
      * Required by ChoiceLoaderInterface.
      */
@@ -128,6 +147,7 @@ class ClientChoiceLoader implements ChoiceLoaderInterface
         $result = [];
         foreach ($choices as $id) {
             if ($this->choiceExists($id)) {
+                $this->selected = array($id);
                 $result[] = $id;
             }
         }
@@ -137,18 +157,22 @@ class ClientChoiceLoader implements ChoiceLoaderInterface
 
     /**
      * Get first n choices
-     * 
+     *
      * @param string $filter
-     * 
+     *
      * @return array
      */
     public function getChoicesList($filter)
     {
         $params = array();
         if ($filter !== false) {
-            $params['name'] = $filter;
+            $params['name'] = urlencode($filter);
+            if ($this->filterTenancy) {
+                $params['tenancyId'] = $this->tenancyService->getTenancyIdCurrent();
+            }
         }
-        $choices = $this->webservice->getChoices('client', $params);
+        
+        $choices = $this->webservice->getChoices($this->webserviceParameter, $params);
 
         $result = [];
         $cnt = 0;
@@ -171,7 +195,7 @@ class ClientChoiceLoader implements ChoiceLoaderInterface
      */
     protected function choiceExists($id)
     {
-        $label = array_search($id, $this->initChoices());
+        $label = array_search($id, $this->initChoices(array("id" => $id)));
 
         return $label === false ? false : true;
     }
@@ -181,17 +205,18 @@ class ClientChoiceLoader implements ChoiceLoaderInterface
      */
     protected function getChoiceLabel($id)
     {
-        $label = array_search($id, $this->initChoices());
+        $label = array_search($id, $this->initChoices(array("id" => $id)));
 
         return $label === false ? false : $label;
     }
 
     /**
+     * @param array $params Contiene un array con los datos a verificar.
      * @return array
      */
-    protected function initChoices()
+    protected function initChoices($params = array())
     {
-        return $this->webservice->getChoices('client');
+        return $this->webservice->getChoices($this->webserviceParameter, $params);
     }
 
 }

+ 1 - 1
Resources/config/services.yml

@@ -9,7 +9,7 @@ services:
        
    webservice.client.choiceloader:
        class: WebserviceBundle\Form\ChoiceList\Loader\ClientChoiceLoader
-       arguments: ["@webservice"]
+       arguments: ["@webservice", "@base_tenancy.tenancy_service"]
        
    webservice.client.admin:
        class: WebserviceBundle\Services\ClientAdmin

+ 16 - 3
Resources/views/Type/remote_client_widget.html.twig

@@ -24,10 +24,18 @@
                     p: params.page
                 };
             };
-
-            $('select[id$="clientId"]').select2({
+            
+        {% if id is not defined %}
+            {% set id = 'clientId' %}
+        {% endif %}
+            
+        {% if ajax_url is not defined %}
+            {% set ajax_url = 'ajax_client_list' %}
+        {% endif %}
+            
+            $('select[id$="{{ id }}"]').select2({
                 ajax: {
-                    url: '{{ path('ajax_client_list') }}',
+                    url: '{{ path(ajax_url) }}',
                     dataType: 'json',
                     delay: 250,
                     data: getAjaxListData,
@@ -43,6 +51,10 @@
             <div style="width: 50%; float: left;">
                 {{ block('choice_widget') }}
             </div>
+            {% if create is not defined %}
+                {% set create = true %}
+            {% endif %}
+            {% if create %}
             {% set url = remote_client_url() %}
             {% if url != '#' %}
             <div style="width: 50%; float: left;">
@@ -51,6 +63,7 @@
                 </a>
             </div>
             {% endif %}
+            {% endif %}
         </div>
     {% endspaceless %}
 {% endblock %}