示例#1
0
 /**
  * @param Document $document
  * @return ViewBuilder
  */
 public function setDocument(Document $document)
 {
     $this->singleDocument = $document;
     $resourceClass = $this->resourceClass;
     $this->view->setData($resourceClass::createFromReadModel($document));
     return $this;
 }
 public function showAction(Request $request, $exception, DebugLoggerInterface $logger = null)
 {
     $view = new View();
     $view->setData(json_decode($exception->getMessage(), true));
     $view->setFormat('json');
     return $this->container->get('fos_rest.view_handler')->handle($view);
 }
示例#3
0
 public function postAction()
 {
     $todos = $this->getDoctrine()->getRepository('AppBundle:Todo')->findAll();
     $view = new View();
     $view->setData($todos);
     return $this->handleView($view);
 }
 /**
  * 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);
 }
 protected function createView($returnData)
 {
     $view = new View();
     $view->setData($returnData);
     $view->setStatusCode($returnData['status']);
     $view->setFormat('json');
     return $view;
 }
 public function validationFailureAction()
 {
     $validator = $this->validator;
     $article = new Article();
     //$article->setPath('/foo');
     $article->setTitle('The path was set');
     $article->setBody('Disable the setPath() call to get a validation error example');
     $view = new View();
     $errors = $validator->validate($article);
     if (count($errors)) {
         $view->setStatusCode(400);
         $view->setData($errors);
     } else {
         $view->setData($article);
     }
     return $this->viewHandler->handle($view);
 }
 /**
  * alternatively use class="LiipHelloBundle:Article", but this has a bit more overhead
  *
  * @ParamConverter("article", class="Liip\HelloBundle\Document\Article")
  */
 public function converterAction(Article $article = null)
 {
     $view = new View();
     $view->setTemplate(new TemplateReference('LiipHelloBundle', 'Hello', 'index'));
     $name = $article ? 'found: ' . $article->getTitle() : 'No found';
     $view->setData(array('name' => $name));
     $viewHandler = $this->container->get('my_view');
     return $viewHandler->handle($view);
 }
 /**
  * @ApiDoc(
  *   resource = true,
  *   description = "Retrieves the health authority data for a postcode",
  *   statusCodes = {
  *     200 = "Returned when successful",
  *     400 = "Returned when there is a data error",
  *     404 = "Returned when no entities are found"
  *   }
  * )
  *
  * @param string $postcode
  * @return View
  */
 public function getAuthorityAction($postcode)
 {
     $result = $this->getService()->findByPostCode(strtolower(str_replace(' ', '', $postcode)));
     $view = new View();
     $view->setData($result);
     if (!count($result)) {
         $view->setStatusCode(404);
     }
     return $view;
 }
示例#9
0
 /**
  * Lists all Article entities.
  *
  */
 public function indexAction()
 {
     //echo phpinfo(); die;
     $em = $this->getDoctrine()->getManager();
     $entities = $em->getRepository('MwRestBundle:Article')->findAll();
     $view = new View();
     $view->setData($entities);
     $view->setTemplateVar('entities');
     $view->setTemplate('MwRestBundle:Article:index.html.twig');
     return $this->container->get('fos_rest.view_handler')->handle($view);
 }
示例#10
0
 /**
  * @param ViewHandler   $handler
  * @param View          $view
  * @param Request       $request
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function createResponse(ViewHandler $handler, View $view, Request $request)
 {
     $format = $view->getFormat() ?: $request->getRequestFormat();
     $data = $view->getData();
     if ($data instanceof Cursor) {
         $view->setData(iterator_to_array($data, false));
         $view->getResponse()->headers->set('X-Total-Count', $data->count());
         return $handler->createResponse($view, $request, $view->getFormat());
     }
     if ($data instanceof Form && Codes::HTTP_BAD_REQUEST === $view->getStatusCode()) {
         $view->setData($this->formatFormErrors($data));
         return $handler->createResponse($view, $request, $format);
     }
     return $handler->createResponse($view, $request, $format);
 }
示例#11
0
 /**
  * @ApiDoc
  *
  * @param integer $objectId            
  * @throws NotFoundHttpException
  */
 public function getUserAction($userId = 0)
 {
     /* @var $model \App\ModuleObjectsBundle\Model\MapObjectModel */
     $model = $this->container->get('app_module_user.model.user');
     $data = $model->findOneById($userId);
     if (null === $data) {
         throw new NotFoundHttpException();
     }
     $view = new View();
     $view->setData($data);
     $context = new SerializationContext();
     $context->setGroups(array('.all', 'user.get'));
     $view->setSerializationContext($context);
     return $this->viewHandler->handle($view);
 }
 /**
  * Renders the parameters and template and initializes a new response object with the
  * rendered content.
  *
  * @param GetResponseForControllerResultEvent $event A GetResponseForControllerResultEvent instance
  */
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $request = $event->getRequest();
     $view = $event->getControllerResult();
     if (!$view instanceof View) {
         if (!$request->attributes->get('_view') && !$this->container->getParameter('fos_rest.view_response_listener.force_view')) {
             return;
         }
         $view = new View($view);
     }
     if (null === $view->getFormat()) {
         $view->setFormat($request->getRequestFormat());
     }
     $vars = $request->attributes->get('_template_vars');
     if (!$vars) {
         $vars = $request->attributes->get('_template_default_vars');
     }
     if (!empty($vars)) {
         $parameters = $view->getData();
         if (null !== $parameters && !is_array($parameters)) {
             throw new \RuntimeException('View data must be an array if using a templating aware format.');
         }
         $parameters = (array) $parameters;
         foreach ($vars as $var) {
             if (!array_key_exists($var, $parameters)) {
                 $parameters[$var] = $request->attributes->get($var);
             }
         }
         $view->setData($parameters);
     }
     $viewHandler = $this->container->get('fos_rest.view_handler');
     if ($viewHandler->isFormatTemplating($view->getFormat())) {
         $template = $request->attributes->get('_template');
         if ($template) {
             if ($template instanceof TemplateReference) {
                 $template->set('format', null);
                 $template->set('engine', null);
             }
             $view->setTemplate($template);
         }
     }
     $response = $viewHandler->handle($view, $request);
     $event->setResponse($response);
 }
 /**
  * @param IsIdentifiable $viewData
  * @param string         $grouping
  * @return View
  */
 protected function setViewData(IsIdentifiable $viewData, $grouping = self::DEFAULT_API_GROUPING)
 {
     $this->view->setData($viewData);
     $this->setGrouping($grouping);
     return $this->view;
 }
 /**
  * @dataProvider prepareTemplateParametersDataProvider
  */
 public function testPrepareTemplateParametersWithProvider($viewData, $expected)
 {
     $handler = new ViewHandler();
     $view = new View();
     $view->setData($viewData);
     $this->assertEquals($expected, $handler->prepareTemplateParameters($view));
 }
 /**
  * @ApiDoc(
  *   resource = true,
  *   description = "Adds a website the district council data set",
  *   statusCodes = {
  *     200 = "Returned when successful",
  *     400 = "Returned when there is a data error",
  *     404 = "Returned when no entities are found"
  *   }
  * )
  *
  * @param string       $entityCode
  * @param ParamFetcher $paramFetcher
  *
  * @RequestParam(name="url", nullable=false, strict=true, description="The url of the district council website")
  * @RequestParam(name="council_name", nullable=false, strict=true, description="The display name for the disctrict council")
  *
  * @return View
  */
 public function putDistrictCouncilDetailsAction($entityCode, ParamFetcher $paramFetcher)
 {
     /** @var DistrictCouncil $result */
     $result = $this->getService()->findByEntityCode(new DistrictCouncil($entityCode, ''));
     $result->setDistrictCouncilName($paramFetcher->get('council_name'))->setWebsite($paramFetcher->get('url'))->setLastUpdated(new \DateTime());
     $result = $this->getService()->saveDistrictCouncil($result);
     $view = new View();
     $view->setData($result);
     if (null === $result->getId()) {
         $view->setStatusCode(404);
     }
     return $view;
 }
示例#16
0
 protected function configError(View $view, $message, $typeMessage, $status)
 {
     $view->setData(array('data' => array(array('texte' => $message, 'typeAlert' => $typeMessage))))->setStatusCode($status);
     return $view;
 }
 /**
  * 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);
 }
 /**
  * @dataProvider statusCodeProvider
  */
 public function testStatusCode($annotationCode, $viewCode, $expectedCode)
 {
     $this->createViewResponseListener(['json' => true]);
     $viewAnnotation = new ViewAnnotation([]);
     $viewAnnotation->setStatusCode($annotationCode);
     $request = new Request();
     $request->setRequestFormat('json');
     $request->attributes->set('_view', $viewAnnotation);
     $this->templating->expects($this->any())->method('render')->will($this->returnValue('foo'));
     $view = new View();
     $view->setStatusCode($viewCode);
     $view->setData('foo');
     $event = $this->getResponseEvent($request, $view);
     $response = new Response();
     $event->expects($this->any())->method('setResponse')->will($this->returnCallback(function ($r) use(&$response) {
         $response = $r;
     }));
     $this->listener->onKernelView($event);
     $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Response', $response);
     $this->assertSame($expectedCode, $response->getStatusCode());
 }
示例#19
0
 /**
  * @dataProvider prepareTemplateParametersDataProvider
  */
 public function testPrepareTemplateParametersWithProvider($viewData, $templateData, $expected)
 {
     $handler = new ViewHandler(array('html' => true));
     $view = new View();
     $view->setFormat('html');
     $view->setData($viewData);
     if (null !== $templateData) {
         $view->setTemplateData($templateData);
     }
     $this->assertEquals($expected, $handler->prepareTemplateParameters($view));
 }
示例#20
0
 /**
  * @dataProvider prepareTemplateParametersDataProvider
  */
 public function testPrepareTemplateParametersWithProvider($viewData, $templateData, $expected)
 {
     $handler = $this->createViewHandler(['html' => true]);
     $handler->setSerializationContextAdapter($this->getMock('FOS\\RestBundle\\Context\\Adapter\\SerializationContextAdapterInterface'));
     $view = new View();
     $view->setFormat('html');
     $view->setData($viewData);
     if (null !== $templateData) {
         $view->setTemplateData($templateData);
     }
     $this->assertEquals($expected, $handler->prepareTemplateParameters($view));
 }
示例#21
0
 /**
  * @param View $view
  */
 private function unwrapViewData(View $view)
 {
     $view->setData($this->unwrapIfCollaborator($view->getData()));
 }
 /**
  * Get advanced search result.
  *
  * Supported Keywords:
  *
  *   from: List of entity aliases to search from. It can be one alias or group
  *
  *   where: Auxiliary keyword for visual separation 'from' block from search parameters
  *
  *   and, or: Used to combine multiple clauses, allowing you to refine your search.
  *
  * Syntax: and(or) field_type field_name operator value
  *
  *   offset: Allow to set offset of first result.
  *
  *   max_results: Set results count for the query.
  *
  *   order_by: Allow to set results order. Syntax: order_by field_type field_name direction
  *
  * Supported keywords:
  *
  *  text
  *
  *  integer
  *
  *  decimal
  *
  *  datetime
  *
  * Operators:
  *
  *  ~, !~ Work only with string fields. Used for set text field value / search strings without value.
  *
  *  =  Used for search records where field matches the specified value.
  *
  *  != used for search records where field does not matches the specified value.
  *
  *  >, <, <=, >= Operators is used to search for the records that have the specified field must be greater, less,
  * than, less than equals, or greater than equals of the specified value
  *
  *  in Used for search records where field in the specified set of data
  *
  *  !in Used for search records where field not in the specified set of data
  *
  * Examples:
  *
  *  from demo_product where name ~ samsung and double price > 100
  *
  *  integer count != 10
  *
  *  all_text !~ "test string"
  *
  *  from (demo_products, demo_categories) where description ~ test order_by name offset 5 max_results 10
  *
  *  integer count !in (1, 3, 5)
  *
  * @ApiDoc(
  *  description="Get advanced search result.",
  *  resource=true,
  *  filters={
  *      {"name"="query", "dataType"="string"}
  *  }
  * )
  * @AclAncestor("oro_search")
  */
 public function getAction()
 {
     $view = new View();
     return $this->get('fos_rest.view_handler')->handle($view->setData($this->get('oro_search.index')->advancedSearch($this->getRequest()->get('query'))->toSearchResultData()));
 }
示例#23
0
 /**
  * @dataProvider setDataDataProvider
  */
 public function testSetData($data)
 {
     $view = new View();
     $view->setData($data);
     $this->assertEquals($data, $view->getData());
 }
 /**
  * @param Response     $response
  * @param ParameterBag $parameterBag
  * @return bool|void
  */
 protected function doExecute(Response $response, ParameterBag $parameterBag)
 {
     /** @var Request $request */
     /** @var AbstractType $formType */
     /** @var object $entity */
     /** @var bool $cleanForm */
     /** @var bool $cleanRequestData */
     /** @var bool $getContent */
     /** @var array $formOptions */
     /** @var SerializationContext $serializationContext */
     /** @var \Closure $onPreValidation */
     /** @var \Closure $onPostValidation */
     /** @var \Closure $onPostPersist */
     /** @var \Closure $onSuccess */
     /** @var \Closure $onFailure  */
     $request = $parameterBag->get('request');
     $formType = $parameterBag->get('formType');
     $entity = $parameterBag->get('entity');
     $cleanForm = $parameterBag->get('cleanForm');
     $cleanRequestData = $parameterBag->get('cleanRequestData', true);
     $getContent = $parameterBag->get('getContent');
     $formOptions = $parameterBag->get('formOptions', array());
     $serializationContext = $parameterBag->get('serializationContext');
     $onPreValidation = $parameterBag->get('onPreValidation');
     $onPostValidation = $parameterBag->get('onPostValidation');
     $onPostPersist = $parameterBag->get('onPostPersist');
     $onSuccess = $parameterBag->get('onSuccess');
     $onFailure = $parameterBag->get('onFailure ');
     $view = new View();
     $httpResponse = $view->getResponse();
     $requestData = array_merge($request->request->all(), $request->files->all());
     if ($serializationContext) {
         $view->setSerializationContext($serializationContext);
     }
     $form = $this->getFormFactory()->createNamed(null, get_class($formType), $entity, array_merge(array('csrf_protection' => false), $formOptions));
     if ($cleanRequestData) {
         $requestData = $this->cleanRequestData($requestData, $form);
     }
     if ($cleanForm) {
         $this->cleanForm($requestData, $form);
     }
     $this->prepareFormCollections($request, $form);
     /**
      * Pre validation
      */
     $this->onPreValidation($request, $form, $entity, $httpResponse);
     if ($onPreValidation instanceof \Closure) {
         $onPreValidation($request, $form, $entity, $httpResponse);
     }
     if ($httpResponse->getStatusCode() != HttpResponse::HTTP_OK) {
         $response->response = $view;
         return true;
     }
     $form->submit($requestData);
     if ($form->isValid()) {
         if ($onPostValidation instanceof \Closure) {
             $onPostValidation($request, $form, $entity, $httpResponse);
             if ($httpResponse->getStatusCode() != HttpResponse::HTTP_OK) {
                 $response->response = $view;
                 return true;
             }
         }
         $isEditAction = $entity->getId();
         $statusCode = $isEditAction ? HttpResponse::HTTP_OK : HttpResponse::HTTP_CREATED;
         /** @var \Doctrine\Common\Persistence\ObjectManager $em */
         $em = $this->getDoctrine()->getManager();
         $em->persist($entity);
         if ($onPostPersist instanceof \Closure) {
             $onPostPersist($request, $form, $entity, $httpResponse);
         }
         $em->flush();
         $httpResponse->setStatusCode($statusCode);
         if ($isEditAction) {
             if ($getContent) {
                 $em->refresh($entity);
                 $view->setData($entity);
             }
         } else {
             $view->setData($entity->getId());
         }
         if ($onSuccess instanceof \Closure) {
             $onSuccess($request, $form, $entity, $httpResponse);
         }
         $response->response = $view;
         return true;
     }
     if ($onFailure instanceof \Closure) {
         $onFailure($request, $form, $entity, $httpResponse);
         $response->response = $view;
         return true;
     }
     $response->response = $form;
     return false;
 }
 /**
  * Get advanced search result.
  *
  * Supported Keywords:
  *
  *   from: List of entity aliases to search from. It can be one alias or group
  *
  *   where: Auxiliary keyword for visual separation 'from' block from search parameters
  *
  *   and, or: Used to combine multiple clauses, allowing you to refine your search.
  *
  * Syntax: and(or) field_type field_name operator value
  *
  *   offset: Allow to set offset of first result.
  *
  *   max_results: Set results count for the query.
  *
  *   order_by: Allow to set results order. Syntax: order_by field_type field_name direction
  *
  * Supported keywords:
  *
  *  text
  *
  *  integer
  *
  *  decimal
  *
  *  datetime
  *
  * Operators:
  *
  *  ~, !~ Work only with string fields. Used for set text field value / search strings without value.
  *
  *  =  Used for search records where field matches the specified value.
  *
  *  != used for search records where field does not matches the specified value.
  *
  *  >, <, <=, >= Operators is used to search for the records that have the specified field must be greater, less,
  * than, less than equals, or greater than equals of the specified value
  *
  *  in Used for search records where field in the specified set of data
  *
  *  !in Used for search records where field not in the specified set of data
  *
  *  replace spaces with _ underscore for fulltext search
  *
  * Examples:
  *
  *  from demo_product where name ~ samsung and double price > 100
  *
  *  where integer count != 10
  *
  *  where all_text !~ test_string
  *
  *  from demo_products where description ~ test order_by name offset 5
  *
  *  from (demo_products, demo_categories) where description ~ test offset 5 max_results 10
  *
  *  integer count !in (1, 3, 5)
  *
  * @ApiDoc(
  *  description="Get advanced search result.",
  *  resource=true,
  *  filters={
  *      {"name"="query", "dataType"="string"}
  *  }
  * )
  * @AclAncestor("oro_search")
  */
 public function getAction()
 {
     $view = new View();
     $result = $this->get('oro_search.index')->advancedSearch($this->getRequest()->get('query'));
     $dispatcher = $this->container->get('event_dispatcher');
     foreach ($result->getElements() as $item) {
         $dispatcher->dispatch(PrepareResultItemEvent::EVENT_NAME, new PrepareResultItemEvent($item));
     }
     return $this->get('fos_rest.view_handler')->handle($view->setData($result->toSearchResultData()));
 }
 /**
  * @dataProvider statusCodeProvider
  */
 public function testStatusCode($annotationCode, $viewCode, $expectedCode)
 {
     $viewAnnotation = new ViewAnnotation([]);
     $viewAnnotation->setStatusCode($annotationCode);
     $request = new Request();
     $request->setRequestFormat('json');
     $request->attributes->set('_view', $viewAnnotation);
     $this->viewHandler = new ViewHandler(['json' => 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->templating->expects($this->any())->method('render')->will($this->returnValue('foo'));
     $view = new View();
     $view->setStatusCode($viewCode);
     $view->setData('foo');
     $event = $this->getResponseEvent($request, $view);
     $response = new Response();
     $event->expects($this->any())->method('setResponse')->will($this->returnCallback(function ($r) use(&$response) {
         $response = $r;
     }));
     $this->listener->onKernelView($event);
     $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Response', $response);
     $this->assertSame($expectedCode, $response->getStatusCode());
 }