php Symfony-Component-HttpFoundation-Session-Session类(方法)实例源码

下面列出了php Symfony-Component-HttpFoundation-Session-Session 类(方法)源码代码实例,从而了解它的用法。

作者:fresnostate-librar    项目:xerxe   
/**
  * Create new Xerxes Request
  */
 public static function createFromGlobals(ControllerMap $controller_map)
 {
     $registry = Registry::getInstance();
     // reverse proxy
     if ($registry->getConfig("REVERSE_PROXIES", false)) {
         self::$trustProxy = true;
         self::$trustedProxies = explode(',', $registry->getConfig("REVERSE_PROXIES"));
     }
     // request
     $request = parent::createFromGlobals();
     // set cookie path and name
     $basepath = $request->getBasePath();
     $id = strtolower($basepath);
     $id = preg_replace('/\\//', '_', $id);
     $id = 'xerxessession_' . $id;
     $session_options = array('name' => $id, 'cookie_path' => $basepath == '' ? '/' : $basepath);
     $storage = new NativeSessionStorage($session_options);
     // session
     $session = new Session($storage);
     $session->start();
     // register these mo-fo's
     $request->setRegistry($registry);
     $request->setSession($session);
     $request->setControllerMap($controller_map);
     // do our special mapping
     $request->extractQueryParams();
     return $request;
 }

作者:rombar    项目:PgExplore   
/**
  * @param Registry $doctrine
  * @param Session $session
  * @param Logger $logger
  * @param Parameters $parameters
  */
 public function __construct(Registry $doctrine, Session $session, Logger $logger, Parameters $parameters)
 {
     $this->doctrine = $doctrine;
     $this->session = $session;
     $this->logger = $logger;
     $this->parameters = $parameters;
     $fromRetriever = new PgRetriever($doctrine, $this->logger, $this->parameters->getManagerFrom());
     $fromRetriever->setIndexType(PgRetriever::INDEX_TYPE_NAME);
     $fromMassRetriever = new PgMassRetriever($doctrine, $this->logger, $this->parameters->getManagerFrom());
     $toRetriever = new PgRetriever($doctrine, $this->logger, $this->parameters->getManagerTo());
     $toRetriever->setIndexType(PgRetriever::INDEX_TYPE_NAME);
     $toMassRetriever = new PgMassRetriever($doctrine, $this->logger, $this->parameters->getManagerTo());
     $this->fromAnalyzer = new PgAnalyzer($this->logger, $fromRetriever, $fromMassRetriever);
     $this->toAnalyzer = new PgAnalyzer($this->logger, $toRetriever, $toMassRetriever);
     if ($this->session->has(SyncHandler::SESSION_FROM_KEY)) {
         $this->fromAnalyzer->setSchemas($this->session->get(SyncHandler::SESSION_FROM_KEY));
         $this->fromAnalyzer->initTables();
     } else {
         $this->fromAnalyzer->initSchemas();
         $this->fromAnalyzer->initSchemasElements();
         $this->fromAnalyzer->initCompareTableInfo();
         //$this->session->set(SyncHandler::SESSION_FROM_KEY, $this->fromAnalyzer->getSchemas());
     }
     if ($this->session->has(SyncHandler::SESSION_TO_KEY)) {
         $this->toAnalyzer->setSchemas($this->session->get(SyncHandler::SESSION_TO_KEY));
         $this->toAnalyzer->initTables();
     } else {
         $this->toAnalyzer->initSchemas();
         $this->toAnalyzer->initSchemasElements();
         $this->toAnalyzer->initCompareTableInfo();
         $this->toAnalyzer->initTables();
         //$this->session->set(SyncHandler::SESSION_TO_KEY, $this->toAnalyzer->getSchemas());
     }
 }

作者:kmachoC    项目:Sigpr   
/**
  * @Route("/units/{id}", name="unit_show")
  * @Template()
  */
 public function showAction($id)
 {
     $session = new Session();
     $array = array();
     $user = $session->get('user');
     if ($user) {
         $array['user'] = $user;
     }
     $request = $this->get('request');
     $p_researchers = $request->query->get('p_researcher');
     $p_projects = $request->query->get('p_project');
     $service = $this->get("unit.service");
     $researchers = $service->getInv($id, $p_researchers, 20);
     $projects = $service->getProjectsByUnit($id, $p_projects, 20);
     $c_researchers = $service->getAllInv($id);
     $c_projects = $service->getAllProjectsByUnit($id);
     $states = array();
     for ($i = 0; $i < count($projects); $i++) {
         if (!in_array($projects[$i]["cestado"], $states)) {
             $states[$projects[$i]["cestado"]] = $projects[$i]["estado"];
         }
     }
     $unit = $service->getInfoByUnit($id);
     //  var_dump($unit);
     $array['states'] = $states;
     $array['projects'] = $projects;
     $array['p_researcher'] = $p_researchers;
     $array['p_project'] = $p_projects;
     $array['c_researcher'] = ceil(count($c_researchers) / 20);
     $array['c_project'] = ceil(count($c_projects) / 20);
     $array['researchers'] = $researchers;
     $array['unit'] = $unit;
     return $array;
 }

作者:bestmodule    项目:alertify-bundl   
/**
  * Alertify filter
  * @param TwigEnvironment $environment
  * @param Session         $session
  *
  * @return string
  */
 public function alertifyFilter($environment, Session $session)
 {
     $flashes = $session->getFlashBag()->all();
     $renders = array();
     foreach ($flashes as $type => $flash) {
         if ($type == "callback") {
             foreach ($flash as $key => $currentFlash) {
                 $currentFlash['body'] .= $environment->render('AvAlertifyBundle:Modal:callback.html.twig', $currentFlash);
                 $session->getFlashBag()->add($currentFlash['engine'], $currentFlash);
                 $renders[$type . $key] = $this->alertifyFilter($session);
             }
         } else {
             foreach ($flash as $key => $content) {
                 if (is_array($content)) {
                     $context = isset($content['context']) ? $content['context'] : null;
                     $defaultParameters = self::getDefaultParametersFromContext($context);
                     $parameters = array_merge($defaultParameters, $content);
                 } else {
                     $defaultParameters = self::getDefaultParametersFromContext(null);
                     $parameters = array_merge($defaultParameters, array('body' => $content));
                 }
                 $parameters['type'] = $type;
                 $renders[$type . $key] = $environment->render('AvAlertifyBundle:Modal:' . $parameters['engine'] . '.html.twig', $parameters);
             }
         }
     }
     return implode(' ', $renders);
 }

作者:rakesh-mohant    项目:oauth2-symfony-bundl   
public function testImplicitGrant()
 {
     // Start session manually.
     $session = new Session(new MockFileSessionStorage());
     $session->start();
     // Query authorization endpoint with response_type = token.
     $parameters = array('response_type' => 'token', 'client_id' => 'http://democlient1.com/', 'redirect_uri' => 'http://democlient1.com/redirect_uri', 'scope' => 'demoscope1', 'state' => $session->getId());
     $server = array('PHP_AUTH_USER' => 'demousername1', 'PHP_AUTH_PW' => 'demopassword1');
     $client = $this->createClient();
     $crawler = $client->request('GET', '/api/oauth2/authorize', $parameters, array(), $server);
     $this->assertTrue($client->getResponse()->isRedirect());
     // Check basic auth response that can simply compare.
     $authResponse = Request::create($client->getResponse()->headers->get('Location'), 'GET');
     $this->assertEquals('http://democlient1.com/redirect_uri', $authResponse->getSchemeAndHttpHost() . $authResponse->getBaseUrl() . $authResponse->getPathInfo());
     // Check basic token response that can simply compare.
     $tokenResponse = $authResponse->query->all();
     $this->assertEquals('bearer', $tokenResponse['token_type']);
     $this->assertEquals('demoscope1', $tokenResponse['scope']);
     $this->assertEquals($session->getId(), $tokenResponse['state']);
     // Query debug endpoint with access_token.
     $parameters = array();
     $server = array('HTTP_Authorization' => implode(' ', array('Bearer', $tokenResponse['access_token'])));
     $client = $this->createClient();
     $crawler = $client->request('GET', '/api/oauth2/debug', $parameters, array(), $server);
     $debugResponse = json_decode($client->getResponse()->getContent(), true);
     $this->assertEquals('demousername1', $debugResponse['username']);
 }

作者:swnsm    项目:coursework3.   
public function getUserDataHeader(Session $session)
 {
     if (!$session->has('userId')) {
         return null;
     }
     return ['name' => $session->get('userName'), 'secondName' => $session->get('userSName'), 'role' => $session->get('userRole')];
 }

作者:ls    项目:OneupUploaderBundl   
public function setUp()
 {
     $this->numberOfPayloads = 5;
     $this->realDirectory = sys_get_temp_dir() . '/storage';
     $this->chunkDirectory = $this->realDirectory . '/' . $this->chunksKey;
     $this->tempDirectory = $this->realDirectory . '/' . $this->orphanageKey;
     $this->payloads = array();
     if (!$this->checkIfTempnameMatchesAfterCreation()) {
         $this->markTestSkipped('Temporary directories do not match');
     }
     $filesystem = new \Symfony\Component\Filesystem\Filesystem();
     $filesystem->mkdir($this->realDirectory);
     $filesystem->mkdir($this->chunkDirectory);
     $filesystem->mkdir($this->tempDirectory);
     $adapter = new Adapter($this->realDirectory, true);
     $filesystem = new GaufretteFilesystem($adapter);
     $this->storage = new GaufretteStorage($filesystem, 100000);
     $chunkStorage = new GaufretteChunkStorage($filesystem, 100000, null, 'chunks');
     // create orphanage
     $session = new Session(new MockArraySessionStorage());
     $session->start();
     $config = array('directory' => 'orphanage');
     $this->orphanage = new GaufretteOrphanageStorage($this->storage, $session, $chunkStorage, $config, 'cat');
     for ($i = 0; $i < $this->numberOfPayloads; $i++) {
         // create temporary file as if it was reassembled by the chunk manager
         $file = tempnam($this->chunkDirectory, 'uploader');
         $pointer = fopen($file, 'w+');
         fwrite($pointer, str_repeat('A', 1024), 1024);
         fclose($pointer);
         //gaufrette needs the key relative to it's root
         $fileKey = str_replace($this->realDirectory, '', $file);
         $this->payloads[] = new GaufretteFile(new File($fileKey, $filesystem), $filesystem);
     }
 }

作者:GrizliK198    项目:symfony-certification-prepare-projec   
function initSession()
{
    $storage = new NativeSessionStorage(['cookie_lifetime' => 3600, 'gc_probability' => 1, 'gc_divisor' => 1, 'gc_maxlifetime' => 10000], new NativeFileSessionHandler());
    $session = new Session($storage, new NamespacedAttributeBag());
    $session->start();
    return $session;
}

作者:jacobjj    项目:PageKit-framewor   
/**
  * {@inheritdoc}
  */
 protected function getSessionToken()
 {
     if (!$this->session->has($this->name)) {
         $this->session->set($this->name, sha1(uniqid(rand(), true)));
     }
     return $this->session->get($this->name);
 }

作者:stze    项目:siacolweb-servici   
public function environmentSessionController(FilterControllerEvent $event)
 {
     $controller = $event->getController();
     $session = new Session();
     $environment = $session->get('environment');
     // Validar si hay un environment cargado a la session de usuario
     if (isset($environment)) {
         // Validar si el controller es una instacia de InitController
         if ($controller[0] instanceof InitController) {
             // ****** if auth
             // ****** redirect home
             // ****** no
             // ****** redirect login
             return;
         }
         return;
     } else {
         // NO exite un environment cargado
         // Validar si el controller NO es instacia de InitController
         if (!$controller[0] instanceof InitController) {
             //redireccion a init controller
             $redirectUrl = '/init';
             $event->setController(function () use($redirectUrl) {
                 return new RedirectResponse($redirectUrl);
             });
         } else {
             return;
         }
     }
 }

作者:Jrbebe    项目:GestionTitr   
/**
  * @Route("/ajax/tableau",name="ajaxtab")
  * @Template("coffreappBundle:Default:tableau.html.twig")
  */
 public function TableauAction()
 {
     $session = new Session();
     $em = $this->getDoctrine()->getManager();
     $entities = $em->getRepository('coffreappBundle:Ticket')->findBy(array('operateur' => $session->get('Codecaisse'), 'session' => $session->get('Session')), array('id' => "desc"));
     return array('entity' => $entities);
 }

作者:TuxCoffeeCorne    项目:tc   
public function indexAction()
 {
     $login_session = $this->getRequest()->getSession();
     if (!$login_session) {
         $login_session = new Session();
     }
     $this->setConfig();
     // Is the user already logged in? Redirect user to the private page
     if ($login_session->has('username')) {
         // if logged in redirect to users page
         return $this->redirect($this->generateUrl('user_page'));
         //all Symfony versions
         // return $this->redirectToRoute('user_page'); // Symfony 2.6 and above
     }
     if ($this->getRequest()->request->has('submit')) {
         $login_success = $this->doLogin();
         if ($login_success) {
             return $this->redirect($this->generateUrl('user_page'));
             //all Symfony versions
         } else {
             $login_error = "The submitted login info is incorrect or you're not a Tux Coffee Corner user.";
         }
     }
     //render login-form
     return $this->render('TuxCoffeeCornerUserBundle::userLogin.html.php', array('login_error' => $login_error));
 }

作者:alinnflorin    项目:CraueFormFlowBundl   
/**
  * {@inheritDoc}
  */
 protected function setUp()
 {
     $session = new Session(new MockArraySessionStorage());
     $session->setId('12345');
     $this->tokenStorage = new TokenStorage();
     $this->generator = new UserSessionStorageKeyGenerator($this->tokenStorage, $session);
 }

作者:kamalsolime    项目:symfony-blo   
public function createAction($article_id, Request $request)
 {
     $repository = $this->getDoctrine()->getRepository('BlogArticlesBundle:Article');
     $query = $repository->createQueryBuilder('a')->where('a.isActive = 1')->where('a.id = :id')->setParameter('id', $article_id)->setMaxResults(1)->getQuery();
     $article = $query->getOneOrNullResult();
     if (!$article) {
         throw $this->createNotFoundException('The article does not exist');
     }
     $comment = new Comment();
     $form = $this->getForm($article_id, $comment);
     $form->handleRequest($request);
     $session = new Session();
     if ($request->isMethod('POST')) {
         if ($form->isValid()) {
             $em = $this->getDoctrine()->getManager();
             $comment->setArticle($article);
             $comment->setIsActive(1);
             $comment->setCreatedAt(new \DateTime('now'));
             $em->persist($comment);
             $em->flush();
             $session->getFlashBag()->add('sucess', 'Save Done');
         } else {
             //                $errors = array();
             //                foreach ($form->getErrors(true , true) as $key => $error) {
             //                    $errors[] = $error->getMessage();
             //                }
             $session->getFlashBag()->add('error', 'All fileds required');
         }
     }
     return $this->redirect($this->generateUrl('BlogArticles_view', ['slug' => $article->getSlug()]) . '#comments');
 }

作者:kebool    项目:oauth-v2-bundl   
protected function registerBag(SymfonySession $session)
 {
     $bag = new AttributeBag('_' . self::BAG_NAME);
     $bag->setName(self::BAG_NAME);
     $session->registerBag($bag);
     $this->sessionBag = $session->getBag(self::BAG_NAME);
 }

作者:nadundesilv    项目:SpacebitResourceManage   
public function __construct(Session $session, Connection $conn)
 {
     //Fetching equipment requests count
     $stmt = $conn->prepare("SELECT dept_name FROM staff  where user_id =:user_id;");
     $stmt->bindValue(':user_id', $session->get('user_id'));
     $stmt->execute();
     $staff_member = $stmt->fetch()['dept_name'];
     $stmt = $conn->prepare('SELECT COUNT(DISTINCT request_id) AS count FROM resource_request WHERE (resource_request.resource_id is NULL OR resource_request.resource_id IN (SELECT resource_id FROM equipment)) AND resource_request.department_name = :dept_name AND resource_request.status = 2 AND date_from >= CURDATE();');
     $stmt->bindValue(':dept_name', $staff_member);
     $stmt->execute();
     $this->equipment_requests_count = $stmt->fetch()['count'];
     //Fetching venues requests count
     $stmt = $conn->prepare('CREATE OR REPLACE VIEW admin_resource_view  as select venue.resource_id from venue INNER JOIN resource_administration on venue.resource_id = resource_administration.resource_id and resource_administration.user_id = :user_id;');
     $stmt->bindValue(':user_id', $session->get('user_id'));
     $stmt->execute();
     $stmt = $conn->prepare('SELECT COUNT(DISTINCT request_id) AS count FROM resource_request INNER JOIN view1 using(resource_id) WHERE status = 2 AND date_from >= CURDATE();');
     $stmt->execute();
     $this->venue_requests_count = $stmt->fetch()['count'];
     //Fetching vehicle requests count
     $stmt = $conn->prepare('SELECT COUNT(DISTINCT vehicle_request.request_id) AS count FROM (vehicle_request INNER JOIN vehicle ON vehicle.type = vehicle_request.requested_type) INNER JOIN vehicle_administration ON vehicle.plate_no = vehicle_administration.plate_no WHERE vehicle_administration.user_id = :user_id AND vehicle_request.status = 2 AND date >= CURDATE();');
     $stmt->bindValue(':user_id', $session->get('user_id'));
     $stmt->execute();
     $this->vehicle_requests_count = $stmt->fetch()['count'];
     //Fetching access level
     $stmt = $conn->prepare('SELECT access_level FROM login INNER JOIN user USING(user_id) WHERE user_id = :user_id AND active = true;');
     $stmt->bindValue(':user_id', $session->get('user_id'));
     $stmt->execute();
     $this->access_level = $stmt->fetch()['access_level'];
 }

作者:qmig    项目:rentmype   
/**
  * @Route("/login")
  * @Template()
  */
 public function loginAction()
 {
     $error = "";
     //on vérifie que les deux champs sont rempli en post
     if (isset($_POST["_username"]) && isset($_POST["_password"])) {
         $repository = $this->getDoctrine()->getRepository('loginBundle:user');
         $qb = $repository->createQueryBuilder('u');
         $qb->where('u.email = :email')->setParameters(array('email' => $_POST["_username"]));
         $user = null;
         $array = $qb->getQuery()->getResult();
         if (count($array) > 0) {
             $user = $qb->getQuery()->getResult()[0];
         }
         //si $user est null c'est que l'email est inconnu
         if (null == $user) {
             return $this->render("loginBundle:default:login.html.twig", array('error' => "Compte inconnu, veuillez vous enregistrer"));
         } else {
             //si l'email est connu on vérifie que le password en post correspond à celui en base
             if ($user->comparePass($_POST["_password"])) {
                 $session = new Session();
                 $session->set('name', $_POST["_username"]);
                 return $this->render("loginBundle:Secured:index.html.twig", array('user' => $user, 'error' => $error));
             } else {
                 $error = "Le mot de passe est erroné";
             }
         }
     }
     return array('error' => $error);
 }

作者:anonim113    项目:ruszdupe-we   
/**
  * @Route("/checkIn", name="loginCheck")
  * @Template()
  */
 public function checkInAction()
 {
     if (isset($_GET['connectData'])) {
         //Jeżeli są dane, to loguje
         $wykop = $this->get('WykopApi');
         $connect_data = $wykop->handleConnectData();
         $session = new Session();
         $session->set('token', $connect_data['token']);
         $session->set('sign', $connect_data['sign']);
         $profile = $wykop->doRequest('profile/index/' . $connect_data['login']);
         if (!$wykop->isValid()) {
             throw new Exception($this->api->getError());
         } else {
             $answer = $wykop->doRequest('user/login', array('login' => $profile['login'], 'accountkey' => $session->get('token')));
             if (!$wykop->isValid()) {
                 throw new Exception($this->api->getError());
             }
             $roles = ['ROLE_USER_WYKOP'];
             if ($profile['login'] === 'anonim1133') {
                 $roles[] = 'ROLE_ADMIN';
             }
             $token = new UsernamePasswordToken($profile['login'], $answer['userkey'], 'wykop', $roles);
             $token->setAttribute('wykop_login', $profile['login']);
             $token->setAttribute('wykop_sex', $profile['sex']);
             $token->setAttribute('wykop_group', $profile['author_group']);
             $token->setAttribute('wykop_avatar', $profile['avatar_med']);
             $token->setAttribute('wykop_login_date', new \DateTime('now'));
             $this->get('security.token_storage')->setToken($token);
             $session->set('_security_main', serialize($token));
         }
     }
     return $this->redirect('/');
 }

作者:ls    项目:OneupUploaderBundl   
public function setUp()
 {
     $this->numberOfPayloads = 5;
     $this->tempDirectory = sys_get_temp_dir() . '/orphanage';
     $this->realDirectory = sys_get_temp_dir() . '/storage';
     $this->payloads = array();
     $filesystem = new Filesystem();
     $filesystem->mkdir($this->tempDirectory);
     $filesystem->mkdir($this->realDirectory);
     for ($i = 0; $i < $this->numberOfPayloads; $i++) {
         // create temporary file
         $file = tempnam(sys_get_temp_dir(), 'uploader');
         $pointer = fopen($file, 'w+');
         fwrite($pointer, str_repeat('A', 1024), 1024);
         fclose($pointer);
         $this->payloads[] = new FilesystemFile(new UploadedFile($file, $i . 'grumpycat.jpeg', null, null, null, true));
     }
     // create underlying storage
     $this->storage = new FilesystemStorage($this->realDirectory);
     // is ignored anyways
     $chunkStorage = new FilesystemChunkStorage('/tmp/');
     // create orphanage
     $session = new Session(new MockArraySessionStorage());
     $session->start();
     $config = array('directory' => $this->tempDirectory);
     $this->orphanage = new FilesystemOrphanageStorage($this->storage, $session, $chunkStorage, $config, 'cat');
 }

作者:AscensoDigita    项目:ADPerfilBundl   
public function __construct(Session $session, EntityManager $em, $sessionName, PerfilManager $perfilManager, TokenStorageInterface $tokenStorage)
 {
     $this->em = $em;
     $this->perfil_id = $session->get($sessionName, null);
     $this->perfilManager = $perfilManager;
     $this->tokenStorage = $tokenStorage;
 }


问题


面经


文章

微信
公众号

扫码关注公众号