本文整理汇总了PHP中Silex\Application::redirect方法的典型用法代码示例。如果您正苦于以下问题:PHP Application::redirect方法的具体用法?PHP Application::redirect怎么用?PHP Application::redirect使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Silex\Application
的用法示例。
在下文中一共展示了Application::redirect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: connect
public function connect(Application $app)
{
$controllers = new ControllerCollection();
$controllers->get('auth', function () use($app) {
if ($app['session']->has($app['config']['prefix'] . 'authed-user')) {
return $app->redirect('/');
}
return $app['twig']->render('PT/pages/authenticate.html', array('auth_path' => $app['uri']->generate('authenticate')));
})->bind('authenticate');
$controllers->post('auth', function () use($app) {
if ($app['request']->get('username') === $app['config']['authenticate']['username'] && $app['request']->get('password') === $app['config']['authenticate']['password']) {
$userHash = $userHash = sha1($app['config']['authenticate']['username'] . $app['config']['authenticate']['password']);
$currentUser = $app['session']->set($app['config']['prefix'] . 'authed-user', $userHash);
return $app->redirect('/');
} else {
$app['session']->setFlash('error', 'error');
$app['session']->remove($app['config']['prefix'] . 'authed-user');
return $app->redirect($app['uri']->generate('authenticate'));
}
})->bind('do_authenticate');
$controllers->get('deauth', function ($result) use($app) {
$app['session']->remove($app['config']['prefix'] . 'authed-user');
return $app->redirect($app['uri']->generate('authenticate'));
})->value('result', null)->bind('de_authenticate');
return $controllers;
}
示例2: connect
/**
* Silex method that exposes routes to the app
*
* @param Silex\Application $app Application instance
*
* @return Silex\ControllerCollection Object encapsulating crafted routes
*/
public function connect(Application $app)
{
$ctrl = $app['controllers_factory'];
/**
* Homepage
*/
$ctrl->get('/', function () use($app) {
$root = str_replace('index.php/', '', $app['url_generator']->generate('home'));
if ($app['request']->getRequestURI() != $root) {
return $app->redirect($root, Response::HTTP_MOVED_PERMANENTLY);
}
return $app['twig']->render('front/partials/home.twig');
})->bind('home');
/**
* Admin root
*/
$ctrl->get('/admin', function () use($app) {
return $app->redirect($app['url_generator']->generate($app['config']['admin']['root']));
});
/**
* robots.txt
*/
$ctrl->get('/robots.txt', function () use($app) {
$response = new Response('User-agent: *' . PHP_EOL . ($app['debug'] ? 'Disallow: /' : 'Sitemap: ' . $app['url_generator']->generate('home') . 'sitemap.xml'));
$response->headers->set('Content-Type', 'text/plain');
return $response;
});
return $ctrl;
}
示例3: turn
/**
* Handle turn request then redirect to home
*
* @param Request $request
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function turn(Request $request)
{
// get the coordinate from the request
$coordinate = $request->get('coordinate');
// load game session
$this->loadGameSession();
switch ($coordinate) {
default:
// turn
$message = $this->doTurn($coordinate);
break;
case '':
$message = 'enter a coordinate';
break;
case 'show':
$this->getFlashBag()->set('show', '1');
$message = 'showing ships';
break;
case 'reset':
$this->resetGame();
$message = 'game restarted';
break;
}
// store message to display it next time
$this->getFlashBag()->add('message', $message);
// update session
$this->updateGameSession();
// redirect to home page
return $this->app->redirect($this->getUrlGenerator()->generate('home'));
}
示例4: index
public function index(Application $app, $firstChar, $page)
{
//Page number 0 or below
if ($page <= 0) {
$redirectUrl = "/a-z/{$firstChar}/1";
return $app->redirect($redirectUrl);
}
$data = $app['programme_api']->fetchPageData($firstChar, $page);
$successfulRequest = $data[0];
if ($successfulRequest) {
$pageData = $data[1];
$totalProgrammes = $pageData->atoz_programmes->count;
if ($totalProgrammes == 0) {
return $app['twig']->render('no-results.twig', array());
}
$perPage = $pageData->atoz_programmes->per_page;
$numberOfPages = ceil($totalProgrammes / $perPage);
if ($page > $numberOfPages) {
//Page number is past last page
$redirectUrl = "/a-z/{$firstChar}/{$numberOfPages}";
return $app->redirect($redirectUrl);
} else {
$programmes = $pageData->atoz_programmes->elements;
return $app['twig']->render('az.twig', array('firstChar' => $firstChar, 'numOfPages' => $numberOfPages, 'pageNo' => $page, 'programmes' => $programmes, 'imageSize' => '240x135'));
}
} else {
$error = $data[1];
$app->abort(500, 'jooooo');
}
}
示例5: register
public function register(Application $app)
{
$app['user.hydrator'] = function () use($app) {
return new UserHydrator($app['taxonomy.service'], new TermHydrator());
};
$app['user.manager'] = function () use($app) {
return new UserService($app['db'], $app['user.hydrator']);
};
$app['auth.mustAuthenticate'] = function (Application $app) {
return function () use($app) {
if (!$app['session']->has('user')) {
return $app->redirect($app['url_generator']->generate('auth.login'));
}
};
};
$app['auth.isAdmin'] = function (Application $app) {
return function () use($app) {
$user = $app['session']->get('user');
if (!$user || $user->role != 'ROLE_ADMIN') {
$app['session']->getFlashBag()->add('error', 'You do not have privileges for the requested page');
return $app->redirect($app['url_generator']->generate('index'));
}
};
};
$app['controller.auth'] = $app->share(function ($app) {
return new AuthController();
});
}
示例6: thumbAction
public function thumbAction(Request $request, Application $app)
{
$source = $request->get('src', false);
$width = $request->get('width', 250);
// Do requested thumbnail in correct format already exists ?
if ($app['flysystems']['thumbs']->has($width . "/" . $source)) {
return $app->redirect($request->getBasePath() . '/thumbs/' . $width . '/' . $source, 301);
}
// Do requested file exists ?
if (!$source || !$app['flysystems']['local']->has($source)) {
return new Response("Source file not found.", 404);
}
try {
$contents = $app['flysystems']['local']->read($source);
$imageManager = new ImageManager();
$image = $imageManager->make($contents);
$image->resize($width, null, function ($constraint) {
$constraint->aspectRatio();
});
$info = $app['flysystems']['local']->getWithMetadata($source, ['mimetype']);
$image->encode($info['mimetype']);
$app['flysystems']['thumbs']->put($width . "/" . $source, $image);
return $app->redirect($request->getBasePath() . '/thumbs/' . $width . '/' . $source, 301);
} catch (\Exception $e) {
return new Response("Erreur !", 500);
}
// Should not happen, everything failed. Display not found image :(
return $app->redirect($request->getBasePath() . '/assets/img/' . $width . '_not-found.png', 302);
}
示例7: connect
public function connect(Application $app)
{
$this->app = $app;
$jira = $app['controllers_factory'];
$jira->get('/connect/{redirect}', function (Request $request, $redirect) use($app) {
$token = $app['jira.oauth.temp_credentials']($redirect);
$app['session']->set('oauth', $token);
return $app->redirect($app['jira.oauth.auth_url']);
})->value('redirect', null)->bind('jira-connect');
$jira->get('/callback', function ($url, $verifier) use($app) {
$tempToken = $app['session']->get('oauth');
$app['jira.token'] = $tempToken;
$app['jira.oauth_verifier'] = $verifier;
$token = $app['jira.oauth.auth_credentials']($url);
$app['session']->set('oauth', $token);
return $app->redirect($url);
})->convert('url', function ($url, Request $request) {
if (!$request->query->has('url')) {
return $this->app['jira.default_redirect'];
}
$url = $request->get('url');
try {
return $this->app['url_generator']->generate($url);
} catch (RouteNotFoundException $e) {
return '/' . $url;
}
})->convert('verifier', function ($verifier, Request $request) {
if (!$request->query->has('oauth_verifier')) {
throw new \InvalidArgumentException('There was no oauth verifier in the request');
}
return $request->get('oauth_verifier');
})->bind('jira-callback');
return $jira;
}
示例8: getThingEditForm
private function getThingEditForm(Application $app, Request $request, $thingId)
{
$error = $request->query->get('error');
$repo = $app->getThingRepository();
$add = false;
$thing = $repo->getById($thingId);
if ($thing === null) {
$defaults = null;
$add = true;
} else {
$defaults = ['name' => $thing->getName(), 'email' => $thing->getEmail(), 'description' => $thing->getDescription()];
}
$form = $app['form.factory']->createBuilder('form', $defaults)->add('name', 'text')->add('email', 'email')->add('description', 'textarea', array('required' => false))->getForm();
// handle form submission
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
if ($add) {
$thing = new Thing();
}
$thing->setEmail(strtolower($data['email']))->setName($data['name'])->setDescription($data['description']);
if ($add) {
if (!$repo->add($thing)) {
return $app->redirect($app['url_generator']->generate('things_add', array('error' => 'Failed adding thing')));
}
} else {
$repo->update($thing);
}
return $app->redirect($app['url_generator']->generate('things_index'));
}
return new Response($app['twig']->render('edit.html.twig', ['form' => $form->createView(), 'thing' => $thing, 'error' => $error]));
}
示例9: connect
public function connect(Application $app)
{
$controllers = $app['controllers_factory'];
$controllers->get('/', function (Application $app, Request $request) {
$body = $app['twig']->render('signup.html', array('user' => array('name' => '', 'email' => '', 'password' => '6 chars minimum')));
return new Response($body, 200);
})->before(function (Request $request, Application $app) {
if ($app['user.logged_in']) {
return $app->redirect('/');
}
});
$controllers->post('/', function (Application $app, Request $request) {
$userService = $app['user.service'];
$post = $request->request->all();
$user = $userService->manageFormData($post);
if (\Filehosting\Service\UserService::VALIDATION_FAILED === $user) {
$user = $userService->identifyUser($request->cookies->all(), false);
$body = $app['twig']->render('failed.html', array('subject' => 'Validation', 'userID' => $user->getId() === null ? "" : $user->getId()));
return new Response($body, 200);
}
$app['em']->flush();
if (null === $user->getId()) {
throw new Exception("Не удалось сохранить пользователя в БД.");
}
$lm = $app['user.service.login_manager'];
if (!$lm->isLoggedIn()) {
$lm->logIn($user->getId());
}
return $app->redirect("/user/{$user->getId()}");
});
return $controllers;
}
示例10: authAction
public function authAction(Request $request, Application $app)
{
if ($app['session']->get('twitter_oauth_token') === null) {
// get the request token
$reply = $app['twitter']->oauth_requestToken(['oauth_callback' => $request->getUri()]);
if (empty($reply)) {
return new Response('Reply is empty');
}
// store the token
$app['twitter']->setToken($reply->oauth_token, $reply->oauth_token_secret);
$app['session']->set('twitter_oauth_token', $reply->oauth_token);
$app['session']->set('twitter_oauth_token_secret', $reply->oauth_token_secret);
$app['session']->set('twitter_oauth_verify', true);
// redirect to auth website
return $app->redirect($app['twitter']->oauth_authorize());
} elseif ($request->get('oauth_verifier') !== null && $app['session']->get('twitter_oauth_verify') !== null) {
// verify the token
$app['twitter']->setToken($app['session']->get('twitter_oauth_token'), $app['session']->get('twitter_oauth_token_secret'));
$app['session']->set('twitter_oauth_verify', null);
// get the access token
$reply = $app['twitter']->oauth_accessToken(['oauth_verifier' => $request->get('oauth_verifier')]);
// store the token (which is different from the request token!)
$app['session']->set('twitter_oauth_token', $reply->oauth_token);
$app['session']->set('twitter_oauth_token_secret', $reply->oauth_token_secret);
$app['session']->set('loggedin', true);
$app['session']->set('twitter_screen_name', $reply->screen_name);
return $app->redirect('/');
}
return $app->redirect('/logout');
}
示例11: addAction
public function addAction(Request $request, Application $app)
{
$newStudent = new Student();
$class = $app['dao.className']->findClassname($request->request->get('classname'));
$statuts = $app['dao.statutStudent']->findStatut($request->request->get('statut'));
if (null !== $request->request->get('id_student')) {
$newStudent->setIdStudent($request->request->get('id_student'));
}
$newStudent->setName($request->request->get('name'));
$newStudent->setFirstname($request->request->get('firstname'));
$newStudent->setBirthday($request->request->get('birthday'));
$newStudent->setAddress($request->request->get('address'));
$newStudent->setTel($request->request->get('phone'));
$newStudent->setEmail($request->request->get('email'));
$newStudent->setDtCreate(date('Y-m-d H:i:s'));
$newStudent->setDtUpdate(date('Y-m-d H:i:s'));
$newStudent->setClass($class);
$newStudent->setStatut($statuts);
$app['dao.student']->saveStudent($newStudent);
$classes = $app['dao.className']->findAll();
if (null !== $request->request->get('id_student')) {
$app['session']->getFlashBag()->add('success', 'L\'étudiant a bien été modifiée !');
//message flash success si réussi
return $app->redirect($app['url_generator']->generate('studentslist'));
} else {
$app['session']->getFlashBag()->add('success', 'L\'étudiant a bien été ajouté !');
//message flash success si réussi
return $app->redirect($app['url_generator']->generate('studentslist'));
}
}
示例12: uploadAction
public function uploadAction(Application $app, Request $request)
{
// Read file from request
$file = $request->files->get('savegame');
if ($file === null) {
throw new BadRequestHttpException("Savegame data not found in request. Did you chose a savegame\n before pressing Submit?");
}
// // Check upload was successful
if ($file->getError() !== UPLOAD_ERR_OK) {
throw new BadRequestHttpException("An error occured while uploading your savegame. Please try\n again and report the problem if it persists.");
}
// Read the data
$data = $file->openFile()->fread(4096);
// Check header
$header = substr($data, 0, 14);
if (!in_array($header, ['ISAACNGSAVE06R', 'ISAACNGSAVE08R'])) {
throw new BadRequestHttpException("Invalid file header. A savegame file should start with the\n string `ISAACNGSAVEXXR`.\n\nYou either uploaded a file wich is\n not a BOIR savegame, or the savegame version is not supported.");
}
// Calculate the hash which is used to identify the savegame
$hash = md5($data);
// If file already exists, skip the upload
if ($app['archiver']->exists($hash)) {
return $app->redirect('/show/' . $hash);
}
// Save the file
$app['archiver']->save($data);
// Redirect to show
return $app->redirect('/show/' . $hash);
}
示例13: editAction
public function editAction(Application $app, Request $request)
{
$usersModel = new usersModel($app);
$id = (int) $request->get('id', 0);
$user = $usersModel->getUser($id);
$usersModel = new UsersModel($app);
$user['roles'] = $usersModel->getRoles();
if (count($user)) {
$form = $app['form.factory']->createBuilder(new UserForm(), $user)->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$data['role_id'] = $data['role'];
$data['password'] = $app['security.encoder.digest']->encodePassword($data['password'], '');
unset($data['roles'], $data['role']);
var_dump($data);
$usersModel = new usersModel($app);
$usersModel->saveUser($data);
$app['session']->getFlashBag()->add('message', array('type' => 'success', 'content' => $app['translator']->trans('User edited')));
return $app->redirect($app['url_generator']->generate('users_index'), 301);
}
$this->view['id'] = $id;
$this->view['form'] = $form->createView();
} else {
return $app->redirect($app['url_generator']->generate('users_add'), 301);
}
return $app['twig']->render('users/edit.twig', $this->view);
}
示例14: view
public function view(Request $request, Application $app, $appName, $resetPasswordKey = '')
{
switch ($appName) {
/** @noinspection PhpMissingBreakStatementInspection */
case 'reset_password':
$user = new UserModelBase();
if (!$user->readByProperty('resetPasswordKey', $resetPasswordKey)) {
$app['session']->getFlashBag()->add('errorMessage', 'Your password reset cannot be completed. Please try again.');
return $app->redirect('/auth/login');
}
if (!$user->hasForgottenPassword(false)) {
$app['session']->getFlashBag()->add('errorMessage', 'Your password reset cannot be completed. It may have expired. Please try again.');
return $app->redirect('/auth/login');
}
// no break; - intentional fall through to next case
// no break; - intentional fall through to next case
case 'forgot_password':
case 'login':
$this->setupNgView($app, $appName);
$this->setupAuthView($request, $app);
return $this->renderPage($app, 'angular-app');
break;
default:
return $this->renderPage($app, $appName);
}
}
示例15: oauthRedirectAction
/**
* Отправляет пользователя на нужный url, для oauth авторизации
*
* @param Request $request
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function oauthRedirectAction(Request $request)
{
$provider = $request->get('provider', null);
if (null === $provider) {
throw new BadRequestHttpException('Bad request params');
}
return $this->app->redirect($this->app['gitlab_api']->getAuthUrl());
}