Create a handler by config

@return \SessionHandlerInterface
@throws \InvalidArgumentException
346881
public function createHandlerByConfig(): \SessionHandlerInterface
    {
        if (!isset($this->getConfig()['driver'])) {
            throw new \InvalidArgumentException('Session driver required');
        }
        $handler = $this->getHandler($this->getConfig()['driver']);
        $handler instanceof LifetimeInterface && $handler->setLifetime($this->getConfig()['lifetime']);
        return $handler;
    }
272071
private function getHandler($handler): FormHandlerInterface
    {
        if (is_string($handler)) {
            if (!isset($this->handlers[$handler])) {
                $handler = new $handler();
            } else {
                $handler = $this->handlers[$handler];
            }
        }

        if (!$handler instanceof FormHandlerInterface) {
            throw new InvalidHandlerException(FormHandlerInterface::class, $handler);
        }

        return $handler;
    }
95062
public function setConfig()
    {
        // error
        if (func_num_args() < 2 || func_num_args() > 3) {
            throw new InvalidArgumentException('Invalid Call of method "config"');
        }

        // default main config
        if (func_num_args() == 2) {
            return $this->setConfig('main', func_get_arg(0), func_get_arg(1));
        }

        // default global config
        return $this->configObject(func_get_arg(0))->setConfig(func_get_arg(1), func_get_arg(2));
    }
1194083
public static function create()
    {
        return parent::create()
            ->setSerializationContextFactory(array(self::class, 'createDefaultSerializationContext'))
            ->addDefaultHandlers()
            ->configureListeners(function (EventDispatcher $dispatcher) {
                $proxySubscriber = new DoctrineProxySubscriber(false);
                $dispatcher->addSubscriber($proxySubscriber);
            })
            ->configureHandlers(function (HandlerRegistryInterface $handlerRegistry) {
                $proxyHandler = new DoctrineProxyHandler();
                $handlerRegistry->registerSubscribingHandler($proxyHandler);
            })
        ;
    }
321776
public static function init()
    {
        $c = new Configuration();
        $cc = $c->from('app')->get('session');

        if (strtolower($cc) == 'session') {
            return new Session();
        } elseif (strtolower($cc) == 'file') {
            return new File();
        } elseif (strtolower($cc) == 'cookie') {
            return new Cookie();
        } else {
            throw new \Exception($cc.' is not a supported session type!');
        }
    }
1164351
public static function isSessionHandler($handler)
    {
        $config = Config::getInstance();
        return !isset($config->General['session_save_handler'])
        || $config->General['session_save_handler'] === $handler;
    }
213348
public function registerHandlersFromConfig()
    {
        $config = $this->container->getConfigInstance();
        foreach ($config->getAJAXTypeHandlers() as $handlerArray) {

            if (isset($handlerArray['path'])) {
                $path = $handlerArray['path'];
                if (!file_exists($path)) {
                    throw new FileNotFoundException($path, "AJAXTypeHandler class file");
                }
                /** @noinspection PhpIncludeInspection */
                require_once $path;
            }

            $className = $handlerArray['class_name'];

            if (!class_exists($className)) {
                throw new ClassNotDefinedException($className);
            }

            $handler = new $className($this->container);

            if($handler instanceof TypeHandlerGenerator){
                $handler = $handler->generateTypeHandler();
            }

            if (!($handler instanceof TypeHandler)) {
                throw new ClassNotInstanceOfException($handler == null ? 'null' : get_class($handler), 'AJAXTypeHandler');
            }

            $this->registerHandler($handler);
        }
    }
622745
public function init() {
        if (!extension_loaded('redis')) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension is not loaded');
        }

        if (empty($this->host)) {
            throw new exception('sessionhandlerproblem', 'error', '', null,
                    '$CFG->session_redis_host must be specified in config.php');
        }

        // The session handler requires a version of Redis with the SETEX command (at least 2.0).
        $version = phpversion('Redis');
        if (!$version or version_compare($version, '2.0') <= 0) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension version must be at least 2.0');
        }

        $this->connection = new \Redis();

        $result = session_set_save_handler(array($this, 'handler_open'),
            array($this, 'handler_close'),
            array($this, 'handler_read'),
            array($this, 'handler_write'),
            array($this, 'handler_destroy'),
            array($this, 'handler_gc'));
        if (!$result) {
            throw new exception('redissessionhandlerproblem', 'error');
        }

        // MDL-59866: Add retries for connections (up to 5 times) to make sure it goes through.
        $counter = 1;
        $maxnumberofretries = 5;

        while ($counter <= $maxnumberofretries) {

            try {

                $delay = rand(100000, 500000);

                // One second timeout was chosen as it is long for connection, but short enough for a user to be patient.
                if (!$this->connection->connect($this->host, $this->port, 1, null, $delay)) {
                    throw new RedisException('Unable to connect to host.');
                }

                if ($this->auth !== '') {
                    if (!$this->connection->auth($this->auth)) {
                        throw new RedisException('Unable to authenticate.');
                    }
                }

                if (!$this->connection->setOption(\Redis::OPT_SERIALIZER, $this->serializer)) {
                    throw new RedisException('Unable to set Redis PHP Serializer option.');
                }

                if ($this->prefix !== '') {
                    // Use custom prefix on sessions.
                    if (!$this->connection->setOption(\Redis::OPT_PREFIX, $this->prefix)) {
                        throw new RedisException('Unable to set Redis Prefix option.');
                    }
                }
                if ($this->database !== 0) {
                    if (!$this->connection->select($this->database)) {
                        throw new RedisException('Unable to select Redis database '.$this->database.'.');
                    }
                }
                $this->connection->ping();
                return true;
            } catch (RedisException $e) {
                $logstring = "Failed to connect (try {$counter} out of {$maxnumberofretries}) to redis ";
                $logstring .= "at {$this->host}:{$this->port}, error returned was: {$e->getMessage()}";

                // @codingStandardsIgnoreStart
                error_log($logstring);
                // @codingStandardsIgnoreEnd
            }

            $counter++;

            // Introduce a random sleep between 100ms and 500ms.
            usleep(rand(100000, 500000));
        }

        // We have exhausted our retries, time to give up.
        return false;
    }
1173645
private function getSessionHandler(array $config)
    {
        $handler = array_get($config, 'handler', 'default');

        // Build handler using a matching method "get{Type}Handler"
        $method = Str::camel("get_{$handler}_handler");
        if (method_exists($this, $method)) {
            return $this->{$method}($config);
        }

        /*
         * @todo Change this to return an exception if an unsupported handler is configured. This makes it easier to get
         * configuration dialed in properly
         */
        //throw new \RuntimeException(t('Unsupported session handler "%s"', $handler));

        // Return the default session handler by default
        return $this->getSessionHandler(['handler' => 'default'] + $config);
    }
647870
protected function determineHandler()
    {
        $handler = collect($this->config->get('handlers'))
            ->map(function (string $handlerClassName) {
                if (! class_exists($handlerClassName)) {
                    throw InvalidHandler::handlerDoesNotExist($handlerClassName);
                }

                return new $handlerClassName($this->request);
            })
            ->filter(function (HandlesSlashCommand $handler) {
                return $handler->canHandle($this->request);
            })
            ->first();

        if (! $handler) {
            throw RequestCouldNotBeHandled::noHandlerFound($this->request);
        }

        return $handler;
    }
1365678
private function initializeLogger()
    {
        if (Log::hasLogger()) {
            return;
        }

        $logger = new Logger($this->getConfig()['log']['name'] ?? 'foundation');

        if (!$this->getConfig()['debug'] ?? false || defined('PHPUNIT_RUNNING')) {
            $logger->pushHandler(new NullHandler());
        } elseif (($this->getConfig()['log']['handler'] ?? null) instanceof HandlerInterface) {
            $logger->pushHandler($this->getConfig()['log']['handler']);
        } elseif ($logFile = $this->getConfig()['log']['file'] ?? null) {
            $logger->pushHandler(new StreamHandler(
                    $logFile,
                    $this->getConfig()['log']['level'] ?? Logger::WARNING,
                    true,
                    $this->getConfig()['log']['permission'] ?? null
            ));
        }

        Log::setLogger($logger);
    }
1133992
public static function initialize()
    {
        if (static::$isConfigurationLoaded === true) {
            return;
        }
        
        foreach (static::$handlers as $handler) {
            EventManager::getInstance()->addEventHandler($handler[0], $handler[1], $handler[2], $handler[3]);
        }

        static::$isConfigurationLoaded = true;
    }
371371
protected function createHandlerInstance($className, $handlerArgs)
    {
        if (method_exists($this, 'init' . $className)) {
            return call_user_func(array($this, 'init' . $className), explode(',', $handlerArgs));
        } else {
            return null;
        }
    }
287763
public function getRegisteredHandler($byClassName)
    {
        foreach ($this->handlers as $handler)
        {
            if (is_a($handler, $byClassName))
            {
                return $handler;
            }
        }

        throw new \InvalidArgumentException('There is no handler named "' . $byClassName . '" registered.');
    }
500616
public function create(): ConfigurationInterface
    {
        $config = $this->detectConfig();
        $config->set('env', $this->environment);

        return $config;
    }
414420
public static function getSessionHandler() {
        $sessionDriver = get_config('session_driver');
        
        self::$sessionDriver = $sessionDriver ? $sessionDriver : 'native';

        if (self::$sessionDriver) {
            switch (self::$sessionDriver) {
                case 'native':
                    self::$sessionHandler = new Session(get_config('session_timeout'));
                    break;
                case 'database':
                    self::$sessionHandler = new DbSession(get_config('session_timeout'));
                    break;
            }
        }

        if (self::$sessionHandler) {
            return self::$sessionHandler;
        } else {
            throw new \Exception(ExceptionMessages::MISCONFIGURED_SESSION_HANDLER);
        }
    }
1099442
public function getHandler()
    {
        if(!$this->_handler instanceof UserSessionHandlerInterface)
        {
            $this->_handler = $this->getObject($this->_handler);

            if(!$this->_handler instanceof UserSessionHandlerInterface)
            {
                throw new \UnexpectedValueException(
                    'Handler: '.get_class($this->_handler).' does not implement UserSessionHandlerInterface'
                );
            }
        }

        return $this->_handler;
    }