getMethod() public method

If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the "real" intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if enableHttpMethodParameterOverride() has been called. The method is always an uppercased string.
See also: getRealMethod()
public getMethod ( ) : string
return string The request method
Example #1
0
 public function indexAction(Request $request)
 {
     $debug = "DEBUG: indexAction()";
     $response = null;
     // $request  = $this->getRequest(); Symfony2
     $form = $this->createFormBuilder()->add('url', TextType::class, array('attr' => array('placeholder' => 'ef0bdd815d2a39741c4c30842b7f9488', 'class' => 'input-lg')))->getForm();
     $debug .= " ; " . print_r($request->getMethod(), true);
     if ($request->getMethod() == 'POST') {
         $debug .= " ; POST OK";
         dump("OK");
         $form->handleRequest($request);
         if ($form->isValid()) {
             $debug .= " ; FormIsValid";
             $params = array('apikey' => 'xoxo', 'url' => $form->get('url')->getData());
             // Call internal api
             $url = $this->generateUrl('tweet_count_api_url', array(), true);
             $url .= '?' . http_build_query($params);
             dump($url);
             $curl = curl_init($url);
             curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
             $response = curl_exec($curl);
             curl_close($curl);
             $debug .= " ; URL:{$url}";
             if ($response !== null) {
                 $response = json_decode($response);
             }
         }
     }
     return $this->render('TweetCountWebsiteBundle:Default:index.html.twig', array('form' => $form->createView(), 'response' => $response, 'debug' => $debug));
 }
 /**
  * Process form
  *
  * @param  EmailTemplate $entity
  *
  * @return bool True on successful processing, false otherwise
  */
 public function process(EmailTemplate $entity)
 {
     // always use default locale during template edit in order to allow update of default locale
     $entity->setLocale($this->defaultLocale);
     if ($entity->getId()) {
         // refresh translations
         $this->manager->refresh($entity);
     }
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         // deny to modify system templates
         if ($entity->getIsSystem() && !$entity->getIsEditable()) {
             $this->form->addError(new FormError($this->translator->trans('oro.email.handler.attempt_save_system_template')));
             return false;
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             // mark an email template creating by an user as editable
             if (!$entity->getId()) {
                 $entity->setIsEditable(true);
             }
             $this->manager->persist($entity);
             $this->manager->flush();
             return true;
         }
     }
     return false;
 }
 /**
  * @param LineItem $lineItem
  *
  * @return bool
  */
 public function process(LineItem $lineItem)
 {
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             /** @var LineItemRepository $lineItemRepository */
             $lineItemRepository = $this->manager->getRepository('OroB2BShoppingListBundle:LineItem');
             $existingLineItem = $lineItemRepository->findDuplicate($lineItem);
             if ($existingLineItem) {
                 $existingLineItem->setQuantity($lineItem->getQuantity() + $existingLineItem->getQuantity());
                 $existingLineItemNote = $existingLineItem->getNotes();
                 $newNotes = $lineItem->getNotes();
                 $notes = trim(implode(' ', [$existingLineItemNote, $newNotes]));
                 if ($notes) {
                     $existingLineItem->setNotes($notes);
                 }
                 $this->savedId = $existingLineItem->getId();
             } else {
                 $this->manager->persist($lineItem);
             }
             $this->manager->flush();
             return true;
         }
     }
     return false;
 }
 /**
  * {@inheritdoc}
  */
 protected function attemptAuthentication(Request $request)
 {
     if ($this->options['post_only'] && 'post' !== strtolower($request->getMethod())) {
         if (null !== $this->logger) {
             $this->logger->debug(sprintf('Authentication method not supported: %s.', $request->getMethod()));
         }
         return null;
     }
     if (null !== $this->csrfProvider) {
         $csrfToken = $request->get($this->options['csrf_parameter'], null, true);
         if (false === $this->csrfProvider->isCsrfTokenValid($this->options['intention'], $csrfToken)) {
             throw new InvalidCsrfTokenException('Invalid CSRF token.');
         }
     }
     if (null !== $this->recaptcha && false === $this->recaptchaDisabled) {
         try {
             if (true !== $this->recaptcha->checkAnswer($request->server->get('REMOTE_ADDR'), $request->get($this->recaptcha->getChallengeField()), $request->get($this->recaptcha->getResponseField()))) {
                 throw new InvalidRecaptchaException('Invalid captcha.');
             }
         } catch (Exception $e) {
             throw new AuthenticationException('Invalid captcha.', null, null, $e);
         }
     }
     $username = trim($request->get($this->options['username_parameter'], null, true));
     $password = $request->get($this->options['password_parameter'], null, true);
     $request->getSession()->set(SecurityContextInterface::LAST_USERNAME, $username);
     return $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey));
 }
 /**
  * @param LineItem $lineItem
  *
  * @return bool
  */
 public function process(LineItem $lineItem)
 {
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         /** @var EntityManagerInterface $manager */
         $manager = $this->registry->getManagerForClass('OroB2BShoppingListBundle:LineItem');
         $manager->beginTransaction();
         // handle case for new shopping list creation
         $formName = $this->form->getName();
         $formData = $this->request->request->get($formName, []);
         if (empty($formData['shoppingList']) && !empty($formData['shoppingListLabel'])) {
             $shoppingList = $this->shoppingListManager->createCurrent($formData['shoppingListLabel']);
             $formData['shoppingList'] = $shoppingList->getId();
             $this->request->request->set($formName, $formData);
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             /** @var LineItemRepository $lineItemRepository */
             $lineItemRepository = $manager->getRepository('OroB2BShoppingListBundle:LineItem');
             $existingLineItem = $lineItemRepository->findDuplicate($lineItem);
             if ($existingLineItem) {
                 $this->updateExistingLineItem($lineItem, $existingLineItem);
             } else {
                 $manager->persist($lineItem);
             }
             $manager->flush();
             $manager->commit();
             return true;
         } else {
             $manager->rollBack();
         }
     }
     return false;
 }
Example #6
0
 /**
  * Process form
  *
  * @param  Task $entity
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(Task $entity)
 {
     $action = $this->entityRoutingHelper->getAction($this->request);
     $targetEntityClass = $this->entityRoutingHelper->getEntityClassName($this->request);
     $targetEntityId = $this->entityRoutingHelper->getEntityId($this->request);
     if ($targetEntityClass && !$entity->getId() && $this->request->getMethod() === 'GET' && $action === 'assign' && is_a($targetEntityClass, 'Oro\\Bundle\\UserBundle\\Entity\\User', true)) {
         $entity->setOwner($this->entityRoutingHelper->getEntity($targetEntityClass, $targetEntityId));
         FormUtils::replaceField($this->form, 'owner', ['read_only' => true]);
     }
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             // TODO: should be refactored after finishing BAP-8722
             // Contexts handling should be moved to common for activities form handler
             if ($this->form->has('contexts')) {
                 $contexts = $this->form->get('contexts')->getData();
                 $this->activityManager->setActivityTargets($entity, $contexts);
             } elseif ($targetEntityClass && $action === 'activity') {
                 // if we don't have "contexts" form field
                 // we should save association between activity and target manually
                 $this->activityManager->addActivityTarget($entity, $this->entityRoutingHelper->getEntityReference($targetEntityClass, $targetEntityId));
             }
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
 /**
  * Process form
  *
  * @param  Issue $entity
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(Issue $entity)
 {
     $action = $this->entityRoutingHelper->getAction($this->request);
     $targetEntityClass = $this->entityRoutingHelper->getEntityClassName($this->request);
     $targetEntityId = $this->entityRoutingHelper->getEntityId($this->request);
     if ($targetEntityClass && !$entity->getId() && $this->request->getMethod() === 'GET' && $action === 'assign' && is_a($targetEntityClass, 'Oro\\Bundle\\UserBundle\\Entity\\User', true)) {
         $entity->setAssignee($this->entityRoutingHelper->getEntity($targetEntityClass, $targetEntityId));
         FormUtils::replaceField($this->form, 'assignee', ['read_only' => true]);
     }
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             /* if ($targetEntityClass && $action === 'activity') {
                    $this->activityManager->addActivityTarget(
                        $entity,
                        $this->entityRoutingHelper->getEntityReference($targetEntityClass, $targetEntityId)
                    );
                }*/
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
 /**
  * @return RedirectResponse|Response
  *
  * @throws AccessDeniedException
  */
 public function createAction(Request $request = null)
 {
     $this->admin->checkAccess('create');
     $class = $this->get('sonata.page.manager.snapshot')->getClass();
     $pageManager = $this->get('sonata.page.manager.page');
     $snapshot = new $class();
     if ($request->getMethod() == 'GET' && $request->get('pageId')) {
         $page = $pageManager->findOne(array('id' => $request->get('pageId')));
     } elseif ($this->admin->isChild()) {
         $page = $this->admin->getParent()->getSubject();
     } else {
         $page = null;
         // no page selected ...
     }
     $snapshot->setPage($page);
     $form = $this->createForm('sonata_page_create_snapshot', $snapshot);
     if ($request->getMethod() == 'POST') {
         $form->submit($request);
         if ($form->isValid()) {
             $snapshotManager = $this->get('sonata.page.manager.snapshot');
             $transformer = $this->get('sonata.page.transformer');
             $page = $form->getData()->getPage();
             $page->setEdited(false);
             $snapshot = $transformer->create($page);
             $this->admin->create($snapshot);
             $pageManager->save($page);
             $snapshotManager->enableSnapshots(array($snapshot));
         }
         return $this->redirect($this->admin->generateUrl('edit', array('id' => $snapshot->getId())));
     }
     return $this->render('SonataPageBundle:SnapshotAdmin:create.html.twig', array('action' => 'create', 'form' => $form->createView()));
 }
 function index(Request $request, Application $app)
 {
     $extension = $app['extensions']->getExtensionById('org.openacalendar.facebook');
     $appID = $app['appconfig']->getValue($extension->getAppConfigurationDefinition('app_id'));
     $appSecret = $app['appconfig']->getValue($extension->getAppConfigurationDefinition('app_secret'));
     $userToken = $app['appconfig']->getValue($extension->getAppConfigurationDefinition('user_token'));
     if ('POST' == $request->getMethod() && $request->request->get('CSFRToken') == $app['websession']->getCSFRToken() && $request->request->get('submitted') == 'appdetails') {
         $appID = $request->request->get('app_id');
         $appSecret = $request->request->get('app_secret');
         // Beacuse we are using a different app, we'll need a different user token to.
         $userToken = '';
         $app['appconfig']->setValue($extension->getAppConfigurationDefinition('app_id'), $appID);
         $app['appconfig']->setValue($extension->getAppConfigurationDefinition('app_secret'), $appSecret);
         $app['appconfig']->setValue($extension->getAppConfigurationDefinition('user_token'), $userToken);
     }
     if ('POST' == $request->getMethod() && $request->request->get('CSFRToken') == $app['websession']->getCSFRToken() && $request->request->get('submitted') == 'userdetails') {
         // Convert this short lived into long lived
         $url = "https://graph.facebook.com/oauth/access_token?client_id=" . $appID . "&client_secret=" . $appSecret . "&grant_type=fb_exchange_token&fb_exchange_token=" . $request->get('newfacebookaccesstoken');
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_TIMEOUT, 20);
         $result = curl_exec($ch);
         curl_close($ch);
         parse_str($result, $resultArray);
         if (!$resultArray['access_token']) {
             die("Did not get long-lived access token, problem.");
         }
         $userToken = $resultArray['access_token'];
         $app['appconfig']->setValue($extension->getAppConfigurationDefinition('user_token'), $userToken);
     }
     return $app['twig']->render('facebook/sysadmin/user/index.html.twig', array('app_id' => $appID, 'app_secret' => $appSecret ? substr($appSecret, 0, 5) . "XXXXXXX" : '', 'user_token' => $userToken ? substr($userToken, 0, 5) . "XXXXXXX" : ''));
 }
 /**
  * Process form
  *
  * @param  CalendarEvent $entity
  * @throws \LogicException
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(CalendarEvent $entity)
 {
     if (!$entity->getCalendar()) {
         if ($this->securityFacade->getLoggedUser() && $this->securityFacade->getOrganization()) {
             /** @var Calendar $defaultCalendar */
             $defaultCalendar = $this->manager->getRepository('OroCalendarBundle:Calendar')->findDefaultCalendar($this->securityFacade->getLoggedUser()->getId(), $this->securityFacade->getOrganization()->getId());
             $entity->setCalendar($defaultCalendar);
         } else {
             throw new \LogicException('Current user did not define');
         }
     }
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             $targetEntityClass = $this->entityRoutingHelper->getEntityClassName($this->request);
             if ($targetEntityClass) {
                 $targetEntityId = $this->entityRoutingHelper->getEntityId($this->request);
                 $targetEntity = $this->entityRoutingHelper->getEntityReference($targetEntityClass, $targetEntityId);
                 $action = $this->entityRoutingHelper->getAction($this->request);
                 if ($action === 'activity') {
                     $this->activityManager->addActivityTarget($entity, $targetEntity);
                 }
                 if ($action === 'assign' && $targetEntity instanceof User && $targetEntityId !== $this->securityFacade->getLoggedUserId()) {
                     /** @var Calendar $defaultCalendar */
                     $defaultCalendar = $this->manager->getRepository('OroCalendarBundle:Calendar')->findDefaultCalendar($targetEntity->getId(), $targetEntity->getOrganization()->getId());
                     $entity->setCalendar($defaultCalendar);
                 }
             }
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
 /**
  * Process form
  *
  * @param AccountUser $accountUser
  * @return bool True on successful processing, false otherwise
  */
 public function process(AccountUser $accountUser)
 {
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             if (!$accountUser->getId()) {
                 if ($this->form->get('passwordGenerate')->getData()) {
                     $generatedPassword = $this->userManager->generatePassword(10);
                     $accountUser->setPlainPassword($generatedPassword);
                 }
                 if ($this->form->get('sendEmail')->getData()) {
                     $this->userManager->sendWelcomeEmail($accountUser);
                 }
             }
             $token = $this->securityFacade->getToken();
             if ($token instanceof OrganizationContextTokenInterface) {
                 $organization = $token->getOrganizationContext();
                 $accountUser->setOrganization($organization)->addOrganization($organization);
             }
             $this->userManager->updateUser($accountUser);
             return true;
         }
     }
     return false;
 }
    /**
     * {@inheritdoc}
     */
    protected function attemptAuthentication(Request $request)
    {
        if ($this->options['post_only'] && 'post' !== strtolower($request->getMethod())) {
            if (null !== $this->logger) {
                $this->logger->debug(sprintf('Authentication method not supported: %s.', $request->getMethod()));
            }

            return null;
        }

        if (null !== $this->csrfProvider) {
            $csrfToken = $request->get($this->options['csrf_parameter']);

            if (false === $this->csrfProvider->isCsrfTokenValid($this->options['csrf_page_id'], $csrfToken)) {
                throw new InvalidCsrfTokenException('Invalid CSRF token.');
            }
        }

        $username = trim($request->get($this->options['username_parameter']));
        $password = $request->get($this->options['password_parameter']);

        $request->getSession()->set(SecurityContextInterface::LAST_USERNAME, $username);

        return $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey));
    }
Example #13
0
 public function auth(Request $request)
 {
     $token = $request->headers->get('X-Auth-Token');
     if (empty($token)) {
         // 兼容老的协议,即将去除
         $token = $request->headers->get('Auth-Token', '');
     }
     $method = strtolower($request->headers->get('X-Auth-Method'));
     if ($method == 'keysign') {
         $decoded = $this->decodeKeysign($token);
         $this->setCurrentUser(array('id' => 0, 'nickname' => '游客', 'currentIp' => $request->getClientIp(), 'roles' => array()));
     } else {
         $whilelist = isset($this->whilelist[$request->getMethod()]) ? $this->whilelist[$request->getMethod()] : array();
         $path = rtrim($request->getPathInfo(), '/');
         $inWhiteList = 0;
         foreach ($whilelist as $pattern) {
             if (preg_match($pattern, $path)) {
                 $inWhiteList = 1;
                 break;
             }
         }
         if (!$inWhiteList && empty($token)) {
             throw new \RuntimeException('API Token不存在!');
         }
         $token = $this->getUserService()->getToken('mobile_login', $token);
         if (!$inWhiteList && empty($token['userId'])) {
             throw new \RuntimeException('API Token不不正确!');
         }
         $user = $this->getUserService()->getUser($token['userId']);
         if (!$inWhiteList && empty($user)) {
             throw new \RuntimeException('登录用户不存在!');
         }
         $this->setCurrentUser($user);
     }
 }
Example #14
0
 /**
  * Process form
  *
  * @param  Call $entity
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(Call $entity)
 {
     $targetEntityClass = $this->request->get('entityClass');
     $targetEntityId = $this->request->get('entityId');
     $options = [];
     if ($targetEntityClass && $this->request->getMethod() === 'GET') {
         $targetEntity = $this->entityRoutingHelper->getEntity($targetEntityClass, $targetEntityId);
         if (!$entity->getId()) {
             $entity->setPhoneNumber($this->phoneProvider->getPhoneNumber($targetEntity));
         }
         $options = ['phone_suggestions' => array_unique(array_map(function ($item) {
             return $item[0];
         }, $this->phoneProvider->getPhoneNumbers($targetEntity)))];
     }
     $this->form = $this->formFactory->createNamed($this->formName, $this->formType, $entity, $options);
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             if ($targetEntityClass) {
                 $targetEntity = $this->entityRoutingHelper->getEntity($targetEntityClass, $targetEntityId);
                 $this->callActivityManager->addAssociation($entity, $targetEntity);
                 $phones = $this->phoneProvider->getPhoneNumbers($targetEntity);
                 foreach ($phones as $phone) {
                     if ($entity->getPhoneNumber() === $phone[0]) {
                         $this->callActivityManager->addAssociation($entity, $phone[1]);
                     }
                 }
             }
             $this->onSuccess($entity);
             return true;
         }
     }
     return false;
 }
 protected function initializeRequestAttributes(Request $request, $master)
 {
     if ($master) {
         // set the context even if the parsing does not need to be done
         // to have correct link generation
         $this->router->setContext(array('base_url' => $request->getBaseUrl(), 'method' => $request->getMethod(), 'host' => $request->getHost(), 'port' => $request->getPort(), 'is_secure' => $request->isSecure()));
     }
     if ($request->attributes->has('_controller')) {
         // routing is already done
         return;
     }
     // add attributes based on the path info (routing)
     try {
         $parameters = $this->router->match($request->getPathInfo());
         if (null !== $this->logger) {
             $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], json_encode($parameters)));
         }
         $request->attributes->add($parameters);
         if ($locale = $request->attributes->get('_locale')) {
             $request->getSession()->setLocale($locale);
         }
     } catch (NotFoundException $e) {
         $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
         if (null !== $this->logger) {
             $this->logger->err($message);
         }
         throw new NotFoundHttpException($message, $e);
     } catch (MethodNotAllowedException $e) {
         $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), strtoupper(implode(', ', $e->getAllowedMethods())));
         if (null !== $this->logger) {
             $this->logger->err($message);
         }
         throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
     }
 }
 public function updateAction(Request $request)
 {
     $ExamId = $request->get('id');
     $em = $this->getDoctrine()->getManager();
     $exam = $em->getRepository('ClassUserBundle:Exams')->find($ExamId);
     //under this condition edit form will filled with the existing data
     //when class being selected this mehtod will be invoked.
     if ($request->getMethod() == 'GET' && $exam != null) {
         $encoders = array(new JsonEncoder());
         $normalizers = array(new ObjectNormalizer());
         $serializer = new Serializer($normalizers, $encoders);
         $jsonContent = $serializer->serialize($exam, 'json');
         return new \Symfony\Component\HttpFoundation\Response($jsonContent);
     }
     //this conditon will work when data being submitted through the form
     if ($request->getMethod() == 'POST' && $exam != null) {
         if ($request->request->get('fees')) {
             $exam->setFees($request->request->get('fees'));
         }
         if ($request->request->get('conductDay')) {
             $exam->setConductDay($request->request->get('conductDay'));
         }
         if ($request->request->get('time')) {
             $exam->setTime($request->request->get('time'));
         }
         if ($request->request->get('teacher_id')) {
             $exam->setTeacherid($request->request->get('teacher_id'));
         }
         $em->flush();
         return new JsonResponse(array('message' => 'Updated Successfully'));
     }
     return new JsonResponse(array('message' => 'ERROR'));
 }
Example #17
0
 /**
  * @throws \LogicException
  *
  * @return array
  */
 public function getFormSubmittedData()
 {
     if ('POST' !== $this->request->getMethod()) {
         throw new \LogicException('Unable to fetch submitted data, only POST request supported');
     }
     return $this->request->get($this->form->getName(), []);
 }
 /**
  * Process form
  *
  * @param  CalendarEvent $entity
  *
  * @throws \LogicException
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(CalendarEvent $entity)
 {
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $originalChildren = new ArrayCollection();
         foreach ($entity->getChildEvents() as $childEvent) {
             $originalChildren->add($childEvent);
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             $this->ensureCalendarSet($entity);
             $targetEntityClass = $this->entityRoutingHelper->getEntityClassName($this->request);
             if ($targetEntityClass) {
                 $targetEntityId = $this->entityRoutingHelper->getEntityId($this->request);
                 $targetEntity = $this->entityRoutingHelper->getEntityReference($targetEntityClass, $targetEntityId);
                 $action = $this->entityRoutingHelper->getAction($this->request);
                 if ($action === 'activity') {
                     $this->activityManager->addActivityTarget($entity, $targetEntity);
                 }
                 if ($action === 'assign' && $targetEntity instanceof User && $targetEntityId !== $this->securityFacade->getLoggedUserId()) {
                     /** @var Calendar $defaultCalendar */
                     $defaultCalendar = $this->manager->getRepository('OroCalendarBundle:Calendar')->findDefaultCalendar($targetEntity->getId(), $targetEntity->getOrganization()->getId());
                     $entity->setCalendar($defaultCalendar);
                 }
             }
             $this->onSuccess($entity, $originalChildren, $this->form->get('notifyInvitedUsers')->getData());
             return true;
         }
     }
     return false;
 }
 /**
  * Handles a web API request.
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  *   The HTTP request object.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   The response object.
  */
 public function handle(Request $request)
 {
     $route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT);
     $plugin = $route->getDefault('_plugin');
     $operation = $route->getRequirement('_operation');
     $resource = $this->container->get('plugin.manager.rest')->getInstance(array('id' => $plugin));
     // Deserialize incoming data if available.
     $serializer = $this->container->get('serializer');
     $received = $request->getContent();
     $unserialized = NULL;
     if (!empty($received)) {
         $format = $request->getContentType();
         // Only allow serialization formats that are explicitly configured. If no
         // formats are configured allow all and hope that the serializer knows the
         // format. If the serializer cannot handle it an exception will be thrown
         // that bubbles up to the client.
         $config = $this->container->get('config.factory')->get('rest.settings')->get('resources');
         $enabled_formats = isset($config[$plugin][$request->getMethod()]) ? $config[$plugin][$request->getMethod()] : array();
         if (empty($enabled_formats) || isset($enabled_formats[$format])) {
             $unserialized = json_decode($received);
             //        $definition = $resource->getDefinition();
             //        $class = $definition['serialization_class'];
             //        try {
             //          $unserialized = $serializer->deserialize($received, $class, $format);
             //        }
             //        catch (UnexpectedValueException $e) {
             //          $error['error'] = $e->getMessage();
             //          $content = $serializer->serialize($error, $format);
             //          return new Response($content, 400, array('Content-Type' => $request->getMimeType($format)));
             //        }
         } else {
             throw new UnsupportedMediaTypeHttpException();
         }
     }
     // Invoke the operation on the resource plugin.
     // All REST routes are restricted to exactly one format, so instead of
     // parsing it out of the Accept headers again, we can simply retrieve the
     // format requirement. If there is no format associated, just pick HAL.
     $format = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT)->getRequirement('_format') ?: 'hal_json';
     try {
         $operation_annotation = $resource->getMethodAnnotation($operation);
         $arguments = $this->getArguments($operation_annotation, $request, $unserialized);
         $response = $resource->{$operation}($arguments, $unserialized, $request);
     } catch (HttpException $e) {
         $error['error'] = $e->getMessage();
         $content = $serializer->serialize($error, $format);
         // Add the default content type, but only if the headers from the
         // exception have not specified it already.
         $headers = $e->getHeaders() + array('Content-Type' => $request->getMimeType($format));
         return new Response($content, $e->getStatusCode(), $headers);
     }
     // Serialize the outgoing data for the response, if available.
     $data = $response->getResponseData();
     if ($data != NULL) {
         $output = $serializer->serialize($data, $format);
         $response->setContent($output);
         $response->headers->set('Content-Type', $request->getMimeType($format));
     }
     return $response;
 }
Example #20
0
    /**
     * Handle invalidation, including Http PURGE requests.
     * All non-allowed PURGE requests will receive an HTTP 405
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param boolean $catch
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function invalidate( Request $request, $catch = false )
    {
        if ( $request->getMethod() !== 'PURGE' && $request->getMethod() !== 'BAN' )
        {
            return parent::invalidate( $request, $catch );
        }

        // Reject all non-authorized clients
        if ( !$this->isInternalRequestAllowed( $request ) )
        {
            return new Response( '', 405 );
        }

        $response = new Response();
        $store = $this->getStore();
        if ( $store instanceof RequestAwarePurger )
        {
            $result = $store->purgeByRequest( $request );
        }
        else
        {
            $result = $store->purge( $request->getUri() );
        }

        if ( $result === true )
        {
            $response->setStatusCode( 200, 'Purged' );
        }
        else
        {
            $response->setStatusCode( 404, 'Not purged' );
        }

        return $response;
    }
Example #21
0
 /**
  * Handle and return response.
  *
  * @return Response
  *
  * @throws BadRequestException
  */
 public function serve()
 {
     Log::debug('Request received:', ['Method' => $this->request->getMethod(), 'URI' => $this->request->getRequestUri(), 'Query' => $this->request->getQueryString(), 'Protocal' => $this->request->server->get('SERVER_PROTOCOL'), 'Content' => $this->request->getContent()]);
     $result = $this->handleRequest();
     $response = $this->buildResponse($result['response']);
     Log::debug('Server response created:', compact('response'));
     return new Response($response);
 }
Example #22
0
 /**
  * Performs route matching & dispatch and sends the response.
  *
  * @return $this
  */
 public function run()
 {
     // Route
     $match = $this->router->match($this->request->getPathInfo(), $this->request->getMethod(), $this->request->getHttpHost(false));
     // Dispatch
     $this->dispatch($match);
     // Respond
     $this->response->send();
 }
 /**
  * @param EntityManager $user
  *
  * @return bool
  */
 public function process(ProjetModel $projet)
 {
     $this->form->setData($projet);
     if ('POST' == $this->request->getMethod()) {
         $this->form->bind($this->request);
         if ($this->form->isValid()) {
             $projet->setUser($this->connectedUser);
             ############ Edit settings ##############
             $DestinationDirectory = __DIR__ . '/../../../../../web/uploads/';
             //specify upload directory ends with / (slash)
             $Quality = 90;
             //jpeg quality
             ##########################################
             //Let's check allowed $ImageType, we use PHP SWITCH statement here
             $ext = $projet->file->getMimeType();
             switch (strtolower($projet->file->getMimeType())) {
                 case 'image/png':
                     //Create a new image from file
                     $CreatedImage = imagecreatefrompng($projet->file->getRealPath());
                     break;
                 case 'image/gif':
                     $CreatedImage = imagecreatefromgif($projet->file->getRealPath());
                     break;
                 case 'image/jpeg':
                 case 'image/pjpeg':
                     $CreatedImage = imagecreatefromjpeg($projet->file->getRealPath());
                     break;
                 default:
                     die('Unsupported File!');
                     //output error and exit
             }
             // Crop and save image to upload directory
             $cropService = $this->cropper;
             $destImage = uniqid() . '.' . $projet->file->guessExtension();
             if (!$cropService->cropImage($projet->getX(), $projet->getY(), $projet->getW(), $projet->getH(), $DestinationDirectory . $destImage, $CreatedImage, $Quality, $projet->file->getMimeType())) {
                 die('Erreur lors du rognage de l\'image');
             }
             $projet->setPhoto($destImage);
             // Create entity project
             $entity = new Projet();
             $entity->setNomprojet($projet->getNomprojet());
             $entity->setDescription($projet->getDescription());
             $entity->setDuree($projet->getDuree());
             $entity->setDaterealisation($projet->getDaterealisation());
             $entity->setGains($projet->getGains());
             $entity->setFinancement($projet->getFinancement());
             $entity->setPhoto($projet->getPhoto());
             $entity->setCout($projet->getCout());
             $entity->setUser($projet->getUser());
             $this->entityManager->persist($entity);
             $this->entityManager->flush();
             return true;
         }
     }
     return false;
 }
Example #24
0
 /**
  * @Route("/orders")
  * @Template()
  */
 public function ordersAction(Request $request)
 {
     // GET requests simply show the Place Order page
     if ($request->getMethod() == 'GET') {
         $em = $this->getDoctrine()->getManager();
         $orders = $em->getRepository('AppBundle:Order')->findAll(array(), array('id', 'ASC'));
         return $this->render('Orders/orders.html.twig', array('orders' => $orders));
     } elseif ($request->getMethod() == 'PUT') {
     }
 }
Example #25
0
 /**
  * Return request parameter from query or post body
  */
 public function getParameters()
 {
     if ($this->parameters === null) {
         $this->parameters = new ParameterBag($this->request->query->all());
         if ($this->request->getMethod() !== Request::METHOD_GET) {
             $this->parameters->add($this->request->request->all());
         }
     }
     return $this->parameters;
 }
 /**
  * @param ShoppingList $shoppingList
  * @return boolean
  */
 public function process(ShoppingList $shoppingList)
 {
     $this->form->setData($shoppingList);
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             return $this->onSuccess($shoppingList);
         }
     }
     return false;
 }
Example #27
0
 /**
  * Run the application and match routes to the requested uri
  *
  * @param $routes
  * @return App
  * @throws Exceptions\MethodNotAllowed
  * @throws Exceptions\NotFound
  */
 public function run(array $routes) : App
 {
     array_walk($routes, function (array $route) {
         $this->router->routeRequestCollection[] = new RouteRequest($route['httpMethod'], $route['route'], $route['handler']);
     });
     $this->router->dispatch($this->request->getPathInfo(), $this->request->getMethod(), function ($handler, array $args = []) {
         $response = call_user_func_array($handler, [$this->request, $args]);
         $response->send();
     });
     return $this;
 }
Example #28
0
 /**
  * Process form
  *
  * @param FormInterface $form
  * @return bool
  */
 public function process(FormInterface $form)
 {
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $form->submit($this->request);
         if ($form->isValid()) {
             $this->onSuccess($form->getData());
             return true;
         }
     }
     return false;
 }
Example #29
0
 /**
  * Process form
  *
  * @param mixed $entity
  *
  * @return mixed|null The instance of saved entity on successful processing; otherwise, null
  */
 public function process($entity)
 {
     $entity = $this->prepareFormData($entity);
     if (in_array($this->request->getMethod(), ['POST', 'PUT'], true)) {
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             return $this->onSuccess($entity) ?: $entity;
         }
     }
     return null;
 }
Example #30
0
 protected function getCubeData(Request $request)
 {
     $cubeParams = array();
     if ($templateUri = $request->request->get('_template')) {
         $template = \Settings\Template::find($templateUri);
         $cubeParams = json_decode($template->Content->value, true);
     } elseif ($request->getMethod() === 'POST') {
         $cubeParams = $request->request->all();
     }
     if (isset($cubeParams['_dimensions'])) {
         $chosenDimensions = array_keys($cubeParams['_dimensions']);
     } elseif ($request->getMethod() === 'GET') {
         $chosenDimensions = $this->getDefaultDimensions();
     } else {
         $chosenDimensions = array();
     }
     if (isset($cubeParams['_facts'])) {
         $chosenFacts = array_keys($cubeParams['_facts']);
     } elseif ($request->getMethod() === 'GET') {
         $chosenFacts = $this->getDefaultFacts();
     } else {
         $chosenFacts = array();
     }
     // check if template is out of date with invalid facts/dimensions
     if ($templateUri && (count($chosenDimensions) !== count(array_intersect($chosenDimensions, $this->getDimensions())) || count($chosenFacts) !== count(array_intersect($chosenFacts, $this->getFacts())))) {
         throw new \LogicException('Template "' . $template->Title . '"" is invalid or out of date');
     }
     $filter = $this->getFilter();
     if (!$filter instanceof Form) {
         $filter = $this->createForm($filter);
     }
     if ($request->getMethod() === 'POST') {
         $filter->bind($request);
     }
     $specification = $filter->getData();
     $cube = $this->getCube();
     $builder = new CubeBuilder($cube);
     $builder->dimensions($chosenDimensions)->facts($chosenFacts)->with($specification);
     if ($order = $request->get('_order')) {
         if (is_string($order)) {
             $order = array($order);
         }
         $order = array_intersect($order, array_merge($chosenFacts, $chosenDimensions));
         foreach ($order as $property) {
             $builder->asc($property);
         }
     }
     $items = $builder->analyze();
     $result = array('items' => $items, 'dimensions' => $this->getDimensions(), 'facts' => $this->getFacts(), 'filter' => $filter->createView(), 'chosen_dimensions' => $chosenDimensions, 'chosen_facts' => $chosenFacts, 'order' => $order);
     if ($this->hasTemplating()) {
         $result['template'] = array('items' => $this->findTemplates(), 'chosen' => $templateUri, 'name' => 'php:cube:' . \NGS\Name::full($cube));
     }
     return $result;
 }