vendor/launchpad/backend/src/Api/Controller/BaseApiController.php line 253

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: marija
  5.  * Date: 15.1.18.
  6.  * Time: 15.42
  7.  */
  8. namespace LaunchPad\Bundle\LaunchPadBundle\Api\Controller;
  9. use Doctrine\Common\Annotations\AnnotationReader;
  10. use LaunchPad\Bundle\LaunchPadBundle\Base\Entity\User\User;
  11. use Gedmo\Translator\TranslationInterface;
  12. use LaunchPad\Bundle\LaunchPadBundle\Base\Exception\MissingApiParamsException;
  13. use LaunchPad\Bundle\LaunchPadBundle\Base\Service\AppNormalizerService;
  14. use LaunchPad\Bundle\LaunchPadBundle\Base\Service\BaseService;
  15. //use BoBoFin\Base\Serializer\Normalizer\BoBoFinNormalizer;
  16. use LaunchPad\Bundle\LaunchPadBundle\Base\Serializer\Normalizer\AppNormalizer;
  17. use LaunchPad\Bundle\LaunchPadBundle\Base\Controller\BaseController;
  18. use LaunchPad\Bundle\LaunchPadBundle\Base\Service\Stats\Apple\AppleReportService;
  19. use LaunchPad\Bundle\LaunchPadBundle\Base\Service\Translation\TranslationService;
  20. use LaunchPad\Bundle\LaunchPadBundle\Base\Service\User\UserPermissionService;
  21. use Symfony\Component\HttpFoundation\JsonResponse;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use Symfony\Component\HttpFoundation\RequestStack;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\Routing\Annotation\Route;
  26. use Symfony\Component\Security\Core\Security;
  27. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  28. use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
  29. use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
  30. use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
  31. use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  32. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  33. use Symfony\Component\Serializer\Serializer;
  34. /**
  35.  * Class BaseApiController
  36.  * @package LaunchPad\Api\Controller
  37.  */
  38. class BaseApiController extends BaseController
  39. {
  40.     /** @var array  */
  41.     protected $data = [];
  42.     /** @var BaseService */
  43.     private $baseService;
  44.     /** @var AppNormalizerService */
  45.     private $appNormalizerService;
  46. //    /**
  47. //     * @Route("", name="api_root")
  48. //     *
  49. //     */
  50. //    public function indexAction(Request $request)
  51. //    {
  52. //        $apiDefinitions = $this->getParameter('api');
  53. //
  54. //        $scheme = $request->query->get('scheme');
  55. //
  56. //        if(!$scheme) {
  57. //            return $this->render(
  58. //                "@WebsiteTemplates/swagger/index.html.twig",
  59. //                [
  60. //                    'definitions' => $apiDefinitions
  61. //                ]
  62. //            );
  63. //        }
  64. //
  65. //        return $this->render(
  66. //            "@WebsiteTemplates/swagger/ui.html.twig",
  67. //            [
  68. //                'url' => '/api/definition?scheme=' . urlencode($scheme)
  69. //            ]
  70. //        );
  71. //    }
  72. //
  73. //    /**
  74. //     * @Route("/definition", name="api_definition")
  75. //     * @param Request $request
  76. //     * @return Response
  77. //     */
  78. //    public function apiDefinitionAction(Request $request)
  79. //    {
  80. //        $scheme = $request->query->get('scheme');
  81. //
  82. //       // dump($scheme);
  83. //        $apiDefinitions = $this->getParameter('api');
  84. //
  85. //        $selectedDefinition = null;
  86. //
  87. //        foreach($apiDefinitions as $definition) {
  88. //            if($definition['name'] == $scheme) {
  89. //                $selectedDefinition = $definition;
  90. //                break;
  91. //            }
  92. //        }
  93. //
  94. //        $openapi = \OpenApi\scan($selectedDefinition['paths']);
  95. //        header('Content-Type: application/json');
  96. //        return new Response($openapi->toJson());
  97. //    }
  98.     /**
  99.      * Set BaseApiService
  100.      *
  101.      * @param BaseService $baseService
  102.      */
  103.     public function setBaseApiService(BaseService $baseService)
  104.     {
  105.         $this->baseService $baseService;
  106.     }
  107.     /**
  108.      * Set BaseApiService
  109.      *
  110.      * @param AppNormalizerService $appNormalizerService
  111.      */
  112.     public function setAppNormalizerService(AppNormalizerService $appNormalizerService)
  113.     {
  114.         $this->appNormalizerService $appNormalizerService;
  115.     }
  116.     /**
  117.      * Return json success response
  118.      *
  119.      * @param array $data
  120.      * @param null $message
  121.      * @param array $groups
  122.      * @return JsonResponse
  123.      * @throws \Doctrine\Common\Annotations\AnnotationException
  124.      * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface
  125.      */
  126.     protected function success($data null$message null$groups = [])
  127.     {
  128.         if (is_string($data) && empty($message)) {
  129.             $message $data;
  130.             $data null;
  131.         }
  132.         return $this->jsonOutput([
  133.             'success' => true,
  134.             'data' => $data,
  135.             'message' => $message
  136.         ], 200$groups);
  137.     }
  138.     /**
  139.      * Return json failure response
  140.      *
  141.      * @param null $data
  142.      * @param null $message
  143.      * @param array $groups
  144.      * @return JsonResponse
  145.      * @throws \Doctrine\Common\Annotations\AnnotationException
  146.      * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface
  147.      */
  148.     protected function failure($data null$message null$groups = [])
  149.     {
  150.         if (is_string($data) && empty($message)) {
  151.             $message $data;
  152.             $data null;
  153.         }
  154.         return $this->jsonOutput([
  155.             'success' => false,
  156.             'data' => $data,
  157.             'message' => $message
  158.         ], 200$groups);
  159.     }
  160.     /**
  161.      * Return JSON error response
  162.      *
  163.      * @param null $type
  164.      * @param array $data
  165.      * @param null $message
  166.      * @param int $code
  167.      * @return JsonResponse
  168.      * @throws \Doctrine\Common\Annotations\AnnotationException
  169.      * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface
  170.      */
  171.     protected function jsonError($type null$data null$message null$code 200)
  172.     {
  173.         if (is_string($data) && empty($message)) {
  174.             $message $data;
  175.             $data null;
  176.         }
  177.         return $this->jsonOutput([
  178.             'success' => false,
  179.             'data' => $data,
  180.             'code' => $code,
  181.             'errors' => [
  182.                 [
  183.                     'type' => $type,
  184.                     'message' => $message,
  185.                 ]
  186.             ]
  187.         ]);
  188.     }
  189.     /**
  190.      * Return Invalid field
  191.      *
  192.      * @param $field
  193.      * @param $message
  194.      * @return JsonResponse
  195.      * @throws \Doctrine\Common\Annotations\AnnotationException
  196.      * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface
  197.      */
  198.     protected function invalidField($field$message)
  199.     {
  200.         $type 'validation_error';
  201.         return $this->invalidFields([
  202.             compact('field''message''type')
  203.         ]);
  204.     }
  205.     /**
  206.      * Return Invalid fields
  207.      *
  208.      * @param $fields
  209.      * @return JsonResponse
  210.      * @throws \Doctrine\Common\Annotations\AnnotationException
  211.      * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface
  212.      */
  213.     protected function invalidFields($fields)
  214.     {
  215.         return $this->jsonOutput([
  216.             'success' => false,
  217.             'code' => 200,
  218.             'errors' => $fields
  219.         ]);
  220.     }
  221.     /**
  222.      * Return JSON output
  223.      *
  224.      * @param $data
  225.      * @param int $code
  226.      * @param array $groups
  227.      * @return JsonResponse
  228.      * @throws \Doctrine\Common\Annotations\AnnotationException
  229.      * @throws \Symfony\Component\Serializer\Exception\ExceptionInterface
  230.      */
  231.     private function jsonOutput($data$code 200$groups = [])
  232.     {
  233.         $encoders = array(new JsonEncoder());
  234.         $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
  235.         $normalizer = new AppNormalizer(
  236.             $classMetadataFactory,
  237.             null,
  238.             null,
  239.             null,
  240.             $this->appNormalizerService
  241.         );
  242.         $normalizers = array(new DateTimeNormalizer(), $normalizer, new GetSetMethodNormalizer());
  243.         $normalizers[1]->setCircularReferenceHandler(function ($object) {
  244.             return $object->getId();
  245.         });
  246.         $serializer = new Serializer($normalizers$encoders);
  247.         if ($groups) {
  248.             $data $serializer->normalize($data'json', ['groups' => $groups]);
  249.             $data $serializer->serialize($data'json', ['groups' => $groups]);
  250.         } else {
  251.             $data $serializer->serialize($data'json');
  252.         }
  253.         return new JsonResponse($data$code, [], true);
  254.     }
  255.     /**
  256.      * Require post params
  257.      *
  258.      * @param array $requiredParameters Array of required parameters.
  259.      *
  260.      * @throws \Doctrine\Common\Annotations\AnnotationException
  261.      * @throws MissingApiParamsException
  262.      */
  263.     protected function requirePostParams($requiredParameters)
  264.     {
  265.         if (empty($this->data)) {
  266.             $currentRequest $this->get('request_stack')->getCurrentRequest();
  267.             $this->data $currentRequest->request->all();
  268.         }
  269.         $postData $this->data;
  270.         $errors = [];
  271.         foreach ($requiredParameters as $requiredParameter) {
  272.             if (is_array($requiredParameter)) {
  273.                 $intersectingKeys array_intersect_key(
  274.                     array_flip($requiredParameter),
  275.                     $postData
  276.                 );
  277.                 if (empty($intersectingKeys)) {
  278.                         $errors[] = [
  279.                             'fields' => implode(', '$requiredParameter),
  280.                             'message' => 'One of following is required 'implode('or '$requiredParameter),
  281.                             'type' => 'validation_error'
  282.                         ];
  283.                 }
  284.                 continue;
  285.             }
  286.             if (!array_key_exists($requiredParameter$postData)) {
  287.                 $errors[] = [
  288.                     'field' => $requiredParameter,
  289.                     'message' => 'This value is required',
  290.                     'type' => 'validation_error'
  291.                 ];
  292.             }
  293.         }
  294.         if (!empty($errors)) {
  295.             throw new MissingApiParamsException('Missing params!'$errors);
  296.         }
  297.     }
  298.     /**
  299.      * Terminate with response
  300.      *
  301.      * @param Response $response
  302.      */
  303.     private function terminateWithResponse(Response $response)
  304.     {
  305.         $request $this->get('request_stack')->getCurrentRequest();
  306.         $response->headers->set('Access-Control-Allow-Origin''*');
  307.         $response->headers->set('Access-Control-Allow-Methods''OPTIONS,GET,POST,PUT,PATCH,DELETE');
  308.         $response->send();
  309.         $this->get('kernel')->terminate($request$response);
  310.         exit();
  311.     }
  312.     /**
  313.      *
  314.      * @param $id
  315.      * @param array $parameters
  316.      * @param null $domain
  317.      * @param null $locale
  318.      * @return string
  319.      */
  320.     public function translate($id, array $parameters = array(), $domain null$locale null)
  321.     {
  322.         $this->get('translator')->trans($id$parameters$domain$locale);
  323.     }
  324.     /**
  325.      * Get full base url
  326.      *
  327.      * @return string
  328.      */
  329.     protected function getFullBaseUrl()
  330.     {
  331.         return $this->get('request_stack')->getCurrentRequest()->getSchemeAndHttpHost();
  332.     }
  333.     /**
  334.      * Check if user is logged in
  335.      *
  336.      * @return bool
  337.      */
  338.     protected function isLoggedIn()
  339.     {
  340.         try {
  341.             return $this->get('security.authorization_checker')->isGranted('ROLE_USER');
  342.         } catch (\Exception $e) {
  343.             return false;
  344.         }
  345.     }
  346.     /**
  347.      * Check if authenticated user is admin
  348.      *
  349.      * @return bool
  350.      */
  351.     protected function isAdmin()
  352.     {
  353.         try {
  354.             return $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN');
  355.         } catch (\Exception $e) {
  356.             return false;
  357.         }
  358.     }
  359.     /**
  360.      * Set data in controller
  361.      *
  362.      * @param $data
  363.      */
  364.     public function setData($data)
  365.     {
  366.         $this->data $data;
  367.     }
  368.     /**
  369.      * Validate post params
  370.      *
  371.      * @param $fields
  372.      */
  373.     public function validatePostParams($fields)
  374.     {
  375.         $data $this->data;
  376.         $request $this->get('request_stack')->getCurrentRequest();
  377.         $form $this->createFormBuilder();
  378.         foreach($fields as $field) {
  379.         }
  380.     }
  381.     /**
  382.      * Get pagination params
  383.      *
  384.      * @return array
  385.      */
  386.     public function getPaginationParams($defaultOffset 0$defaultLimit 20)
  387.     {
  388.         if(isset($this->data['offset'])){
  389.             $offset $this->data['offset'];
  390.         }else{
  391.             $offset $defaultOffset;
  392.         }
  393.         if(isset($this->data['limit'])){
  394.             $limit $this->data['limit'];
  395.         }else{
  396.             $limit $defaultLimit;
  397.         }
  398.         return compact('offset''limit');
  399.     }
  400.     /**
  401.      * Validate request
  402.      *
  403.      * @param $validatorClass
  404.      * @return mixed $validatorClass
  405.      * @throws MissingApiParamsException
  406.      */
  407.     protected function validateRequest($validatorClass)
  408.     {
  409.         return $this->baseService->validateRequest($validatorClass$this->data);
  410.     }
  411. }