/**
  * Returns a Response for the validation failures.
  *
  * @param mixed $input
  * @param ConstraintViolationListInterface $violations
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getErrorResponse($input, ConstraintViolationListInterface $violations)
 {
     $error = new ValidationErrors();
     $error->input = $input;
     $error->violations = $violations;
     return $this->viewHandler->handle(View::create($error, 400, array(), array('Default', 'view')));
 }
 public function getEntityCollectionFormAction(Request $request)
 {
     $entity = $this->resource->getEntity($request);
     list($rel, $formRel) = $this->getRelsFromEntityCollectionFormRoute($request);
     $formDescription = $this->resource->createEntityCollectionFormDescription($formRel, $entity, $rel);
     $formRepresentation = $this->formNormalizer->normalizeFormDescription($formDescription);
     return $this->viewHandler->handle(View::create($formRepresentation));
 }
Esempio n. 3
0
 protected function renderResponse($contentTemplate, $params)
 {
     if ($this->viewHandler) {
         $view = new View($params);
         $view->setTemplate($contentTemplate);
         return $this->viewHandler->handle($view);
     }
     return $this->templating->renderResponse($contentTemplate, $params);
 }
 /**
  * @dataProvider providePermissionData
  */
 public function testPostAction($id, $class, $permissions)
 {
     $request = new Request([], ['id' => $id, 'type' => $class, 'permissions' => [1 => $permissions]]);
     array_walk($permissions, function (&$permissionLine) {
         $permissionLine = $permissionLine === 'true' || $permissionLine === true;
     });
     $this->viewHandler->handle(View::create(['id' => $id, 'type' => $class, 'permissions' => [1 => $permissions]]))->shouldBeCalled();
     $this->permissionController->postAction($request);
 }
 public function testCGetActionWithUnexistingAlias()
 {
     $query = ['alias' => 'not_existent_alias'];
     $request = new Request($query);
     $contentNavigationAliasNotFoundException = new ContentNavigationAliasNotFoundException($query['alias'], []);
     $this->contentNavigationCollector->getNavigationItems(Argument::cetera())->willThrow($contentNavigationAliasNotFoundException);
     $exception = new RestException($contentNavigationAliasNotFoundException->getMessage(), 0, $contentNavigationAliasNotFoundException);
     $this->viewHandler->handle(View::create($exception->toArray(), 404))->shouldBeCalled();
     $this->contentNavigationController->cgetAction($request);
 }
 /**
  * Handle article PUT
  */
 public function putDocumentAction(Request $request, $subject)
 {
     if ($this->securityContext && false === $this->securityContext->isGranted($this->requiredRole)) {
         throw new AccessDeniedException();
     }
     $model = $this->getModelBySubject($request, $subject);
     $type = $this->typeFactory->getTypeByObject($model);
     $result = $this->restHandler->run($request->request->all(), $type, null, RestService::HTTP_PUT);
     $view = View::create($result)->setFormat('json');
     return $this->viewHandler->handle($view, $request);
 }
Esempio n. 7
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $mediaType = $request->attributes->get('media_type');
     if (1 === preg_match($this->regex, $mediaType, $matches)) {
         $this->version = $matches['version'];
         $request->attributes->set('version', $this->version);
         if ($this->viewHandler instanceof ConfigurableViewHandlerInterface) {
             $this->viewHandler->setExclusionStrategyVersion($this->version);
         }
     }
 }
 /**
  * Handle article PUT
  */
 public function putDocumentAction(Request $request, $id)
 {
     $path = '/' . $id;
     $data = $request->request->all();
     $session = $this->registry->getConnection($this->name);
     $node = $session->getNode($path);
     if (empty($node)) {
         throw new ResourceNotFoundException($path . ' not found');
     }
     $this->fromJsonLD($node, $data);
     $session->save();
     // return the updated version
     $view = View::create($this->toJsonLd($node))->setFormat('json');
     return $this->viewHandler->handle($view, $request);
 }
Esempio n. 9
0
 public function postAction(Request $request)
 {
     try {
         $identifier = $request->get('id');
         $type = $request->get('type');
         $permissions = $request->get('permissions');
         $securityContext = $request->get('securityContext');
         if (!$identifier) {
             throw new MissingParameterException(static::class, 'id');
         }
         if (!$type) {
             throw new MissingParameterException(static::class, 'class');
         }
         if (!is_array($permissions)) {
             throw new RestException('The "permissions" must be passed as an array');
         }
         if ($securityContext) {
             $this->securityChecker->checkPermission($securityContext, PermissionTypes::SECURITY);
         }
         // transfer all permission strings to booleans
         foreach ($permissions as &$permission) {
             array_walk($permission, function (&$permissionLine) {
                 $permissionLine = $permissionLine === 'true' || $permissionLine === true;
             });
         }
         $this->accessControlManager->setPermissions($type, $identifier, $permissions);
         return $this->viewHandler->handle(View::create(['id' => $identifier, 'type' => $type, 'permissions' => $permissions]));
     } catch (RestException $exc) {
         return $this->viewHandler->handle(View::create($exc->toArray(), 400));
     }
 }
 /**
  * Render js inclusion for create.js and dependencies and bootstrap code.
  *
  * THe hallo editor is bundled with create.js and available automatically.
  * To use aloha, you need to download the zip, as explained in step 8 of
  * the README.
  *
  * @param string $editor the name of the editor to load, currently hallo and aloha are supported
  */
 public function includeJSFilesAction($editor = 'hallo')
 {
     if ($this->securityContext && false === $this->securityContext->isGranted($this->requiredRole)) {
         return new Response('');
     }
     // We could inject a list of names to template mapping for this
     // to allow adding other editors without changing this bundle
     $view = new View();
     switch ($editor) {
         case 'hallo':
             if ($this->coffee) {
                 $view->setTemplate('SymfonyCmfCreateBundle::includecoffeefiles-hallo.html.twig');
             } else {
                 $view->setTemplate('SymfonyCmfCreateBundle::includejsfiles-hallo.html.twig');
             }
             break;
         case 'aloha':
             $view->setTemplate('SymfonyCmfCreateBundle::includejsfiles-aloha.html.twig');
             break;
         default:
             throw new \InvalidArgumentException("Unknown editor '{$editor}' requested");
     }
     $view->setData(array('cmfCreateStanbolUrl' => $this->stanbolUrl, 'cmfCreateImageUploadEnabled' => (bool) $this->imageClass));
     return $this->viewHandler->handle($view);
 }
 /**
  * @dataProvider getDataForDefaultVarsCopy
  */
 public function testViewWithNoCopyDefaultVars($createAnnotation, $populateDefaultVars, $shouldCopy)
 {
     $request = new Request();
     $request->attributes->set('_template_default_vars', ['customer']);
     $request->attributes->set('customer', 'A person goes here');
     $view = View::create();
     if ($createAnnotation) {
         $viewAnnotation = new ViewAnnotation([]);
         $viewAnnotation->setPopulateDefaultVars($populateDefaultVars);
         $request->attributes->set('_view', $viewAnnotation);
     }
     $event = $this->getResponseEvent($request, $view);
     $this->viewHandler = new ViewHandler(['html' => true]);
     $this->viewHandler->setContainer($this->container);
     // This is why we avoid container dependencies!
     $that = $this;
     $this->container->expects($this->exactly(2))->method('get')->with($this->logicalOr('fos_rest.view_handler', 'fos_rest.templating'))->will($this->returnCallback(function ($service) use($that) {
         return $service === 'fos_rest.view_handler' ? $that->viewHandler : $that->templating;
     }));
     $this->listener->onKernelView($event);
     $data = $view->getData();
     if ($shouldCopy) {
         $this->assertArrayHasKey('customer', $data);
         $this->assertEquals('A person goes here', $data['customer']);
     } else {
         $this->assertNull($data);
     }
 }
Esempio n. 12
0
 protected function renderResponse($contentTemplate, $params)
 {
     if ($this->viewHandler) {
         if (1 === count($params)) {
             $templateVar = key($params);
             $params = reset($params);
         }
         $view = $this->getView($params);
         if (isset($templateVar)) {
             $view->setTemplateVar($templateVar);
         }
         $view->setTemplate($contentTemplate);
         return $this->viewHandler->handle($view);
     }
     return $this->templating->renderResponse($contentTemplate, $params);
 }
Esempio n. 13
0
 /**
  * Return a JSON encoded scalar array of index names.
  *
  * @return Response
  */
 public function indexesAction()
 {
     return $this->viewHandler->handle(View::create(array_map(function ($indexName) {
         $indexConfiguration = $this->indexConfigurationProvider->getIndexConfiguration($indexName);
         return $indexConfiguration ?: new IndexConfiguration($indexName);
     }, $this->getAllowedIndexes())));
 }
Esempio n. 14
0
 /**
  * Takes a key, value pair and stores it as settings for the user.
  *
  * @param Request $request
  *
  * @return Response
  */
 public function putSettingsAction(Request $request)
 {
     $key = $request->get('key');
     $value = $request->get('value');
     try {
         if (!$key) {
             throw new MissingArgumentException(static::$entityNameUserSetting, 'key');
         }
         if (!$value) {
             throw new MissingArgumentException(static::$entityNameUserSetting, 'value');
         }
         $user = $this->tokenStorage->getToken()->getUser();
         // encode before persist
         $data = json_encode($value);
         // get setting
         // TODO: move this logic into own service (UserSettingManager?)
         $setting = $this->userSettingRepository->findOneBy(['user' => $user, 'key' => $key]);
         // or create new one
         if (!$setting) {
             $setting = new UserSetting();
             $setting->setKey($key);
             $setting->setUser($user);
             $this->objectManager->persist($setting);
         }
         // persist setting
         $setting->setValue($data);
         $this->objectManager->flush();
         //create view
         $view = View::create($setting, 200);
     } catch (RestException $exc) {
         $view = View::create($exc->toArray(), 400);
     }
     return $this->viewHandler->handle($view);
 }
 /**
  * TODO: returns empty response.
  *
  * @param Request $request
  *
  * @return Response
  */
 public function showRelatedAction(Request $request)
 {
     $links = array();
     $data = array('links' => $links);
     $view = View::create($data);
     return $this->viewHandler->handle($view);
 }
 public function get(Request $request)
 {
     $url = $request->query->get('url');
     $forceProtocol = $this->config->getForceProtocol();
     if (!is_null($forceProtocol)) {
         if ($forceProtocol === "https") {
             $url = str_replace('http://', 'https://', $url);
         }
         if ($forceProtocol === "http") {
             $url = str_replace('https://', 'http://', $url);
         }
     }
     $result = $this->shariffService->get($url);
     $view = View::create($result);
     $view->setFormat('json');
     return $this->viewHandler->handle($view);
 }
 /**
  * @param GetResponseForControllerResultEvent $event
  */
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $controllerResult = $event->getControllerResult();
     if ($controllerResult instanceof ResourcesListResponseInterface) {
         $responseContext = $controllerResult->getResponseContext();
         if ($responseContext->getIntention() === ResponseContextInterface::INTENTION_API) {
             $factory = new KnpPaginatorRepresentationFactory();
             $representation = $factory->createRepresentation($controllerResult->getResources(), $event->getRequest());
             $event->setResponse($this->viewHandler->handle(View::create($representation, $responseContext->getStatusCode())));
         }
     } elseif ($controllerResult instanceof SingleResourceResponseInterface) {
         $responseContext = $controllerResult->getResponseContext();
         if ($responseContext->getIntention() === ResponseContextInterface::INTENTION_API) {
             $event->setResponse($this->viewHandler->handle(View::create($controllerResult->getResource(), $responseContext->getStatusCode())));
         }
     }
 }
Esempio n. 18
0
 /**
  * Get available Workflows for a document.
  *
  * @param Request $request
  * @param string  $subject
  *
  * @return Response
  *
  * @throws AccessDeniedException If getting workflows for this document is
  *                               not allowed by the access checker.
  */
 public function workflowsAction(Request $request, $subject)
 {
     if (!$this->accessChecker->check($request)) {
         throw new AccessDeniedException();
     }
     $result = $this->restHandler->getWorkflows($subject);
     $view = View::create($result)->setFormat('json');
     return $this->viewHandler->handle($view, $request);
 }
 /**
  * Manage form submission of an attribute option
  *
  * @param AttributeOptionInterface $attributeOption
  * @param array                    $data
  *
  * @return FormInterface
  */
 protected function manageFormSubmission(AttributeOptionInterface $attributeOption, array $data = [])
 {
     $form = $this->formFactory->createNamed('option', 'pim_enrich_attribute_option', $attributeOption);
     $form->submit($data, false);
     if ($form->isValid()) {
         $this->optionSaver->save($attributeOption);
         $option = $this->normalizer->normalize($attributeOption, 'array', ['onlyActivatedLocales' => true]);
         return new JsonResponse($option);
     }
     return $this->viewHandler->handle(RestView::create($form));
 }
Esempio n. 20
0
 public function showRelatedAction(Request $request)
 {
     $tags = $request->query->get('tags');
     $page = $request->query->get('page');
     $tags = explode(',', $tags);
     $lang = $request->getLocale();
     $data = $this->getPagesByTags($tags, $page, $lang);
     $data = array('links' => $data);
     $view = View::create($data);
     return $this->viewHandler->handle($view);
 }
 /**
  * Render js for VIE and a semantic editor.
  *
  * Hallo is a submodule of this bundle and available after right after you
  * followed the installation instructions.
  * To use aloha, you need to download the zip, as explained in step 8 of
  * the README.
  *
  * @param string $editor the name of the editor to load, currently hallo and aloha are supported
  */
 public function includeJSFilesAction($editor = 'hallo')
 {
     // We could inject a list of names to template mapping for this
     // to allow adding other editors without changing this bundle
     $view = new View();
     switch ($editor) {
         case 'hallo':
             if ($this->coffee) {
                 $view->setTemplate('LiipVieBundle::includecoffeefiles-hallo.html.twig');
             } else {
                 $view->setTemplate('LiipVieBundle::includejsfiles-hallo.html.twig');
             }
             break;
         case 'aloha':
             $view->setTemplate('LiipVieBundle::includejsfiles-aloha.html.twig');
             break;
         default:
             throw new \InvalidArgumentException("Unknown editor '{$editor}' requested");
     }
     return $this->viewHandler->handle($view);
 }
 /**
  * @param GetResponseForExceptionEvent $event
  */
 public function onResourceDelete(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     if (!$exception instanceof ForeignKeyConstraintViolationException) {
         return;
     }
     $requestAttributes = $event->getRequest()->attributes;
     $originalRoute = $requestAttributes->get('_route');
     $resourceName = $this->getResourceNameFromRoute($originalRoute);
     if (!$this->isHtmlRequest($event->getRequest())) {
         $event->setResponse($this->viewHandler->handle(View::create(['error' => ['code' => $exception->getSQLState(), 'message' => $this->translator->trans('sylius.resource.delete_error', ['%resource%' => $resourceName], 'flashes')]], 409)));
         return;
     }
     if (null === $requestAttributes->get('_controller')) {
         return;
     }
     $this->session->getBag('flashes')->add('error', $this->translator->trans('sylius.resource.delete_error', ['%resource%' => $resourceName], 'flashes'));
     $referrer = $event->getRequest()->headers->get('referer');
     if (null !== $referrer) {
         $event->setResponse(new RedirectResponse($referrer));
         return;
     }
     $event->setResponse($this->createRedirectResponse($originalRoute, ResourceActions::INDEX));
 }
 /**
  * Render javascript HTML tags for create.js and dependencies and bootstrap
  * javscript code.
  *
  * This bundle comes with templates for ckeditor, hallo and to develop on
  * the hallo coffeescript files.
  *
  * To use a different editor simply create a template following the naming
  * below:
  *   CmfCreateBundle::includejsfiles-%editor%.html.twig
  * and pass the appropriate editor name.
  *
  * @param Request $request The request object for the AccessChecker.
  * @param string  $editor  the name of the editor to load.
  */
 public function includeJSFilesAction(Request $request, $editor = 'ckeditor')
 {
     if (!$this->accessChecker->check($request)) {
         return new Response('');
     }
     $view = new View();
     $view->setTemplate(sprintf('CmfCreateBundle::includejsfiles-%s.html.twig', $editor));
     if ($this->browserFileHelper) {
         $helper = $this->browserFileHelper->getEditorHelper($editor);
         $browseUrl = $helper ? $helper->getUrl() : false;
     } else {
         $browseUrl = false;
     }
     $view->setData(array('cmfCreateEditor' => $editor, 'cmfCreateStanbolUrl' => $this->stanbolUrl, 'cmfCreateImageUploadEnabled' => (bool) $this->imageUploadEnabled, 'cmfCreateFixedToolbar' => (bool) $this->fixedToolbar, 'cmfCreatePlainTextTypes' => json_encode($this->plainTextTypes), 'cmfCreateEditorBasePath' => $this->editorBasePath, 'cmfCreateBrowseUrl' => $browseUrl));
     return $this->viewHandler->handle($view);
 }
Esempio n. 24
0
 /**
  * Deletes a user setting by a given key.
  *
  * @param Request $request
  *
  * @return Response
  */
 public function deleteSettingsAction(Request $request)
 {
     $key = $request->get('key');
     try {
         if (!$key) {
             throw new MissingArgumentException(static::$entityNameUserSetting, 'key');
         }
         $user = $this->tokenStorage->getToken()->getUser();
         // get setting
         // TODO: move this logic into own service (UserSettingManager?)
         $setting = $this->userSettingRepository->findOneBy(['user' => $user, 'key' => $key]);
         if ($setting) {
             $this->objectManager->remove($setting);
             $this->objectManager->flush();
             $view = View::create(null, 204);
         } else {
             $view = View::create(null, 400);
         }
     } catch (RestException $exc) {
         $view = View::create($exc->toArray(), 400);
     }
     return $this->viewHandler->handle($view);
 }
Esempio n. 25
0
 public function indexAction()
 {
     $rootRepresentation = $this->createRootRepresentation();
     return $this->viewHandler->handle(View::create($rootRepresentation));
 }