本文整理汇总了PHP中FOS\RestBundle\View\View::create方法的典型用法代码示例。如果您正苦于以下问题:PHP View::create方法的具体用法?PHP View::create怎么用?PHP View::create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类FOS\RestBundle\View\View
的用法示例。
在下文中一共展示了View::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: liquidacion
/**
* @param Request $request
* @param $id
* @return View
*/
public function liquidacion(Request $request, $id)
{
/** @var ServicioOperativo $servicio */
$servicio = $this->get($id);
if (!$servicio) {
throw new NotFoundHttpException("No existe el servicio '{$id}'");
}
$liquidacion = new Liquidacion();
$olds = array();
if ($servicio) {
foreach ($servicio->getLiquidaciones() as $l) {
$olds[$l->getId()] = $l;
}
}
$form = $this->getFormfactory()->create(new LiquidacionType(), $liquidacion);
$form->submit($request->request->all());
if ($form->isValid()) {
/** @var EntregaOperacion $entregaOperativo */
/** @var EntregaOperacion $l */
foreach ($liquidacion->getLiquidaciones() as $entregaOperativo) {
if (isset($olds[$entregaOperativo->getId()])) {
$l = $olds[$entregaOperativo->getId()];
$l->setCantidad($entregaOperativo->getCantidad());
$this->getEm()->persist($l);
} else {
$this->getEm()->persist($entregaOperativo);
}
}
$this->getEm()->flush();
return View::create()->setStatusCode(Codes::HTTP_NO_CONTENT);
}
return View::create($form)->setStatusCode(Codes::HTTP_BAD_REQUEST);
}
示例2: postUserConsentAction
/**
* @param Request $request
* @return View
*/
public function postUserConsentAction(Request $request)
{
$practoAccountId = $this->authenticate(true);
$userManager = $this->get('consult.user_manager');
$userConsent = $userManager->setConsultEnabled($practoAccountId);
return View::create(array("consent" => $userConsent));
}
示例3: putAction
/**
* Change user password
*
* @View(serializerEnableMaxDepthChecks=true)
*
* @Put("/profile/change-password", name="_change_password_profile")
*
* @param Request $request
* @param $entity
*
* @return Response
*/
public function putAction(Request $request)
{
$request->request->set('current_password', $request->request->get('currentPassword'));
$entity = $this->getUser();
if (!is_object($entity) || !$entity instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
/** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$event = new GetResponseUserEvent($entity, $request);
$dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
$changePasswordType = $this->get('app.change_password.form.type');
try {
$request->setMethod('PATCH');
//Treat all PUTs as PATCH
$form = $this->createForm($changePasswordType, $entity, array('method' => $request->getMethod(), 'validation_groups' => array('ChangePassword', 'Default')));
$this->removeExtraFields($request, $form);
$form->handleRequest($request);
if ($form->isValid()) {
/** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
$userManager->updateUser($entity);
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);
}
}
示例4: postDarshansAction
public function postDarshansAction()
{
$postData = $this->getRequest()->request->all();
$darshanManager = $this->get('abhay_api.darshan_manager');
$darshan = $darshanManager->add($postData);
return View::create($darshan->serialise(), Codes::HTTP_CREATED);
}
示例5: _processForm
private function _processForm(User $user)
{
$statusCode = $user->isNew() ? 201 : 204;
$form = $this->createForm(new UserType(), $user);
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$factory = $this->get('security.encoder_factory');
/** @var ObjectManager $em */
$em = $this->getDoctrine()->getManager();
/** @var PasswordEncoderInterface $encoder */
$encoder = $factory->getEncoder($user);
$data = $form->getData();
try {
$user->createNewAccount($encoder, $em, $data->getEmail(), $data->getPassword());
$response = new Response();
$response->setStatusCode($statusCode);
// set the `Location` header only when creating new resources
if (201 === $statusCode) {
$response->headers->set('Location', $this->generateUrl('api_user_get', array('id' => $user->getId()), true));
}
return $response;
} catch (\PDOException $e) {
$form->addError(new FormError("Same user already exists!"));
}
}
return View::create($form, 400);
}
示例6: searchJsonAction
/**
* @param Request $request
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function searchJsonAction(Request $request)
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$keyword = $request->get('keyword');
$results = $this->get('dos.repository.tag')->search($keyword) ?: array();
return $this->viewHandler->handle($configuration, View::create($results));
}
示例7: indexAction
public function indexAction()
{
$view = View::create();
$view->setData(array('date' => date('r'), 'name' => 'some name'));
$view->setTemplate('APIUserBundle:Default:index.html.twig')->setTemplateData(array('name' => 'some name'));
return $view;
}
示例8: indexAction
public function indexAction(Request $request)
{
$view = View::create();
$data = ['test' => 'test'];
$view->setData($data)->setTemplateData(['testtemplate' => 'testtemplate']);
return $view;
}
示例9: postBlogsAction
/**
* Creates a new Blog - need admin previlage
*
* @param ParamFetcher $paramFetcher Paramfetcher
*
* @RequestParam(name="title", requirements=".*", default="", description="Title.")
* @RequestParam(name="blog", requirements=".*", default="", description="Text.")
* @RequestParam(name="tags", requirements=".*", default="", description="tags - comma seperated.")
*
* @return FOSView
* @Secure(roles="ROLE_ADMIN")
* @ApiDoc()
*/
public function postBlogsAction(ParamFetcher $paramFetcher)
{
$blog = new Blog();
$form = $this->createFormBuilder($blog, array('csrf_protection' => false))->add('title')->add('blog')->add('tags')->getForm();
//$form = $this->createForm(new BlogType(), $blog);
if (trim($paramFetcher->get('title')) == '') {
throw new HttpException(400, 'Enter title.');
}
if (trim($paramFetcher->get('blog')) == '') {
throw new HttpException(400, 'Enter blog.');
}
if (trim($paramFetcher->get('tags')) == '') {
throw new HttpException(400, 'Enter tags.');
}
if ($this->getRequest()->getMethod() == 'POST') {
$form->bindRequest($this->getRequest());
$blog->setBlog($paramFetcher->get('blog'));
$blog->setTags($paramFetcher->get('tags'));
$blog->setTitle($paramFetcher->get('title'));
$blog->setAuthor($this->get('security.context')->getToken()->getUser());
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($blog);
$em->flush();
} else {
return FOSView::create($this->getErrorMessages($form), 400);
}
}
return FOSView::create($blog, 200);
}
示例10: planillaAction
/**
* @Pdf(
* stylesheet="SisesApplicationBundle:PDF\PDF:planilla_style.pdf.twig",
* enableCache=true,
* headers={"Content-Type":"application/pdf", "Content-Disposition"="attachment"}
* )
*
* @param $id
* @param $date
*
* @return array
*/
public function planillaAction($id, $date = null)
{
$ea = $this->getEm()->getRepository('SisesApplicationBundle:Entrega\\EntregaAsignacion')->find($id);
if ($ea) {
$asignacion = $ea->getAsignacion();
$personas = $this->getEm()->getRepository('SisesApplicationBundle:Beneficio')->getPersonasDeAsignacion($asignacion);
if ($date) {
try {
$date = new \DateTime($date . '-1');
} catch (\Exception $e) {
throw new NotFoundHttpException("Fecha no disponible");
}
} else {
$date = new \DateTime();
}
$start = new \DateTime($date->format('1-m-Y'));
$end = new \DateTime($date->format('t-m-Y'));
$days = array();
while ($start <= $end) {
$days[] = $start->format('d');
$start->add(new \DateInterval('P1D'));
}
return View::create(array('contrato' => $asignacion->getServicio()->getContrato(), 'lugar' => $asignacion->getLugar()->getNombre(), 'ubicacion' => $asignacion->getLugar()->getUbicacion()->getNombreDetallado(), 'servicio' => $asignacion->getServicio()->getNombre(), 'per_page' => 25, 'date' => $date, 'days' => $days, 'personas' => $personas))->setTemplate('SisesApplicationBundle:PDF\\PDF:planilla.pdf.twig');
}
throw new NotFoundHttpException("Entrega asignacion no encontrada");
}
示例11: processForm
/**
* Processes the form and build the Response object
*
* @param Request $request
* @param Organization $organization
* @return Response|static
* @throws BadRequestHttpException
*/
public function processForm(Request $request, Organization $organization)
{
$statusCode = !$this->em->contains($organization) ? 201 : 204;
$form = $this->container->get('form.factory')->create(OrganizationType::class, $organization);
$formData = json_decode($request->getContent(), true);
$form->submit($this->prepareFormData($formData));
if (!$form->isValid()) {
return View::create($form, 400);
}
if (!$this->em->contains($organization)) {
$this->em->persist($organization);
}
try {
$this->em->flush();
} catch (\Exception $e) {
$pdoException = $e->getPrevious();
// unique constraint
if ($pdoException->getCode() === '23000') {
throw new BadRequestHttpException('Error 23000!');
}
throw new BadRequestHttpException('Unknown error code: ' . $pdoException->getCode());
}
$response = new Response();
$response->setStatusCode($statusCode);
if (201 === $statusCode) {
$response->headers->set('Access-Control-Expose-Headers', 'Location');
$response->headers->set('Location', $this->container->get('router')->generate('api_v1_get_organization', ['organization' => $organization->getId()], UrlGeneratorInterface::RELATIVE_PATH));
}
return $response;
}
示例12: responseDenied
/**
* responseDenied
*
* Crea y devuelve una respuesta de denegación de la API.
* Si no se proporcionan parámetros, el estado HTTP y el mensaje de error tendrán valores por defecto.
*
* @param string $message
* @param int $httpStatusCode
* @return Response
*/
public function responseDenied($message = "", $httpStatusCode = Response::HTTP_NOT_FOUND)
{
$response['state'] = $this::STATE_ERROR;
$response['msg'] = $this->translator->trans($message);
$view = View::create()->setStatusCode($httpStatusCode)->setData($response);
return $this->viewhandler->handle($view);
}
示例13: showAction
/**
* Converts an Exception to a Response.
*
* @param FlattenException $exception A FlattenException instance
* @param DebugLoggerInterface $logger A DebugLoggerInterface instance
* @param string $format The format to use for rendering (html, xml, ...)
* @param integer $code An HTTP response code
* @param string $message An HTTP response status message
* @param array $headers HTTP response headers
*
* @return Response Response instance
*/
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null, $format = 'html')
{
$format = $this->getFormat($request, $format);
if (null === $format) {
$message = 'No matching accepted Response format could be determined, while handling: ';
$message .= $this->getExceptionMessage($exception);
return new Response($message, Codes::HTTP_NOT_ACCEPTABLE, $exception->getHeaders());
}
// the count variable avoids an infinite loop on
// some Windows configurations where ob_get_level()
// never reaches 0
$count = 100;
$currentContent = '';
while (ob_get_level() && --$count) {
$currentContent .= ob_get_clean();
}
$code = $this->getStatusCode($exception);
$viewHandler = $this->container->get('fos_rest.view_handler');
$parameters = $this->getParameters($viewHandler, $currentContent, $code, $exception, $logger, $format);
try {
$view = View::create($parameters, $code, $exception->getHeaders());
$view->setFormat($format);
if ($viewHandler->isFormatTemplating($format)) {
$view->setTemplate($this->findTemplate($format, $code));
}
$response = $viewHandler->handle($view);
} catch (\Exception $e) {
$message = 'An Exception was thrown while handling: ';
$message .= $this->getExceptionMessage($exception);
$response = new Response($message, Codes::HTTP_INTERNAL_SERVER_ERROR, $exception->getHeaders());
}
return $response;
}
示例14: showAction
/**
* Converts an Exception to a Response.
*
* @param Request $request
* @param HttpFlattenException|DebugFlattenException $exception
* @param DebugLoggerInterface $logger
* @param string $format
*
* @return Response
*
* @throws \InvalidArgumentException
*/
public function showAction(Request $request, $exception, DebugLoggerInterface $logger = null, $format = 'html')
{
/**
* Add support for ApiExceptionInterface
*/
if (!$exception instanceof DebugFlattenException && !$exception instanceof HttpFlattenException && !$exception instanceof ApiExceptionInterface) {
throw new \InvalidArgumentException(sprintf('ExceptionController::showAction can only accept some exceptions (%s, %s), "%s" given', 'Symfony\\Component\\HttpKernel\\Exception\\FlattenException', 'Symfony\\Component\\Debug\\Exception\\FlattenException', get_class($exception)));
}
$format = $this->getFormat($request, $format);
if (null === $format) {
$message = 'No matching accepted Response format could be determined, while handling: ';
$message .= $this->getExceptionMessage($exception);
return new Response($message, Codes::HTTP_NOT_ACCEPTABLE, $exception->getHeaders());
}
$currentContent = $this->getAndCleanOutputBuffering();
$code = $this->getStatusCode($exception);
$viewHandler = $this->container->get('fos_rest.view_handler');
$parameters = $this->getParameters($viewHandler, $currentContent, $code, $exception, $logger, $format);
try {
if (!$viewHandler->isFormatTemplating($format)) {
$parameters = $this->createExceptionWrapper($parameters);
}
$view = View::create($parameters, $code, $exception->getHeaders());
$view->setFormat($format);
if ($viewHandler->isFormatTemplating($format)) {
$view->setTemplate($this->findTemplate($request, $format, $code, $this->container->get('kernel')->isDebug()));
}
$response = $viewHandler->handle($view);
} catch (\Exception $e) {
$message = 'An Exception was thrown while handling: ';
$message .= $this->getExceptionMessage($exception);
$response = new Response($message, Codes::HTTP_INTERNAL_SERVER_ERROR, $exception->getHeaders());
}
return $response;
}
示例15: showAction
/**
* Converts an Exception to a Response.
*
* @param Request $request
* @param FlattenException $exception
* @param DebugLoggerInterface $logger
*
* @throws \InvalidArgumentException
*
* @return Response
*/
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
{
$format = $this->getFormat($request, $request->getRequestFormat());
if (null === $format) {
$message = 'No matching accepted Response format could be determined, while handling: ';
$message .= $this->getExceptionMessage($exception);
return new Response($message, Response::HTTP_NOT_ACCEPTABLE, $exception->getHeaders());
}
$currentContent = $this->getAndCleanOutputBuffering();
$code = $this->getStatusCode($exception);
$viewHandler = $this->container->get('fos_rest.view_handler');
$parameters = $this->getParameters($viewHandler, $currentContent, $code, $exception, $logger, $format);
$showException = $request->attributes->get('showException', $this->container->get('kernel')->isDebug());
try {
if (!$viewHandler->isFormatTemplating($format)) {
$parameters = $this->createExceptionWrapper($parameters);
}
$view = View::create($parameters, $code, $exception->getHeaders());
$view->setFormat($format);
if ($viewHandler->isFormatTemplating($format)) {
$view->setTemplate($this->findTemplate($request, $format, $code, $showException));
}
$response = $viewHandler->handle($view);
} catch (\Exception $e) {
$message = 'An Exception was thrown while handling: ';
$message .= $this->getExceptionMessage($exception);
$response = new Response($message, Response::HTTP_INTERNAL_SERVER_ERROR, $exception->getHeaders());
}
return $response;
}