src/AppBundle/Controller/DataObjectRestController.php line 38

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Controller;
  3. use AppBundle\Exception\NotAllowedException;
  4. use AppBundle\Exception\ResourceNotFoundException;
  5. use AppBundle\Repository\AbstractEditableRepository;
  6. use AppBundle\Repository\AbstractRepository;
  7. use AppBundle\Services\ApiDataCollectorService;
  8. use AppBundle\Services\ClassDefinitionService;
  9. use AppBundle\Services\ExportService;
  10. use AppBundle\Services\SftpFileTransferService;
  11. use AppBundle\Services\TranslationService;
  12. use Exception;
  13. use Pimcore\Config;
  14. use Pimcore\Controller\FrontendController;
  15. use Pimcore\Model\DataObject;
  16. use Pimcore\Model\DataObject\Concrete;
  17. use Pimcore\Model\DataObject\Order;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. class DataObjectRestController extends FrontendController
  22. {
  23.     const REPOSITORY_NAMESPACE 'AppBundle\Repository';
  24.     /**
  25.      * @Route("/api-v1/{className}/get/{id}", name="rest_get", methods={"GET"})
  26.      * @param Request $request
  27.      * @return JsonResponse
  28.      * @throws NotAllowedException
  29.      * @throws ResourceNotFoundException
  30.      */
  31.     public function getAction(Request $request)
  32.     {
  33.         $object Concrete::GetById($request->get('id'));
  34.         if (!$object) {
  35.             ApiDataCollectorService::setData([$request->get('id') => ResourceNotFoundException::DEFAULT_MESSAGE]);
  36.             throw new ResourceNotFoundException(ResourceNotFoundException::DEFAULT_MESSAGE);
  37.         }
  38.         if ($object->getClassName() != ucfirst($request->get('className'))) {
  39.             ApiDataCollectorService::setData([$request->get('id') => ResourceNotFoundException::DEFAULT_MESSAGE]);
  40.             throw new ResourceNotFoundException(ResourceNotFoundException::DEFAULT_MESSAGE);
  41.         }
  42.         /** @var AbstractRepository $repo */
  43.         $repo self::REPOSITORY_NAMESPACE '\\' ucfirst(trim($request->get('className'))) . 'Repository';
  44.         if (!class_exists($repo)) {
  45.             ApiDataCollectorService::setData([$request->get('className') => NotAllowedException::DEFAULT_MESSAGE]);
  46.             throw new NotAllowedException(NotAllowedException::DEFAULT_MESSAGE);
  47.         }
  48.         return $this->json([
  49.             'success' => true,
  50.             'data' => $repo::toArray($object)
  51.         ]);
  52.     }
  53.     /**
  54.      * @Route("/api-v1/{className}/get-list/", name="rest_get_list", methods={"GET"})
  55.      * @param Request $request
  56.      * @return JsonResponse
  57.      * @throws Exception
  58.      */
  59.     public function getListAction(Request $request)
  60.     {
  61.         $result = [];
  62.         $user null;
  63.         $userId $request->query->get('user_id');
  64.         if ($userId) {
  65.             $user DataObject\User::getById($userId);
  66.         }
  67.         /** @var AbstractRepository $class */
  68.         $class self::REPOSITORY_NAMESPACE '\\' ucfirst(trim($request->get('className'))) . 'Repository';
  69.         if (!class_exists($class)) {
  70.             ApiDataCollectorService::setData([$request->get('className') => NotAllowedException::DEFAULT_MESSAGE]);
  71.             throw new NotAllowedException(NotAllowedException::DEFAULT_MESSAGE);
  72.         }
  73.         $offset $request->query->get('offset'0);
  74.         $limit $request->query->get('limit'1000);
  75.         $orderKey $request->query->get('orderKey''oo_id');
  76.         $order $request->query->get('order''asc');
  77.         $filters $request->query->get('filter''');
  78.         // Add user on repository in order to filter user dependent data
  79.         $class::setUser($user);
  80.         $decodedFilters rawurldecode($filters);
  81.         $arrayFilters json_decode($decodedFilterstrue);
  82.         $list $class::getApiList($offset$limit$orderKey$order$arrayFilters);
  83.         foreach ($list['data'] as $item) {
  84.             $result[] = $class::toArray($item);
  85.         }
  86.         return $this->json([
  87.             'success' => true,
  88.             'data' => $result,
  89.             'totalItem' => $list['totalItem']
  90.         ]);
  91.     }
  92.     /**
  93.      * @Route("/api-v1/{className}/export", name="rest_export", methods={"POST"})
  94.      * @param string $className
  95.      * @param Request $request
  96.      * @param ExportService $exportService
  97.      * @return JsonResponse
  98.      * @throws NotAllowedException
  99.      */
  100.     public function export(string $classNameRequest $requestExportService $exportService)
  101.     {
  102.         $values json_decode($request->getContent(), true);
  103.         $ids $values['ids'];
  104.         $user null;
  105.         $userId $request->query->get('user_id');
  106.         if ($userId) {
  107.             $user DataObject\User::getById($userId);
  108.         } else {
  109.             throw new NotAllowedException();
  110.         }
  111.         $exportService
  112.             ->setUser($user)
  113.             ->setClassName($className);
  114.         $file $exportService->run($ids);
  115.         $response = [
  116.             'success' => true,
  117.             'message' => '',
  118.             'data' => $file
  119.         ];
  120.         return $this->json($response);
  121.     }
  122.     /**
  123.      * @Route("/api-v1/{className}/", name="rest_route", methods={"POST","PATCH","DELETE"})
  124.      * @param Request $request
  125.      * @return JsonResponse
  126.      * @throws NotAllowedException
  127.      */
  128.     public function genericAction(Request $request)
  129.     {
  130.         $values json_decode($request->getContent(), true);
  131.         $data null;
  132.         /** @var AbstractEditableRepository $repo */
  133.         $repo self::REPOSITORY_NAMESPACE '\\' ucfirst(trim($request->get('className'))) . 'Repository';
  134.         if (!class_exists($repo)) {
  135.             // not allowed because it is the existence of editable repo which define the edition right
  136.             ApiDataCollectorService::setData([$request->get('className') => NotAllowedException::DEFAULT_MESSAGE]);
  137.             throw new NotAllowedException();
  138.         }
  139.         switch ($request->getMethod()) {
  140.             case Request::METHOD_POST:
  141.                 $method 'create';
  142.                 break;
  143.             case Request::METHOD_PATCH:
  144.                 $method 'update';
  145.                 break;
  146.             case Request::METHOD_DELETE:
  147.                 $method 'delete';
  148.                 break;
  149.             default:
  150.                 ApiDataCollectorService::setData([$request->getMethod() => NotAllowedException::DEFAULT_MESSAGE]);
  151.                 throw new NotAllowedException();
  152.                 break;
  153.         }
  154.         if (!method_exists($repo$method)) {
  155.             ApiDataCollectorService::setData([$method => NotAllowedException::DEFAULT_MESSAGE]);
  156.             throw new NotAllowedException();
  157.         }
  158.         $userId $request->query->get('user_id');
  159.         if ($userId) {
  160.             $user DataObject\User::getById($userId);
  161.             $repo::setUser($user);
  162.         }
  163.         $object $repo::$method($values);
  164.         switch ($method) {
  165.             case 'delete':
  166.                 // in case of delete we need to extract correct message
  167.                 $mess TranslationService::getWebsiteTranslation("L'élément a bien été supprimé");
  168.                 if (isset($values['ids']) && count($values['ids']) > 1) {
  169.                     $mess TranslationService::getWebsiteTranslation('Les éléments ont bien été supprimés');
  170.                 }
  171.                 $dataArray ApiDataCollectorService::getData();
  172.                 if (!empty($dataArray) && isset($dataArray['data'])) { // cas des suppressions partielles
  173.                     if(isset($dataArray['globalMessage']) && !is_null($dataArray['globalMessage'])){
  174.                         $mess $dataArray['globalMessage'];
  175.                     }
  176.                     ApiDataCollectorService::setData($dataArray['data']);
  177.                 }
  178.                 $response = [
  179.                     'success' => true,
  180.                     'message' => $mess,
  181.                     'data' => ApiDataCollectorService::getData()
  182.                 ];
  183.                 break;
  184.             case 'create':
  185.             case 'update':
  186.             default:
  187.                 $response = [
  188.                     'success' => true,
  189.                     'data' => $repo::toArray($object)
  190.                 ];
  191.                 break;
  192.         }
  193.         return $this->json($response);
  194.     }
  195.     /**
  196.      * @Route("/api-v1/class-definition/{className}/{attribute}", name="rest_get_attribute", methods={"GET"})
  197.      * @param String $className
  198.      * @param String $attribute
  199.      * @param Request $request
  200.      * @return JsonResponse
  201.      * @throws NotAllowedException
  202.      * @throws ResourceNotFoundException
  203.      */
  204.     public function getAttributeDefinitionAction(string $classNamestring $attributeRequest $request)
  205.     {
  206.         $result ClassDefinitionService::getSelectValues($className$attribute);
  207.         return $this->json([
  208.             'success' => true,
  209.             'data' => $result
  210.         ]);
  211.     }
  212.     /**
  213.      * @Route("/api-v1/class-definition/{className}/{attribute}/create-from-path",
  214.      *     name="rest_create-from-path_attribute",
  215.      *     methods={"POST"}
  216.      *     )
  217.      * @param String $className
  218.      * @param String $attribute
  219.      * @param Request $request
  220.      * @return JsonResponse
  221.      * @throws NotAllowedException
  222.      * @throws ResourceNotFoundException
  223.      */
  224.     public function createAssetFromSourceAction(string $classNamestring $attributeRequest $request)
  225.     {
  226.         $path $request->request->get('path');
  227.         $filename $request->request->get('filename');
  228.         $result ClassDefinitionService::createAssetFromPath(
  229.             $className,
  230.             $attribute,
  231.             $path,
  232.             $filename
  233.         );
  234.         return $this->json([
  235.             'success' => true,
  236.             'data' => $result
  237.         ]);
  238.     }
  239.     /**
  240.      * @Route("/api-v1/order/download-pdf/{orderId}",
  241.      *     name="rest-download-order-pdf",
  242.      *     methods={"GET"}
  243.      *     )
  244.      * @param string $orderId
  245.      * @return JsonResponse
  246.      * @throws Exception
  247.      */
  248.     public function downloadOrderPdf(string $orderId)
  249.     {
  250.         $order Order::getById($orderId);
  251.         if ($order) {
  252.             $localPath implode(
  253.                 DIRECTORY_SEPARATOR,
  254.                 [
  255.                     PIMCORE_TEMPORARY_DIRECTORY,
  256.                     'lv-order-pdf',
  257.                     $orderId
  258.                 ]);
  259.             $pdfPath $order->getPdf();
  260.             SftpFileTransferService::transferFileFromTwist($pdfPath$localPath);
  261.             $domain Config::getSystemConfiguration('general')['domain'];
  262.             if (empty($domain)) {
  263.                 throw new Exception('Domain is not defined in System configuration > general > domain');
  264.             }
  265.             $partPart explode('/'$pdfPath);
  266.             $filename end($partPart);
  267.             $url $domain '/var/tmp/lv-order-pdf/' $orderId '/' $filename;
  268.             return $this->json([
  269.                 'success' => true,
  270.                 'message' => '',
  271.                 'data' => $url
  272.             ]);
  273.         }
  274.     }
  275. }