Acquire a session from the pool.

@param string $context The type of session to fetch. May be either `r`
(READ) or `rw` (READ/WRITE). **Defaults to** `r`.
@return Session
@throws \RuntimeException
517276
public function acquire($context = SessionPoolInterface::CONTEXT_READ)
    {
        // Try to get a session, run maintenance on the pool, and calculate if
        // we need to create any new sessions.
        list($session, $toCreate) = $this->config['lock']->synchronize(function () {
            $toCreate = [];
            $session = null;
            $shouldSave = false;
            $item = $this->cacheItemPool->getItem($this->cacheKey);
            $data = (array) $item->get() ?: $this->initialize();

            // If the queue has items in it, let's shift one off, however if the
            // queue is empty and we have maxed out the number of sessions let's
            // attempt to purge any orphaned items from the pool to make room
            // for more.
            if ($data['queue']) {
                $session = $this->getSession($data);
                $shouldSave = true;
            } elseif ($this->config['maxSessions'] <= $this->getSessionCount($data)) {
                $this->purgeOrphanedInUseSessions($data);
                $this->purgeOrphanedToCreateItems($data);
                $session = $this->getSession($data);
                $shouldSave = true;
            }

            if (!$session) {
                $count = $this->getSessionCount($data);

                if ($count < $this->config['maxSessions']) {
                    $toCreate = $this->buildToCreateList(1);
                    $data['toCreate'] += $toCreate;
                    $shouldSave = true;
                }
            }

            if ($shouldSave) {
                $this->cacheItemPool->save($item->set($data));
            }

            return [$session, $toCreate];
        });

        // Create a session if needed.
        if ($toCreate) {
            $createdSessions = $this->createSessions(count($toCreate));
            $hasCreatedSessions = count($createdSessions) > 0;

            $session = $this->config['lock']->synchronize(function () use (
                $toCreate,
                $createdSessions,
                $hasCreatedSessions
            ) {
                $session = null;
                $item = $this->cacheItemPool->getItem($this->cacheKey);
                $data = $item->get();
                $data['queue'] = array_merge($data['queue'], $createdSessions);

                // Now that we've created the session, we can remove it from
                // the list of intent.
                foreach ($toCreate as $id => $time) {
                    unset($data['toCreate'][$id]);
                }

                if ($hasCreatedSessions) {
                    $session = array_shift($data['queue']);
                    $data['inUse'][$session['name']] = $session + [
                        'lastActive' => $this->time()
                    ];

                    if ($this->config['shouldAutoDownsize']) {
                        $this->manageSessionsToDelete($data);
                    }
                }

                $this->cacheItemPool->save($item->set($data));

                return $session;
            });
        }

        if ($session) {
            $session = $this->handleSession($session);
        }

        // If we don't have a session, let's wait for one or throw an exception.
        if (!$session) {
            if (!$this->config['shouldWaitForSession']) {
                throw new \RuntimeException('No sessions available.');
            }

            $session = $this->waitForNextAvailableSession();
        }

        if ($this->deleteQueue) {
            $this->deleteSessions($this->deleteQueue);
            $this->deleteQueue = [];
        }

        return $this->database->session($session['name']);
    }
128388
public function getProxy( string $context ): ThenProxy
	{
		if( isset($this->proxy[$context]) )
		{
			return $this->proxy[$context];
		}

		if( !$this->lang->load($context) )
		{
			throw new \InvalidArgumentException("Cannot load the '{$context}' language package");
		}

		$this->proxy[$context] = new ThenProxy($this, $context);
		return $this->proxy[$context];
	}
228891
public static function retrieve($context)
    {
        if ($context instanceof sfContext || $context instanceof sfProjectConfiguration) {
            return $context->getEventDispatcher();
        } elseif (isset($GLOBALS['dispatcher'])) {
            return $GLOBALS['dispatcher'];
        }

        $refClass = new ReflectionClass(get_class($context));

        if ($refClass->hasProperty('dispatcher')) {
            return self::retrieveByDispatcherProperty($refClass, $context);
        } elseif ($refClass->hasProperty('configuration')) {
            return self::retrieveByConfigurationProperty($refClass, $context);
        }
    }
972201
public function getClone($context = null, $original = null)
    {
        $new = clone $this;

        if ($context !== null) {
            $new->context = (string) $context;
        }

        if ($original !== null) {
            $new->original = (string) $original;
        }

        return $new;
    }
1188023
public function setContext($context)
    {
        if (!is_array($context) && !$context instanceof \ArrayObject && !$context instanceof \Iterator) {
            throw new EventException('Unexpected value type for context', EventException::INVALID_CONTEXT);
        }

        $context = Collection::cast($context);

        $this->context = $context;

        return $this;
    }
871537
public function read($length = null)
    {
        $this->assertReadable();
        if (null == $length) {
            $length = $this->bufferSize;
        }
        $ret = fread($this->stream, $length);
        if (false === $ret) {
            throw new RuntimeException('Cannot read stream');
        }
        
        return $ret;
    }
747451
public static function GetCurrentDate( $context )
	{
		$res = DateValue::fromDate( false, new \DateTime( "@" . $context->RunningContext->now ) );
		$res->IsLocal = false;
		$res->Value->microseconds = 0;
		return $res;
	}
1133109
public function fetchEntity(AnCommandContext $context)
    {
        if (!$this->_entity) {
            $this->_entity = $this->getService('com:settings.domain.entity.setting')->load();
        }

        return $this->_entity;
    }
178887
public function createQuery($context = 'list')
    {
        $query = $this->getModelManager()->createQuery($this->getClass());
        $query->setRootPath($this->getRootPath());

        foreach ($this->extensions as $extension) {
            $extension->configureQuery($this, $query, $context);
        }

        return $query;
    }
1282656
public static function getInstance(ContextInterface $context)
    {
        $fileManager     = new FileManager();
        $historyHydrator = HistoryHydratorFactory::getInstance($context);

        return new HistoryManager($fileManager, $historyHydrator);
    }
190711
private function getScenario( $context )
	{
		if ( is_string( $context ) )
		{
			if ( ! isset( $this->contexts[ $context ] ) ) return null;
			$context = $this->contexts[ $context ];
		}

		if ( isset( $context['scenario'] ) ) return $context['scenario'];
		if ( isset( $context['entity']['scenario'] ) ) return $context['entity']['scenario'];

		return null;
	}
660136
public function getRequest()
    {
        if ($this->hasRequest() === false) {
            // Try to get request from container.
            $this->setRequest($this->getContainer()->get('request_stack')->getCurrentRequest());
        }

        if ($this->hasRequest() === false) {
            throw new \RuntimeException("Sorry, the request is not available in this context");
        }

        return $this->request;
    }
293197
protected function ensureContext(OperationContextInterface $context = null)
    {
        if ($context === null) {
            $context = $this->getSession()->getDefaultContext();
        }

        return $context;
    }
427617
public function createQuery($context = 'list')
    {
        if ($context === 'list') {
            /** @var $em \Doctrine\ORM\EntityManager */
            $em = $this->getModelManager()->getEntityManager($this->getClass());

            /** @var $cmd \Doctrine\Common\Persistence\Mapping\ClassMetadata */
            $cmd = $em->getMetadataFactory()->getMetadataFor($this->getClass());

            $queryBuilder = $em->createQueryBuilder();
            $queryBuilder
                ->select('n')
                ->from($this->getClass(), 'n');

            if ($cmd->hasField('root')) {
                $queryBuilder->orderBy('n.root, n.lft');
            } else {
                $queryBuilder->orderBy('n.lft');
            }

            return new ProxyQuery($queryBuilder);
        }
        return parent::createQuery($context);
    }
777446
public function fetchEntity(AnCommandContext $context)
    {
        if (!$this->_entity) {
            if ($entity = $this->getService('com:settings.domain.entity.template')->load($this->alias)) {
                $this->_entity = $entity;
            }
        }

        return $this->_entity;
    }
840495
public function fetchEntity(AnCommandContext $context)
    {
        if ($this->isDispatched() && $this->getRequest()->alias) {
            $this->setIdentifiableKey('alias');
        }

        return parent::fetchEntity($context);
    }
499469
public function startSession($context=null, $useExisting=false)
    {
        $logger = $GLOBALS['logger'];
        $app = $GLOBALS['app'];

        // Strip '.'
        $appContext = rtrim($app->getConfiguration()->getApplicationContext(), '.');
        if (empty($appContext)) {
            $appContext = "/";
        } else {
            $appContext = "/".$appContext."/";
        }

        if ($useExisting === true) {
            $sessionCookieName = $app->getConfiguration()->getApplicationContext()."-"."_n5_session";
            $sessionCookieName = preg_replace("/\./", "_",$sessionCookieName); 
            session_set_cookie_params(0, $appContext, null, false, true);
            session_name($sessionCookieName);
            session_start();
        if (!$this->isActiveSession()) {
            self::resetActiveSession();
        }

            $this->_session = new Session($_SESSION);
            if ($this->_session->getAttribute('category') !== null) {
                return;
            }
        }

        if (!isset($_SESSION[self::GLOBAL_PREFIX.'category'])) {
            // No session exists yet.
            if ($context === null) {
                $context = new WebContext($_REQUEST);
            }

            session_unset();
            session_destroy();
            $sessionCookieName = $app->getConfiguration()->getApplicationContext()."-"."_n5_session"; 
            $sessionCookieName = preg_replace("/\./", "_",$sessionCookieName); 
            session_set_cookie_params(0, $appContext, null, false, true);
            session_name($sessionCookieName);
            session_start();
            session_regenerate_id();
            $_SESSION = array();

            $app = $GLOBALS['app'];
            if (!$app->getConfiguration()->isLocal()) {
                //$handler = new CachedSessionHandler();
                //session_set_save_handler(
                    //array($handler, 'open'),
                    //array($handler, 'close'),
                    //array($handler, 'read'),
                    //array($handler, 'write'),
                    //array($handler, 'destroy'),
                    //array($handler, 'gc')
                //);
            }

            $_SESSION[self::GLOBAL_PREFIX.'category']      = $context->get('device');
            $_SESSION[self::GLOBAL_PREFIX.'location']      = $context->get('location');
            $_SESSION[self::GLOBAL_PREFIX.'last_accessed'] = time();
        }//end if

        $this->_session = new Session($_SESSION);

    }