getUriForPath() public method

Generates a normalized URI for the given path.
public getUriForPath ( string $path ) : string
$path string A path to use instead of the current one
return string The normalized URI for the path
Esempio n. 1
0
 /**
  * @Route("uploadFile", name="pic.upload.file")
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function uploadFilesAction(Request $request)
 {
     $this->get("logger")->debug("Entramos al subidor de imágenes");
     $em = $this->getDoctrine()->getManager();
     $files = $request->files;
     $this->get("logger")->debug("Despues de sacar las imagenes del request");
     $this->get("logger")->debug(sprintf("Conteo de los archivos a subir: %s", count($files)));
     $data = array();
     if (count($files) > 0) {
         foreach ($files as $file) {
             $md5 = md5_file($file);
             $result = $em->createQuery("select p from PicboardBundle:ThePicture p where p.md5 = :md5 " . " and p.deletedAt = null")->setParameter("md5", $md5)->getOneOrNullResult();
             if (is_null($result)) {
                 $ext = strtolower($file->getClientOriginalExtension());
                 $fileName = $md5 . "." . $ext;
                 $file->move('pictures/', $fileName);
                 $this->get("logger")->debug(sprintf("El nombre del archivo es: %s", $fileName));
                 $picture = new ThePicture();
                 $picture->setMd5($md5);
                 $picture->setPath($fileName);
                 $em->persist($picture);
                 $em->flush();
                 $url = $request->getUriForPath("/pictures/" . $picture->getPath());
                 $content = array('url' => $url);
                 array_push($data, $content);
             } else {
                 $url = $request->getUriForPath("/pictures/" . $result->getPath());
                 $content = array('url' => $url);
                 array_push($data, $content);
             }
         }
         return new JsonResponse($data);
     }
     throw new InvalidArgumentException("No se pueden subir imagenes si no existen");
 }
 /**
  * {@inheritdoc}
  */
 public function start(EventInterface $event, Request $request, AuthenticationException $authException = null)
 {
     if ($this->useForward) {
         return $event->getSubject()->handle(Request::create($this->loginPath), HttpKernelInterface::SUB_REQUEST);
     }
     return new RedirectResponse(0 !== strpos($this->loginPath, 'http') ? $request->getUriForPath($this->loginPath) : $this->loginPath, 302);
 }
Esempio n. 3
0
 /**
  * Builds a page with login form.
  *
  * @param Request $request Incoming request.
  * @return string Rendered page content.
  */
 public function showFormAction(Request $request)
 {
     // Check if the operator already logged in
     if ($this->getOperator()) {
         // Redirect the operator to home page.
         // TODO: Use a route for URI generation.
         return $this->redirect($request->getUriForPath('/operator'));
     }
     $page = array('formisRemember' => true, 'version' => MIBEW_VERSION, 'errors' => $request->attributes->get('errors', array()));
     // Try to get login from the request.
     if ($request->request->has('login')) {
         $page['formlogin'] = $request->request->get('login');
     } elseif ($request->query->has('login')) {
         $login = $request->query->get('login');
         if (preg_match("/^(\\w{1,15})\$/", $login)) {
             $page['formlogin'] = $login;
         }
     }
     $page['localeLinks'] = get_locale_links();
     $page['title'] = getlocal('Login');
     $page['headertitle'] = getlocal('Mibew Messenger');
     $page['show_small_login'] = false;
     $page['fixedwrap'] = true;
     return $this->render('login', $page);
 }
Esempio n. 4
0
 /**
  * @Route("/slider/create", name="picture_slider_create")
  * @param Request $request
  * @return JsonResponse
  */
 public function sliderCreateAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $postId = $request->get("postId");
     $files = $request->files;
     $picture = new Picture();
     $result = array();
     $post = $em->createQuery("select p from IndexBundle:Post p where p.id=:id")->setParameter("id", $postId)->getOneOrNullResult();
     if (is_null($post)) {
         throw new InvalidArgumentException("No existe publicacion asociada a id");
     }
     foreach ($files as $file) {
         $uid = uniqid();
         $md5 = md5($uid);
         $ext = strtolower($file->getClientOriginalExtension());
         $fileName = $md5 . "." . $ext;
         $file->move(__DIR__ . "/../../../web/pictures/", $fileName);
         $picture->setMd5($md5);
         $picture->setPath($fileName);
         $picture->setSection("slider");
         $em->persist($picture);
         $em->flush();
         $this->persistAndFlushSlider($picture, $post);
         $url = $request->getUriForPath("/pictures/" . $fileName);
         $data = array('url' => $url);
         array_push($result, $data);
     }
     return new JsonResponse($result);
 }
Esempio n. 5
0
 /**
  * @Route("/{_locale}/get/seed/{seed}", name="get_by_seed_locale")
  * @Route("/get/seed/{seed}", name="get_by_seed")
  */
 public function getBySeedAction(Request $request, $seed)
 {
     $return = array('status' => 1, 'message' => '', 'data' => null);
     // retorno padrão
     $router = $this->container->get('router');
     $translator = $this->get('translator');
     // da uma limpada
     $seed = md5($seed . $this->container->getParameter('secret'));
     // extrai um numero de 0~9
     $seed = substr(base_convert(md5($seed), 16, 10), -1);
     srand($seed);
     // usa pro rand
     // image path
     $image_path = $request->getUriForPath('/image/cenouro.png');
     $message = '';
     // são tão poucas opções que nem vale a pena criar DB
     // balanceia as chances um pouco
     switch (rand(1, 4)) {
         case 1:
             $message = 'Yes!';
             break;
         case 2:
             $message = 'No!';
             break;
         default:
             switch (rand(1, 6)) {
                 case 1:
                     $message = 'Maybe.';
                     break;
                 case 2:
                     $message = 'Sure!';
                     break;
                 case 3:
                     $message = "I really don't care.";
                     break;
                 case 4:
                     $message = "Of course not.";
                     break;
                 case 5:
                     $message = "Ask again.";
                     break;
                 case 6:
                     $message = "Screw you!";
                     break;
             }
             break;
     }
     // traduz, se precisar
     $message = $translator->trans($message);
     // responde
     $data = array('message' => $message, 'image' => $image_path);
     $return['data'] = $data;
     $response = new JsonResponse($return);
     // cache
     $response->setPublic();
     $response->setSharedMaxAge(600000);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     return $response;
 }
Esempio n. 6
0
 /**
  * Convert the given URL to an absolute URL, using base URL from the given Request if the URL is not already \
  * absolute (including network URLs).
  *
  * @param string $url A URL, either absolute or relative.
  * @param Request $request An absolute URL, the site base URL.
  *
  * @return string Absolute URL.
  */
 public static function absoluteUrl($url, Request $request)
 {
     // Check for an absolute URL or a network URL, these get returned directly.
     if (preg_match('/^https?:/i', $url) || substr($url, 0, 2) === '//') {
         return $url;
     }
     return $request->getUriForPath('/' . ltrim($url, '/'));
 }
 protected function attemptAuthentication(Request $request)
 {
     $manager = $this->factory->getManager($this->options['manager'], $request->getUriForPath($this->options['check_path']));
     if (!$manager->getProtocol()->isValidationRequest($request)) {
         return null;
     }
     return $this->authenticationManager->authenticate($manager->createToken($request));
 }
Esempio n. 8
0
 /**
  * {@inheritdoc}
  */
 public function create()
 {
     if (null === $this->request) {
         return null;
     }
     $http = new Http($this->request->getUriForPath($this->request->getPathInfo()), $this->request->getMethod());
     $queryString = $this->request->getQueryString();
     if (strlen($queryString) > 0) {
         $http->setQueryString($queryString);
     }
     $http->setData($this->request->request->all());
     $http->setCookies($this->request->cookies->all());
     $http->setHeaders(array_map(function (array $values) {
         return count($values) === 1 ? reset($values) : $values;
     }, $this->request->headers->all()));
     $http->setEnv($this->request->server->all());
     return $http;
 }
 /**
  * @param Request $request
  * @param null|AuthenticationException $authException
  * @return Response
  */
 public function start(Request $request, AuthenticationException $authException = null)
 {
     $action = $this->config['login_action'];
     $manager = $this->factory->getManager($this->config['manager'], $request->getUriForPath($this->config['check_path']));
     if ($action) {
         return $this->httpKernel->forward($action, array('manager' => $manager, 'request' => $request, 'exception' => $authException));
     }
     return new RedirectResponse($manager->getServer()->getLoginUrl());
 }
 /**
  * @param Request $request
  * @param null|AuthenticationException $authException
  *
  * @return Response
  */
 public function onLogoutSuccess(Request $request)
 {
     $action = $this->config['logout_action'];
     $manager = $this->factory->getManager($this->config['manager'], $request->getUriForPath($this->config['check_path']));
     if ($action) {
         return $this->httpKernel->forward($action, array('manager' => $manager, 'request' => $request));
     }
     return new RedirectResponse($manager->getServer()->getLogoutUrl());
 }
 /**
  * Generates a proxy URI for a given controller.
  *
  * @param ControllerReference  $reference A ControllerReference instance
  * @param Request              $request    A Request instance
  *
  * @return string A proxy URI
  */
 protected function generateProxyUri(ControllerReference $reference, Request $request)
 {
     if (!isset($reference->attributes['_format'])) {
         $reference->attributes['_format'] = $request->getRequestFormat();
     }
     $reference->attributes['_controller'] = $reference->controller;
     $reference->query['_path'] = http_build_query($reference->attributes, '', '&');
     return $request->getUriForPath($this->proxyPath . '?' . http_build_query($reference->query, '', '&'));
 }
Esempio n. 12
0
 /**
  * Creates a redirect Response.
  *
  * @param Request $request A Request instance
  * @param string  $path    A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
  * @param integer $status  The status code
  *
  * @return Response A RedirectResponse instance
  */
 public function createRedirectResponse(Request $request, $path, $status = 302)
 {
     if (0 === strpos($path, '/')) {
         $path = $request->getUriForPath($path);
     } elseif (0 !== strpos($path, 'http')) {
         $path = $this->generateUrl($path, true);
     }
     return new RedirectResponse($path, 302);
 }
 /**
  * Returns a vcard for a profile
  * @param $profile
  * @param $includePhoto
  * @return VCard
  */
 public function getVCard($profile, $includePhoto)
 {
     $vcard = new VCard();
     $vcard->addName($profile['lastName'], $profile['firstName'])->addCompany($profile['company'])->addAddress('', '', $profile['address']['street'], $profile['address']['city'], $profile['address']['region'], $profile['address']['zip'], $profile['address']['country'])->addEmail($profile['email'])->addURL($profile['url'])->addPhoneNumber($profile['phone']['work'], 'WORK')->addPhoneNumber($profile['phone']['mobile'], 'CELL')->addJobtitle($profile['jobTitle']);
     // Add photo
     if ($profile['photo'] != null) {
         $photoUri = null;
         if ($includePhoto) {
             // Generate filesystem URI
             $webDir = $this->kernelRootDir . '/../web/';
             $photoUri = $webDir . $profile['photo'];
         } else {
             // Generate absolute public URI
             $photoUri = $this->request->getUriForPath('/' . $profile['photo']);
         }
         $vcard->addPhoto($photoUri, $includePhoto);
     }
     return $vcard;
 }
Esempio n. 14
0
 public function open($args = false, $hidden = [])
 {
     if ($args === false) {
         $args = ['action' => $this->request->getUri()];
     } else {
         if (is_string($args)) {
             $args = '/' . ltrim($args, '/');
             $args = ['action' => $this->request->getUriForPath($args)];
         }
     }
     if (!isset($args['method'])) {
         $args['method'] = 'POST';
     }
     $s = '<form' . $this->expandArgs($args) . '>';
     foreach ($hidden as $name => $value) {
         $s .= '<input type="hidden" name="' . htmlentities($name) . '" value="' . htmlentities($value) . '">';
     }
     return $s;
 }
 /**
  * @param Request $request
  * @param null|AuthenticationException $authException
  * @return Response
  */
 public function start(Request $request, AuthenticationException $authException = null)
 {
     $action = $this->config['login_action'];
     $manager = $this->factory->getManager($this->config['manager'], $request->getUriForPath($this->config['check_path']));
     if ($action) {
         $subRequest = $request->duplicate(null, null, array('_controller' => $action, 'manager' => $manager, 'request' => $request, 'exception' => $authException));
         return $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
     }
     return new RedirectResponse($manager->getServer()->getLoginUrl());
 }
 public function getResult(Request $request)
 {
     $listingRequest = new PropertyListingRequest();
     // TODO: strict validation of arguments
     $listingRequest->setPerPage((int) $request->get('per_page', 100));
     $listingRequest->setPage((int) $request->get('page', 1));
     $properties = $this->apiFactory->newListPropertiesUseCase()->listProperties($listingRequest);
     $response = $this->app->json($this->apiFactory->newPropertyListSerializer()->serialize($properties));
     (new PaginationHeaderSetter($response->headers))->setHeaders($request->getUriForPath('/properties'), $listingRequest, count($properties->getElements()));
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function start(Request $request, AuthenticationException $authException = null)
 {
     $redirect_uri = $request->getUriForPath($this->options->get('check_path', ''));
     if ($this->options->get('server_url') && $this->options->get('app_url')) {
         $redirect_uri = str_replace($this->options->get('server_url'), $this->options->get('app_url'), $redirect_uri);
     }
     $loginUrl = $this->facebook->getLoginUrl(array('display' => $this->options->get('display', 'page'), 'scope' => implode(',', $this->permissions), 'redirect_uri' => $redirect_uri));
     if ($this->options->get('server_url') && $this->options->get('app_url')) {
         return new Response('<html><head></head><body><script>top.location.href="' . $loginUrl . '";</script></body></html>');
     }
     return new RedirectResponse($loginUrl);
 }
 /**
  * @param Request $request
  *
  * @return RedirectResponse|void
  */
 protected function checkAlreadyLogin(Request $request)
 {
     if ($this->get('dos.user.security')->isLoggedIn()) {
         if ($this->alreadyLoginUrl) {
             return $this->redirect($this->alreadyLoginUrl);
         }
         if ($this->alreadyLoginRoute) {
             return $this->redirectToRoute($this->alreadyLoginRoute);
         }
         return $this->redirect($request->headers->get('referer', $request->getUriForPath('/')));
     }
     return;
 }
 public function grantTypeAuthorizationCodeAction(Request $request)
 {
     $parameters = array('grant_type' => 'authorization_code', 'code' => $request->query->get('code'), 'redirect_uri' => $request->getUriForPath('/demo/response_type/code'), 'client_id' => 'authorization_code_grant', 'client_secret' => 'uoce8AeP');
     $server = array();
     $client = new Client($this->get('kernel'));
     $crawler = $client->request('POST', '/api/v1.0/oauth2/token', $parameters, array(), $server);
     $accessTokenResponse = json_decode($client->getResponse()->getContent(), true);
     $accessTokenRequest = get_object_vars($client->getRequest());
     $modelPath = $this->get('router')->generate('demo_resource_type_model', array('access_token' => $accessTokenResponse['access_token']));
     $debugPath = $this->get('router')->generate('demo_resource_type_debug_endpoint', array('access_token' => $accessTokenResponse['access_token']));
     $refreshPath = $this->get('router')->generate('demo_grant_type_refresh_token', array('username' => 'authorization_code_grant', 'password' => 'uoce8AeP', 'refresh_token' => $accessTokenResponse['refresh_token']));
     return $this->render('TestBundle:demo/grant_type:authorization_code.html.twig', array('access_token_response' => $accessTokenResponse, 'access_token_request' => $accessTokenRequest, 'model_path' => $modelPath, 'debug_path' => $debugPath, 'refresh_path' => $refreshPath));
 }
Esempio n. 20
0
 public function onAuthenticationSuccess(Request $request,
                                         TokenInterface $token)
 {
     $user = $token->getUser();
     $session = $request->getSession();
     $session->setLocale($user->getLocale());
     
     if ($targetUrl = $session->get('_security.target_path')) {
         $session->remove('_security.target_path');
     }
     else {
         $targetUrl = '/';
     }
     
     return new RedirectResponse(0 !== strpos($targetUrl, 'http') ? $request->getUriForPath($targetUrl) : $targetUrl);
 }
 /**
  * Generates a fragment URI for a given controller.
  *
  * @param ControllerReference  $reference A ControllerReference instance
  * @param Request              $request    A Request instance
  *
  * @return string A fragment URI
  */
 protected function generateFragmentUri(ControllerReference $reference, Request $request)
 {
     // We need to forward the current _format and _locale values as we don't have
     // a proper routing pattern to do the job for us.
     // This makes things inconsistent if you switch from rendering a controller
     // to rendering a route if the route pattern does not contain the special
     // _format and _locale placeholders.
     if (!isset($reference->attributes['_format'])) {
         $reference->attributes['_format'] = $request->getRequestFormat();
     }
     if (!isset($reference->attributes['_locale'])) {
         $reference->attributes['_locale'] = $request->getLocale();
     }
     $reference->attributes['_controller'] = $reference->controller;
     $reference->query['_path'] = http_build_query($reference->attributes, '', '&');
     return $request->getUriForPath($this->fragmentPath . '?' . http_build_query($reference->query, '', '&'));
 }
 /**
  * Generates a page for the first step of password recovery process.
  *
  * @param Request $request
  * @return string Rendered page content
  */
 public function indexAction(Request $request)
 {
     if ($this->getOperator()) {
         // If the operator is logged in just redirect him to the home page.
         return $this->redirect($request->getUriForPath('/operator'));
     }
     $page = array('version' => MIBEW_VERSION, 'title' => getlocal('Trouble Accessing Your Account?'), 'headertitle' => getlocal('Mibew Messenger'), 'show_small_login' => true, 'fixedwrap' => true, 'errors' => array());
     $login_or_email = '';
     if ($request->isMethod('POST')) {
         // When HTTP GET method is used the form is just rendered but the
         // user does not pass any data. Thus we need to prevent CSRF attacks
         // only for POST requests
         csrf_check_token($request);
     }
     if ($request->isMethod('POST') && $request->request->has('loginoremail')) {
         $login_or_email = $request->request->get('loginoremail');
         $to_restore = MailUtils::isValidAddress($login_or_email) ? operator_by_email($login_or_email) : operator_by_login($login_or_email);
         if (!$to_restore) {
             $page['errors'][] = getlocal('No such Operator');
         }
         $email = $to_restore['vcemail'];
         if (count($page['errors']) == 0 && !MailUtils::isValidAddress($email)) {
             $page['errors'][] = "Operator hasn't set his e-mail";
         }
         if (count($page['errors']) == 0) {
             $token = sha1($to_restore['vclogin'] . (function_exists('openssl_random_pseudo_bytes') ? openssl_random_pseudo_bytes(32) : time() + microtime() . mt_rand(0, 99999999)));
             // Update the operator
             $to_restore['dtmrestore'] = time();
             $to_restore['vcrestoretoken'] = $token;
             update_operator($to_restore);
             $href = $this->getRouter()->generate('password_recovery_reset', array('id' => $to_restore['operatorid'], 'token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
             // Load mail templates and substitute placeholders there.
             $mail_template = MailTemplate::loadByName('password_recovery', get_current_locale());
             if (!$mail_template) {
                 throw new \RuntimeException('Cannot load "password_recovery" mail template');
             }
             $this->sendMail(MailUtils::buildMessage($email, $email, $mail_template->buildSubject(), $mail_template->buildBody(array(get_operator_name($to_restore), $href))));
             $page['isdone'] = true;
             return $this->render('password_recovery', $page);
         }
     }
     $page['formloginoremail'] = $login_or_email;
     $page['localeLinks'] = get_locale_links();
     $page['isdone'] = false;
     return $this->render('password_recovery', $page);
 }
 /**
  * Builds the target URL according to the defined options.
  *
  * @param Request $request
  *
  * @return string
  */
 protected function determineTargetUrl(Request $request)
 {
     if ($this->options['always_use_default_target_path']) {
         return $this->options['default_target_path'];
     }
     if ($targetUrl = $request->get($this->options['target_path_parameter'], null, true)) {
         return $targetUrl;
     }
     if (null !== $this->providerKey && ($targetUrl = $request->getSession()->get('_security.' . $this->providerKey . '.target_path'))) {
         $request->getSession()->remove('_security.' . $this->providerKey . '.target_path');
         return $targetUrl;
     }
     if ($this->options['use_referer'] && ($targetUrl = $request->headers->get('Referer')) && $targetUrl !== $request->getUriForPath($this->options['login_path'])) {
         return $targetUrl;
     }
     return $this->options['default_target_path'];
 }
 /**
  * @Route("/locale/{locale}", name="pumukit_locale")
  */
 public function changeAction($locale, Request $request)
 {
     //TODO validate if is a valid locale using conf file.
     $this->get('session')->set('_locale', $locale);
     $referer = $request->headers->get("referer");
     $base = $request->getUriForPath("");
     $lastPath = str_replace($base, "", $referer);
     $route = $this->get('router')->getMatcher()->match($lastPath);
     //array_filter ARRAY_FILTER_USE_BOTH only in 5.6
     $params = array();
     foreach ($route as $k => $v) {
         if ("_" != $k[0]) {
             $params[$k] = $v;
         }
     }
     $url = $this->generateUrl($route["_route"], $params);
     return $this->redirect($url);
 }
Esempio n. 25
0
 protected function getFullUrl(Request $request, $path = '', $clear = array('/app_dev.php'))
 {
     $base = $request->getUriForPath('');
     $gen = '';
     if (!empty($path)) {
         $gen = $this->generateUrl($path);
     }
     $url = $base . $gen;
     if (!empty($clear)) {
         if (!is_array($clear)) {
             $clear = array($clear);
         }
         foreach ($clear as $r) {
             $url = str_replace($r, '', $url);
         }
     }
     return $url;
 }
Esempio n. 26
0
 public function onAuthenticationSuccess(Request $request, TokenInterface $token)
 {
     $user = $token->getUser();
     $session = $request->getSession();
     if ($user->getLocale()) {
         $session->setLocale($user->getLocale());
     } else {
         $session->setLocale($this->sm->getSettings()->getDefaultLocale());
     }
     if ($user->getTheme()) {
         $session->set('cuteflow_theme', $user->getTheme());
     }
     $user->setLastLogin(new \DateTime());
     $this->em->persist($user);
     $this->em->flush();
     if ($targetUrl = $session->get('_security.target_path')) {
         $session->remove('_security.target_path');
     } else {
         $targetUrl = '/';
     }
     return new RedirectResponse(0 !== strpos($targetUrl, 'http') ? $request->getUriForPath($targetUrl) : $targetUrl);
 }
Esempio n. 27
0
 /**
  * Creates a Request.
  *
  * @param Request $request The current Request instance
  * @param string  $path    A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
  *
  * @return Request A Request instance
  */
 public function createRequest(Request $request, $path)
 {
     if ($path && '/' !== $path[0] && 0 !== strpos($path, 'http')) {
         $path = $this->generateUrl($path, true);
     }
     if (0 !== strpos($path, 'http')) {
         $path = $request->getUriForPath($path);
     }
     $newRequest = Request::create($path, 'get', array(), $request->cookies->all(), array(), $request->server->all());
     if ($session = $request->getSession()) {
         $newRequest->setSession($session);
     }
     if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) {
         $newRequest->attributes->set(SecurityContextInterface::AUTHENTICATION_ERROR, $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR));
     }
     if ($request->attributes->has(SecurityContextInterface::ACCESS_DENIED_ERROR)) {
         $newRequest->attributes->set(SecurityContextInterface::ACCESS_DENIED_ERROR, $request->attributes->get(SecurityContextInterface::ACCESS_DENIED_ERROR));
     }
     if ($request->attributes->has(SecurityContextInterface::LAST_USERNAME)) {
         $newRequest->attributes->set(SecurityContextInterface::LAST_USERNAME, $request->attributes->get(SecurityContextInterface::LAST_USERNAME));
     }
     return $newRequest;
 }
Esempio n. 28
0
    /**
     * Creates a redirect Response.
     *
     * @param Request $request A Request instance
     * @param string  $path    A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
     * @param integer $status  The status code
     *
     * @return Response A RedirectResponse instance
     */
    public function createRedirectResponse(Request $request, $path, $status = 302)
    {
        if (0 === strpos($path, '/')) {
            $path = $request->getUriForPath($path);
        } elseif (0 !== strpos($path, 'http')) {
            // hack (don't have a better solution for now)
            $context = $this->router->getContext();
            try {
                $parameters = $this->router->match($request->getPathInfo());
            } catch (\Exception $e) {
            }

            if (isset($parameters['_locale'])) {
                $context->setParameter('_locale', $parameters['_locale']);
            } elseif ($session = $request->getSession()) {
                $context->setParameter('_locale', $session->getLocale());
            }

            $path = $this->generateUrl($path, true);
        }

        return new RedirectResponse($path, 302);
    }
Esempio n. 29
0
 /**
  * @covers Symfony\Component\HttpFoundation\Request::getUriForPath
  */
 public function testGetUriForPath()
 {
     $request = Request::create('http://test.com/foo?bar=baz');
     $this->assertEquals('http://test.com/some/path', $request->getUriForPath('/some/path'));
     $request = Request::create('http://test.com:90/foo?bar=baz');
     $this->assertEquals('http://test.com:90/some/path', $request->getUriForPath('/some/path'));
     $request = Request::create('https://test.com/foo?bar=baz');
     $this->assertEquals('https://test.com/some/path', $request->getUriForPath('/some/path'));
     $request = Request::create('https://test.com:90/foo?bar=baz');
     $this->assertEquals('https://test.com:90/some/path', $request->getUriForPath('/some/path'));
     $server = array();
     // Standard Request on non default PORT
     // http://host:8080/index.php/path/info?query=string
     $server['HTTP_HOST'] = 'host:8080';
     $server['SERVER_NAME'] = 'servername';
     $server['SERVER_PORT'] = '8080';
     $server['QUERY_STRING'] = 'query=string';
     $server['REQUEST_URI'] = '/index.php/path/info?query=string';
     $server['SCRIPT_NAME'] = '/index.php';
     $server['PATH_INFO'] = '/path/info';
     $server['PATH_TRANSLATED'] = 'redirect:/index.php/path/info';
     $server['PHP_SELF'] = '/index_dev.php/path/info';
     $server['SCRIPT_FILENAME'] = '/some/where/index.php';
     $request = new Request();
     $request->initialize(array(), array(), array(), array(), array(), $server);
     $this->assertEquals('http://host:8080/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with non default port');
     // Use std port number
     $server['HTTP_HOST'] = 'host';
     $server['SERVER_NAME'] = 'servername';
     $server['SERVER_PORT'] = '80';
     $request->initialize(array(), array(), array(), array(), array(), $server);
     $this->assertEquals('http://host/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port');
     // Without HOST HEADER
     unset($server['HTTP_HOST']);
     $server['SERVER_NAME'] = 'servername';
     $server['SERVER_PORT'] = '80';
     $request->initialize(array(), array(), array(), array(), array(), $server);
     $this->assertEquals('http://servername/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port without HOST_HEADER');
     // Request with URL REWRITING (hide index.php)
     //   RewriteCond %{REQUEST_FILENAME} !-f
     //   RewriteRule ^(.*)$ index.php [QSA,L]
     // http://host:8080/path/info?query=string
     $server = array();
     $server['HTTP_HOST'] = 'host:8080';
     $server['SERVER_NAME'] = 'servername';
     $server['SERVER_PORT'] = '8080';
     $server['REDIRECT_QUERY_STRING'] = 'query=string';
     $server['REDIRECT_URL'] = '/path/info';
     $server['SCRIPT_NAME'] = '/index.php';
     $server['QUERY_STRING'] = 'query=string';
     $server['REQUEST_URI'] = '/path/info?toto=test&1=1';
     $server['SCRIPT_NAME'] = '/index.php';
     $server['PHP_SELF'] = '/index.php';
     $server['SCRIPT_FILENAME'] = '/some/where/index.php';
     $request->initialize(array(), array(), array(), array(), array(), $server);
     $this->assertEquals('http://host:8080/some/path', $request->getUriForPath('/some/path'), '->getUri() with rewrite');
     // Use std port number
     //  http://host/path/info?query=string
     $server['HTTP_HOST'] = 'host';
     $server['SERVER_NAME'] = 'servername';
     $server['SERVER_PORT'] = '80';
     $request->initialize(array(), array(), array(), array(), array(), $server);
     $this->assertEquals('http://host/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite and default port');
     // Without HOST HEADER
     unset($server['HTTP_HOST']);
     $server['SERVER_NAME'] = 'servername';
     $server['SERVER_PORT'] = '80';
     $request->initialize(array(), array(), array(), array(), array(), $server);
     $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite, default port without HOST_HEADER');
     $this->assertEquals('servername', $request->getHttpHost());
     // with user info
     $server['PHP_AUTH_USER'] = '******';
     $request->initialize(array(), array(), array(), array(), array(), $server);
     $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'));
     $server['PHP_AUTH_PW'] = 'symfony';
     $request->initialize(array(), array(), array(), array(), array(), $server);
     $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'));
 }
Esempio n. 30
0
 /**
  * Generates a URI, based on the given path or absolute URL.
  *
  * @param Request $request A Request instance
  * @param string  $path    A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
  *
  * @return string An absolute URL
  *
  * @throws \LogicException
  */
 public function generateUri($request, $path)
 {
     if (0 === strpos($path, 'http') || !$path) {
         return $path;
     }
     if ('/' === $path[0]) {
         return $request->getUriForPath($path);
     }
     if (null === $this->urlGenerator) {
         throw new \LogicException('You must provide a UrlGeneratorInterface instance to be able to use routes.');
     }
     $url = $this->urlGenerator->generate($path, $request->attributes->all(), UrlGeneratorInterface::ABSOLUTE_URL);
     // unnecessary query string parameters must be removed from URL
     // (ie. query parameters that are presents in $attributes)
     // fortunately, they all are, so we have to remove entire query string
     $position = strpos($url, '?');
     if (false !== $position) {
         $url = substr($url, 0, $position);
     }
     return $url;
 }