From 6d0b22e49fa0823ac68e02b695d10607a61f3ff6 Mon Sep 17 00:00:00 2001 From: Tim van Dijen <tvdijen@gmail.com> Date: Sun, 11 Aug 2019 19:43:47 +0200 Subject: [PATCH] Fully typehint lib/*.php --- lib/SimpleSAML/Configuration.php | 146 +++++++++--------------- lib/SimpleSAML/Database.php | 10 +- lib/SimpleSAML/IdP.php | 67 +++++------ lib/SimpleSAML/Logger.php | 65 ++++++----- lib/SimpleSAML/Memcache.php | 13 +-- lib/SimpleSAML/Module.php | 28 ++--- lib/SimpleSAML/Session.php | 143 +++++++++++------------ lib/SimpleSAML/SessionHandler.php | 22 ++-- lib/SimpleSAML/SessionHandlerCookie.php | 14 +-- lib/SimpleSAML/SessionHandlerPHP.php | 20 ++-- lib/SimpleSAML/SessionHandlerStore.php | 6 +- lib/SimpleSAML/Stats.php | 5 +- lib/SimpleSAML/Store.php | 10 +- lib/_autoload_modules.php | 2 +- 14 files changed, 248 insertions(+), 303 deletions(-) diff --git a/lib/SimpleSAML/Configuration.php b/lib/SimpleSAML/Configuration.php index c9c9f9082..e2ce8c5e4 100644 --- a/lib/SimpleSAML/Configuration.php +++ b/lib/SimpleSAML/Configuration.php @@ -92,15 +92,13 @@ class Configuration implements Utils\ClearableState * @param array $config The configuration array. * @param string $location The location which will be given when an error occurs. */ - public function __construct($config, $location) + public function __construct(array $config, string $location) { - Assert::isArray($config); - Assert::string($location); - $this->configuration = $config; $this->location = $location; } + /** * Load the given configuration file. * @@ -192,14 +190,12 @@ class Configuration implements Utils\ClearableState * @param string $configSet The configuration set. Defaults to 'simplesaml'. * @return void */ - public static function setConfigDir($path, $configSet = 'simplesaml') + public static function setConfigDir(string $path, string $configSet = 'simplesaml') : void { - Assert::string($path); - Assert::string($configSet); - self::$configDirs[$configSet] = $path; } + /** * Store a pre-initialized configuration. * @@ -214,12 +210,9 @@ class Configuration implements Utils\ClearableState */ public static function setPreLoadedConfig( Configuration $config, - $filename = 'config.php', - $configSet = 'simplesaml' - ) { - Assert::string($filename); - Assert::string($configSet); - + string $filename = 'config.php', + string $configSet = 'simplesaml' + ): void { if (!array_key_exists($configSet, self::$configDirs)) { if ($configSet !== 'simplesaml') { throw new \Exception('Configuration set \'' . $configSet . '\' not initialized.'); @@ -244,11 +237,10 @@ class Configuration implements Utils\ClearableState * @return \SimpleSAML\Configuration The Configuration object. * @throws \Exception If the configuration set is not initialized. */ - public static function getConfig($filename = 'config.php', $configSet = 'simplesaml') - { - Assert::string($filename); - Assert::string($configSet); - + public static function getConfig( + string $filename = 'config.php', + string $configSet = 'simplesaml' + ): Configuration { if (!array_key_exists($configSet, self::$configDirs)) { if ($configSet !== 'simplesaml') { throw new \Exception('Configuration set \'' . $configSet . '\' not initialized.'); @@ -274,11 +266,10 @@ class Configuration implements Utils\ClearableState * @return \SimpleSAML\Configuration A configuration object. * @throws \Exception If the configuration set is not initialized. */ - public static function getOptionalConfig($filename = 'config.php', $configSet = 'simplesaml') - { - Assert::string($filename); - Assert::string($configSet); - + public static function getOptionalConfig( + string $filename = 'config.php', + string $configSet = 'simplesaml' + ): Configuration { if (!array_key_exists($configSet, self::$configDirs)) { if ($configSet !== 'simplesaml') { throw new \Exception('Configuration set \'' . $configSet . '\' not initialized.'); @@ -304,11 +295,11 @@ class Configuration implements Utils\ClearableState * * @return \SimpleSAML\Configuration The configuration object. */ - public static function loadFromArray($config, $location = '[ARRAY]', $instance = null) - { - Assert::isArray($config); - Assert::string($location); - + public static function loadFromArray( + array $config, + string $location = '[ARRAY]', + ?string $instance = null + ): Configuration { $c = new Configuration($config, $location); if ($instance !== null) { self::$instance[$instance] = $c; @@ -332,10 +323,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the configuration with $instancename name is not initialized. */ - public static function getInstance($instancename = 'simplesaml') + public static function getInstance(string $instancename = 'simplesaml') : Configuration { - Assert::string($instancename); - // check if the instance exists already if (array_key_exists($instancename, self::$instance)) { return self::$instance[$instancename]; @@ -360,7 +349,7 @@ class Configuration implements Utils\ClearableState * * @return string */ - public function getVersion() + public function getVersion(): string { return 'master'; } @@ -378,7 +367,7 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the required option cannot be retrieved. */ - public function getValue($name, $default = null) + public function getValue(string $name, $default = null) { // return the default value if the option is unset if (!array_key_exists($name, $this->configuration)) { @@ -402,7 +391,7 @@ class Configuration implements Utils\ClearableState * * @return boolean If the value is set in this configuration. */ - public function hasValue($name) + public function hasValue(string $name): bool { return array_key_exists($name, $this->configuration); } @@ -415,7 +404,7 @@ class Configuration implements Utils\ClearableState * * @return boolean If any of the keys in $names exist in the configuration */ - public function hasValueOneOf($names) + public function hasValueOneOf(array $names): bool { foreach ($names as $name) { if ($this->hasValue($name)) { @@ -435,7 +424,7 @@ class Configuration implements Utils\ClearableState * * @throws \SimpleSAML\Error\CriticalConfigurationError If the format of 'baseurlpath' is incorrect. */ - public function getBasePath() + public function getBasePath(): string { $baseURL = $this->getString('baseurlpath', 'simplesaml/'); @@ -480,7 +469,7 @@ class Configuration implements Utils\ClearableState * @return string|null $path if $path is an absolute path, or $path prepended with the base directory of this * SimpleSAMLphp installation. We will return NULL if $path is null. */ - public function resolvePath($path) + public function resolvePath(?string $path): ?string { if ($path === null) { return null; @@ -506,7 +495,7 @@ class Configuration implements Utils\ClearableState * * @return string|null The path configuration option with name $name, or $default if the option was not found. */ - public function getPathValue($name, $default = null) + public function getPathValue(string $name, ?string $default = null): ?string { // return the default value if the option is unset if (!array_key_exists($name, $this->configuration)) { @@ -533,7 +522,7 @@ class Configuration implements Utils\ClearableState * @return string The absolute path to the base directory for this SimpleSAMLphp installation. This path will * always end with a slash. */ - public function getBaseDir() + public function getBaseDir(): string { // check if a directory is configured in the configuration file $dir = $this->getString('basedir', null); @@ -581,10 +570,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the option is not boolean. */ - public function getBoolean($name, $default = self::REQUIRED_OPTION) + public function getBoolean(string $name, $default = self::REQUIRED_OPTION) { - Assert::string($name); - $ret = $this->getValue($name, $default); if ($ret === $default) { @@ -619,10 +606,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the option is not a string. */ - public function getString($name, $default = self::REQUIRED_OPTION) + public function getString(string $name, $default = self::REQUIRED_OPTION) { - Assert::string($name); - $ret = $this->getValue($name, $default); if ($ret === $default) { @@ -657,10 +642,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the option is not an integer. */ - public function getInteger($name, $default = self::REQUIRED_OPTION) + public function getInteger(string $name, $default = self::REQUIRED_OPTION) { - Assert::string($name); - $ret = $this->getValue($name, $default); if ($ret === $default) { @@ -699,12 +682,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the option is not in the range specified. */ - public function getIntegerRange($name, $minimum, $maximum, $default = self::REQUIRED_OPTION) + public function getIntegerRange(string $name, int $minimum, int $maximum, $default = self::REQUIRED_OPTION) { - Assert::string($name); - Assert::integer($minimum); - Assert::integer($maximum); - $ret = $this->getInteger($name, $default); if ($ret === $default) { @@ -745,11 +724,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the option does not have any of the allowed values. */ - public function getValueValidate($name, $allowedValues, $default = self::REQUIRED_OPTION) + public function getValueValidate(string $name, array $allowedValues, $default = self::REQUIRED_OPTION) { - Assert::string($name); - Assert::isArray($allowedValues); - $ret = $this->getValue($name, $default); if ($ret === $default) { // the option wasn't found, or it matches the default value. In any case, return this value @@ -790,10 +766,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the option is not an array. */ - public function getArray($name, $default = self::REQUIRED_OPTION) + public function getArray(string $name, $default = self::REQUIRED_OPTION) { - Assert::string($name); - $ret = $this->getValue($name, $default); if ($ret === $default) { @@ -819,10 +793,9 @@ class Configuration implements Utils\ClearableState * required if this parameter isn't given. The default value can be any value, including * null. * - * @return array|mixed The option with the given name, or $default - * if the option isn't found and $default is specified. + * @return mixed The option with the given name, or $default if the option isn't found and $default is specified. */ - public function getArrayize($name, $default = self::REQUIRED_OPTION) + public function getArrayize(string $name, $default = self::REQUIRED_OPTION) { Assert::string($name); @@ -855,10 +828,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the option is not a string or an array of strings. */ - public function getArrayizeString($name, $default = self::REQUIRED_OPTION) + public function getArrayizeString(string $name, $default = self::REQUIRED_OPTION) { - Assert::string($name); - $ret = $this->getArrayize($name, $default); if ($ret === $default) { @@ -898,10 +869,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the option is not an array. */ - public function getConfigItem($name, $default = []) + public function getConfigItem(string $name, $default = []) { - Assert::string($name); - $ret = $this->getValue($name, $default); if ($ret === null) { @@ -929,7 +898,7 @@ class Configuration implements Utils\ClearableState * * @return array Name of all options defined in this configuration file. */ - public function getOptions() + public function getOptions(): array { return array_keys($this->configuration); } @@ -940,7 +909,7 @@ class Configuration implements Utils\ClearableState * * @return array An associative array with all configuration options and values. */ - public function toArray() + public function toArray(): array { return $this->configuration; } @@ -958,10 +927,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the default binding is missing for this endpoint type. */ - private function getDefaultBinding($endpointType) + private function getDefaultBinding(string $endpointType): string { - Assert::string($endpointType); - $set = $this->getString('metadata-set'); switch ($set . ':' . $endpointType) { case 'saml20-idp-remote:SingleSignOnService': @@ -987,10 +954,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If any element of the configuration options for this endpoint type is incorrect. */ - public function getEndpoints($endpointType) + public function getEndpoints(string $endpointType): array { - Assert::string($endpointType); - $loc = $this->location . '[' . var_export($endpointType, true) . ']:'; if (!array_key_exists($endpointType, $this->configuration)) { @@ -1068,10 +1033,11 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If no supported endpoint is found. */ - public function getEndpointPrioritizedByBinding($endpointType, array $bindings, $default = self::REQUIRED_OPTION) - { - Assert::string($endpointType); - + public function getEndpointPrioritizedByBinding( + string $endpointType, + array $bindings, + $default = self::REQUIRED_OPTION + ): ?array { $endpoints = $this->getEndpoints($endpointType); foreach ($bindings as $binding) { @@ -1103,10 +1069,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If no supported endpoint is found and no $default parameter is specified. */ - public function getDefaultEndpoint($endpointType, array $bindings = null, $default = self::REQUIRED_OPTION) + public function getDefaultEndpoint(string $endpointType, array $bindings = null, $default = self::REQUIRED_OPTION) { - Assert::string($endpointType); - $endpoints = $this->getEndpoints($endpointType); $defaultEndpoint = Utils\Config\Metadata::getDefaultEndpoint($endpoints, $bindings); @@ -1136,10 +1100,8 @@ class Configuration implements Utils\ClearableState * * @throws \Exception If the translation is not an array or a string, or its index or value are not strings. */ - public function getLocalizedString($name, $default = self::REQUIRED_OPTION) + public function getLocalizedString(string $name, $default = self::REQUIRED_OPTION) { - Assert::string($name); - $ret = $this->getValue($name, $default); if ($ret === $default) { // the option wasn't found, or it matches the default value. In any case, return this value @@ -1184,11 +1146,8 @@ class Configuration implements Utils\ClearableState * @throws \SimpleSAML\Error\Exception If the file does not contain a valid PEM-encoded certificate, or there is no * certificate in the metadata. */ - public function getPublicKeys($use = null, $required = false, $prefix = '') + public function getPublicKeys(?string $use = null, bool $required = false, string $prefix = ''): array { - Assert::boolean($required); - Assert::string($prefix); - if ($this->hasValue($prefix . 'keys')) { $ret = []; foreach ($this->getArray($prefix . 'keys') as $key) { @@ -1248,6 +1207,7 @@ class Configuration implements Utils\ClearableState } } + /** * Clear any configuration information cached. * Allows for configuration files to be changed and reloaded during a given request. Most useful @@ -1255,7 +1215,7 @@ class Configuration implements Utils\ClearableState * * @return void */ - public static function clearInternalState() + public static function clearInternalState(): void { self::$configDirs = []; self::$instance = []; diff --git a/lib/SimpleSAML/Database.php b/lib/SimpleSAML/Database.php index 4c815a024..cfa21d955 100644 --- a/lib/SimpleSAML/Database.php +++ b/lib/SimpleSAML/Database.php @@ -58,7 +58,7 @@ class Database * * @return \SimpleSAML\Database The shared database connection. */ - public static function getInstance($altConfig = null) + public static function getInstance(Configuration $altConfig = null) : Database { $config = ($altConfig) ? $altConfig : Configuration::getInstance(); $instanceId = self::generateInstanceId($config); @@ -184,7 +184,7 @@ class Database * * @return string Table with configured prefix */ - public function applyPrefix($table) + public function applyPrefix(string $table) : string { return $this->tablePrefix . $table; } @@ -251,7 +251,7 @@ class Database * * @return int|false The number of rows affected by the query or false on error. */ - public function write($stmt, $params = []) + public function write(string $stmt, array $params = []) { $db = $this->dbMaster; @@ -271,7 +271,7 @@ class Database * * @return \PDOStatement object */ - public function read($stmt, $params = []) + public function read(string $stmt, array $params = []) { $db = $this->getSlave(); @@ -284,7 +284,7 @@ class Database * * @return array The array with error information. */ - public function getLastError() + public function getLastError() : array { return $this->lastError; } diff --git a/lib/SimpleSAML/IdP.php b/lib/SimpleSAML/IdP.php index d91231183..f509bbf8e 100644 --- a/lib/SimpleSAML/IdP.php +++ b/lib/SimpleSAML/IdP.php @@ -6,6 +6,9 @@ namespace SimpleSAML; use SAML2\Constants; use SimpleSAML\Auth; +use SimpleSAML\IdP\IFrameLogoutHandler; +use SimpleSAML\IdP\LogoutHandlerInterface; +use SimpleSAML\IdP\TraditionalLogoutHandler; use SimpleSAML\Error; use SimpleSAML\Metadata\MetaDataStorageHandler; use SimpleSAML\Module\saml\Error\NoPassive; @@ -111,7 +114,7 @@ class IdP * * @return string The ID of this IdP. */ - public function getId() + public function getId() : string { return $this->id; } @@ -122,12 +125,10 @@ class IdP * * @param string $id The identifier of the IdP. * - * @return IdP The IdP. + * @return \SimpleSAML\IdP The IdP. */ - public static function getById($id) + public static function getById(string $id) : IdP { - Assert::string($id); - if (isset(self::$idpCache[$id])) { return self::$idpCache[$id]; } @@ -143,9 +144,9 @@ class IdP * * @param array &$state The state array. * - * @return IdP The IdP. + * @return \SimpleSAML\IdP The IdP. */ - public static function getByState(array &$state) + public static function getByState(array &$state) : IdP { Assert::notNull($state['core:IdP']); @@ -158,7 +159,7 @@ class IdP * * @return Configuration The configuration object. */ - public function getConfig() + public function getConfig() : Configuration { return $this->config; } @@ -171,10 +172,8 @@ class IdP * * @return array|null The name of the SP, as an associative array of language => text, or null if this isn't an SP. */ - public function getSPName($assocId) + public function getSPName(string $assocId) : ?array { - Assert::string($assocId); - $prefix = substr($assocId, 0, 4); $spEntityId = substr($assocId, strlen($prefix) + 1); $metadata = MetaDataStorageHandler::getMetadataHandler(); @@ -209,7 +208,7 @@ class IdP * @param array $association The SP association. * @return void */ - public function addAssociation(array $association) + public function addAssociation(array $association) : void { Assert::notNull($association['id']); Assert::notNull($association['Handler']); @@ -226,7 +225,7 @@ class IdP * * @return array List of SP associations. */ - public function getAssociations() + public function getAssociations() : array { $session = Session::getSessionFromRequest(); return $session->getAssociations($this->associationGroup); @@ -239,10 +238,8 @@ class IdP * @param string $assocId The association id. * @return void */ - public function terminateAssociation($assocId) + public function terminateAssociation(string $assocId) : void { - Assert::string($assocId); - $session = Session::getSessionFromRequest(); $session->terminateAssociation($this->associationGroup, $assocId); } @@ -253,7 +250,7 @@ class IdP * * @return boolean True if the user is authenticated, false otherwise. */ - public function isAuthenticated() + public function isAuthenticated() : bool { return $this->authSource->isAuthenticated(); } @@ -265,7 +262,7 @@ class IdP * @param array $state The authentication request state array. * @return void */ - public static function postAuthProc(array $state) + public static function postAuthProc(array $state) : void { Assert::isCallable($state['Responder']); @@ -292,7 +289,7 @@ class IdP * @throws \SimpleSAML\Error\Exception If we are not authenticated. * @return void */ - public static function postAuth(array $state) + public static function postAuth(array $state) : void { $idp = IdP::getByState($state); @@ -340,7 +337,7 @@ class IdP * @throws \SimpleSAML\Module\saml\Error\NoPassive If we were asked to do passive authentication. * @return void */ - private function authenticate(array &$state) + private function authenticate(array &$state) : void { if (isset($state['isPassive']) && (bool) $state['isPassive']) { throw new NoPassive(Constants::STATUS_RESPONDER, 'Passive authentication not supported.'); @@ -363,7 +360,7 @@ class IdP * @throws \Exception If there is no auth source defined for this IdP. * @return void */ - private function reauthenticate(array &$state) + private function reauthenticate(array &$state) : void { $sourceImpl = $this->authSource->getAuthSource(); $sourceImpl->reauthenticate($state); @@ -376,7 +373,7 @@ class IdP * @param array &$state The authentication request state. * @return void */ - public function handleAuthenticationRequest(array &$state) + public function handleAuthenticationRequest(array &$state) : void { Assert::notNull($state['Responder']); @@ -422,19 +419,20 @@ class IdP /** * Find the logout handler of this IdP. * - * @return IdP\LogoutHandlerInterface The logout handler class. + * @return \SimpleSAML\IdP\LogoutHandlerInterface The logout handler class. + * * @throws \Exception If we cannot find a logout handler. */ - public function getLogoutHandler() + public function getLogoutHandler() : LogoutHandlerInterface { // find the logout handler $logouttype = $this->getConfig()->getString('logouttype', 'traditional'); switch ($logouttype) { case 'traditional': - $handler = '\SimpleSAML\IdP\TraditionalLogoutHandler'; + $handler = TraditionalLogoutHandler::class; break; case 'iframe': - $handler = '\SimpleSAML\IdP\IFrameLogoutHandler'; + $handler = IFrameLogoutHandler::class; break; default: throw new Error\Exception('Unknown logout handler: ' . var_export($logouttype, true)); @@ -453,7 +451,7 @@ class IdP * @param array &$state The logout request state. * @return void */ - public function finishLogout(array &$state) + public function finishLogout(array &$state) : void { Assert::notNull($state['Responder']); @@ -473,7 +471,7 @@ class IdP * association. * @return void */ - public function handleLogoutRequest(array &$state, $assocId) + public function handleLogoutRequest(array &$state, ?string $assocId) : void { Assert::notNull($state['Responder']); Assert::nullOrString($assocId); @@ -511,11 +509,8 @@ class IdP * @param \SimpleSAML\Error\Exception|null $error The error that occurred during session termination (if any). * @return void */ - public function handleLogoutResponse($assocId, $relayState, Error\Exception $error = null) + public function handleLogoutResponse(string $assocId, ?string $relayState, Error\Exception $error = null): void { - Assert::string($assocId); - Assert::nullOrString($relayState); - $index = strpos($assocId, ':'); Assert::integer($index); @@ -537,12 +532,10 @@ class IdP * @param string $url The URL the user should be returned to after logout. * @return void */ - public function doLogoutRedirect($url) + public function doLogoutRedirect(string $url): void { - Assert::string($url); - $state = [ - 'Responder' => ['\SimpleSAML\IdP', 'finishLogoutRedirect'], + 'Responder' => [IdP::class, 'finishLogoutRedirect'], 'core:Logout:URL' => $url, ]; @@ -560,7 +553,7 @@ class IdP * @param array &$state The logout state from doLogoutRedirect(). * @return void */ - public static function finishLogoutRedirect(IdP $idp, array $state) + public static function finishLogoutRedirect(IdP $idp, array $state) : void { Assert::notNull($state['core:Logout:URL']); diff --git a/lib/SimpleSAML/Logger.php b/lib/SimpleSAML/Logger.php index 5556e22a1..a62a73b83 100644 --- a/lib/SimpleSAML/Logger.php +++ b/lib/SimpleSAML/Logger.php @@ -4,7 +4,12 @@ declare(strict_types=1); namespace SimpleSAML; +use Exception; use SimpleSAML\Logger\ErrorLogLoggingHandler; +use SimpleSAML\Logger\FileLoggingHandler; +use SimpleSAML\Logger\LoggingHandlerInterface; +use SimpleSAML\Logger\StandardErrorLoggingHandler; +use SimpleSAML\Logger\SyslogLoggingHandler; use Webmozart\Assert\Assert; /** @@ -159,7 +164,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function emergency($string) + public static function emergency(string $string) : void { self::log(self::EMERG, $string); } @@ -171,7 +176,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function critical($string) + public static function critical(string $string) : void { self::log(self::CRIT, $string); } @@ -183,7 +188,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function alert($string) + public static function alert(string $string) : void { self::log(self::ALERT, $string); } @@ -195,7 +200,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function error($string) + public static function error(string $string) : void { self::log(self::ERR, $string); } @@ -207,7 +212,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function warning($string) + public static function warning(string $string) : void { self::log(self::WARNING, $string); } @@ -219,7 +224,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function notice($string) + public static function notice(string $string) : void { self::log(self::NOTICE, $string); } @@ -231,7 +236,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function info($string) + public static function info(string $string) : void { self::log(self::INFO, $string); } @@ -244,7 +249,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function debug($string) + public static function debug(string $string) : void { self::log(self::DEBUG, $string); } @@ -256,7 +261,7 @@ class Logger * @param string $string The message to log. * @return void */ - public static function stats($string) + public static function stats(string $string) : void { self::log(self::NOTICE, $string, true); } @@ -268,7 +273,7 @@ class Logger * @param boolean $val Whether to capture logs or not. Defaults to TRUE. * @return void */ - public static function setCaptureLog($val = true) + public static function setCaptureLog(bool $val = true) : void { self::$captureLog = $val; } @@ -278,7 +283,7 @@ class Logger * Get the captured log. * @return array */ - public static function getCapturedLog() + public static function getCapturedLog() : array { return self::$capturedLog; } @@ -290,7 +295,7 @@ class Logger * @param string $trackId The track identifier to use during this session. * @return void */ - public static function setTrackId($trackId) + public static function setTrackId(string $trackId) : void { self::$trackid = $trackId; self::flush(); @@ -319,12 +324,12 @@ class Logger * * @return void */ - public static function shutdown() + public static function shutdown() : void { if (self::$trackid === self::NO_TRACKID) { try { $s = Session::getSessionFromRequest(); - } catch (\Exception $e) { + } catch (Exception $e) { // loading session failed. We don't care why, at this point we have a transient session, so we use that $s = Session::getSessionFromRequest(); } @@ -342,7 +347,7 @@ class Logger * * @return bool True if the error is masked, false otherwise. */ - public static function isErrorMasked($errno) + public static function isErrorMasked(int $errno) : bool { return ($errno & self::$logMask) || !($errno & error_reporting()); } @@ -356,10 +361,8 @@ class Logger * @param int $mask The log levels that should be masked. * @return void */ - public static function maskErrors($mask) + public static function maskErrors(int $mask) : void { - Assert::integer($mask); - $currentEnabled = error_reporting(); self::$logLevelStack[] = [$currentEnabled, self::$logMask]; @@ -376,7 +379,7 @@ class Logger * * @return void */ - public static function popErrorMask() + public static function popErrorMask(): void { $lastMask = array_pop(self::$logLevelStack); error_reporting($lastMask[0]); @@ -392,7 +395,7 @@ class Logger * @param boolean $stats Whether this is a stats message or a regular one. * @return void */ - private static function defer(int $level, string $message, bool $stats) + private static function defer(int $level, string $message, bool $stats): void { // save the message for later self::$earlyLog[] = ['level' => $level, 'string' => $message, 'statsLog' => $stats]; @@ -410,16 +413,16 @@ class Logger * @return void * @throws \Exception */ - private static function createLoggingHandler(string $handler = null) + private static function createLoggingHandler(?string $handler = null): void { self::$initializing = true; // a set of known logging handlers $known_handlers = [ - 'syslog' => 'SimpleSAML\Logger\SyslogLoggingHandler', - 'file' => 'SimpleSAML\Logger\FileLoggingHandler', - 'errorlog' => 'SimpleSAML\Logger\ErrorLogLoggingHandler', - 'stderr' => 'SimpleSAML\Logger\StandardErrorLoggingHandler', + 'syslog' => SyslogLoggingHandler::class, + 'file' => FileLoggingHandler::class, + 'errorlog' => ErrorLogLoggingHandler::class, + 'stderr' => StandardErrorLoggingHandler::class, ]; // get the configuration @@ -435,13 +438,13 @@ class Logger } if (!array_key_exists($handler, $known_handlers) && class_exists($handler)) { - if (!in_array('SimpleSAML\Logger\LoggingHandlerInterface', class_implements($handler), true)) { - throw new \Exception("The logging handler '$handler' is invalid."); + if (!in_array(LoggingHandlerInterface::class, class_implements($handler), true)) { + throw new Exception("The logging handler '$handler' is invalid."); } } else { $handler = strtolower($handler); if (!array_key_exists($handler, $known_handlers)) { - throw new \Exception( + throw new Exception( "Invalid value for the 'logging.handler' configuration option. Unknown handler '" . $handler . "'." ); } @@ -455,7 +458,7 @@ class Logger self::$loggingHandler = new $handler($config); self::$loggingHandler->setLogFormat(self::$format); self::$initializing = false; - } catch (\Exception $e) { + } catch (Exception $e) { self::$loggingHandler = new ErrorLogLoggingHandler($config); self::$initializing = false; self::log(self::CRIT, $e->getMessage(), false); @@ -469,7 +472,7 @@ class Logger * @param bool $statsLog * @return void */ - private static function log(int $level, string $string, bool $statsLog = false) + private static function log(int $level, string $string, bool $statsLog = false): void { if (self::$initializing) { // some error occurred while initializing logging @@ -478,7 +481,7 @@ class Logger } elseif (php_sapi_name() === 'cli' || defined('STDIN')) { // we are being executed from the CLI, nowhere to log if (!isset(self::$loggingHandler)) { - self::createLoggingHandler(\SimpleSAML\Logger\StandardErrorLoggingHandler::class); + self::createLoggingHandler(StandardErrorLoggingHandler::class); } $_SERVER['REMOTE_ADDR'] = "CLI"; if (self::$trackid === self::NO_TRACKID) { diff --git a/lib/SimpleSAML/Memcache.php b/lib/SimpleSAML/Memcache.php index 196608bc7..e9a23c904 100644 --- a/lib/SimpleSAML/Memcache.php +++ b/lib/SimpleSAML/Memcache.php @@ -49,7 +49,7 @@ class Memcache * * @return mixed The data stored with the given key, or null if no data matching the key was found. */ - public static function get($key) + public static function get(string $key) { Logger::debug("loading key $key from memcache"); @@ -154,7 +154,7 @@ class Memcache * @param integer|null $expire The expiration timestamp of the data. * @return void */ - public static function set($key, $value, $expire = null) + public static function set(string $key, $value, ?int $expire = null) : void { Logger::debug("saving key $key to memcache"); $savedInfo = [ @@ -185,9 +185,8 @@ class Memcache * @param string $key The key we should delete. * @return void */ - public static function delete($key) + public static function delete(string $key): void { - Assert::string($key); Logger::debug("deleting key $key from memcache"); // store this object to all groups of memcache servers @@ -221,7 +220,7 @@ class Memcache * * @throws \Exception If any configuration option for the server is invalid. */ - private static function addMemcacheServer($memcache, array $server) + private static function addMemcacheServer($memcache, array $server): void { // the hostname option is required if (!array_key_exists('hostname', $server)) { @@ -444,7 +443,7 @@ class Memcache * * @throws \Exception If memcache server status couldn't be retrieved. */ - public static function getStats() + public static function getStats() : array { $ret = []; @@ -471,7 +470,7 @@ class Memcache * * @return array An array with the extended stats output for each server group. */ - public static function getRawStats() + public static function getRawStats() : array { $ret = []; diff --git a/lib/SimpleSAML/Module.php b/lib/SimpleSAML/Module.php index 674312c30..d1d3b34f3 100644 --- a/lib/SimpleSAML/Module.php +++ b/lib/SimpleSAML/Module.php @@ -86,7 +86,7 @@ class Module * * @return string The base directory of a module. */ - public static function getModuleDir($module) + public static function getModuleDir(string $module) : string { $baseDir = dirname(dirname(dirname(__FILE__))) . '/modules'; $moduleDir = $baseDir . '/' . $module; @@ -106,7 +106,7 @@ class Module * * @throws \Exception If module.enable is set and is not boolean. */ - public static function isModuleEnabled($module) + public static function isModuleEnabled(string $module) : bool { $config = Configuration::getOptionalConfig(); return self::isModuleEnabledWithConf($module, $config->getArray('module.enable', [])); @@ -374,7 +374,7 @@ class Module * * @throws \Exception If we cannot open the module's directory. */ - public static function getModules() + public static function getModules() : array { if (!empty(self::$modules)) { return self::$modules; @@ -422,12 +422,8 @@ class Module * * @throws \Exception If the class cannot be resolved. */ - public static function resolveClass($id, $type, $subclass = null) + public static function resolveClass(string $id, string $type, ?string $subclass = null): string { - Assert::string($id); - Assert::string($type); - Assert::nullOrString($subclass); - $tmp = explode(':', $id, 2); if (count($tmp) === 1) { // no module involved @@ -474,9 +470,8 @@ class Module * * @return string The absolute URL to the given resource. */ - public static function getModuleURL($resource, array $parameters = []) + public static function getModuleURL(string $resource, array $parameters = []): string { - Assert::string($resource); Assert::notSame($resource[0], '/'); $url = Utils\HTTP::getBaseURL() . 'module.php/' . $resource; @@ -496,7 +491,7 @@ class Module * points to the file that contains the hook, and 'func' contains the name of the function implementing that hook. * When there are no hooks defined, an empty array is returned. */ - public static function getModuleHooks($module) + public static function getModuleHooks(string $module): array { if (isset(self::$modules[$module]['hooks'])) { return self::$modules[$module]['hooks']; @@ -536,10 +531,8 @@ class Module * * @throws \SimpleSAML\Error\Exception If an invalid hook is found in a module. */ - public static function callHooks($hook, &$data = null) + public static function callHooks(string $hook, &$data = null): void { - Assert::string($hook); - $modules = self::getModules(); $config = Configuration::getOptionalConfig()->getArray('module.enable', []); sort($modules); @@ -592,11 +585,12 @@ class Module * * This method removes the trailing slash and redirects to the resulting URL. * - * @param Request $request The request to process by this controller method. + * @param Symfony\Component\HttpFoundation\Request $request The request to process by this controller method. * - * @return RedirectResponse A redirection to the URI specified in the request, but without the trailing slash. + * @return \Symfony\Component\HttpFoundation\RedirectResponse + * A redirection to the URI specified in the request, but without the trailing slash. */ - public static function removeTrailingSlash(Request $request) + public static function removeTrailingSlash(Request $request) : RedirectResponse { $pathInfo = $request->server->get('PATH_INFO'); $url = str_replace($pathInfo, rtrim($pathInfo, ' /'), $request->getRequestUri()); diff --git a/lib/SimpleSAML/Session.php b/lib/SimpleSAML/Session.php index fdb69c961..26cba31e3 100644 --- a/lib/SimpleSAML/Session.php +++ b/lib/SimpleSAML/Session.php @@ -191,7 +191,7 @@ class Session implements \Serializable, Utils\ClearableState * @param Configuration $config * @return void */ - public function setConfiguration(Configuration $config) + public function setConfiguration(Configuration $config) : void { self::$config = $config; } @@ -204,11 +204,12 @@ class Session implements \Serializable, Utils\ClearableState * * @return string The serialized representation of this session object. */ - public function serialize() + public function serialize() : string { return serialize(get_object_vars($this)); } + /** * Unserialize a session object and load it.. * @@ -216,8 +217,11 @@ class Session implements \Serializable, Utils\ClearableState * be serializable in its original form (e.g.: DOM objects). * * @param string $serialized The serialized representation of a session that we want to restore. + * @return void + * + * Cannot typehint param as string due to upstream restrictions */ - public function unserialize($serialized) + public function unserialize($serialized) : void { $session = unserialize($serialized); if (is_array($session)) { @@ -243,13 +247,14 @@ class Session implements \Serializable, Utils\ClearableState } } + /** * Retrieves the current session. Creates a new session if there's not one. * * @return Session The current session. * @throws \Exception When session couldn't be initialized and the session fallback is disabled by configuration. */ - public static function getSessionFromRequest() + public static function getSessionFromRequest() : Session { // check if we already have initialized the session if (isset(self::$instance)) { @@ -315,6 +320,7 @@ class Session implements \Serializable, Utils\ClearableState return self::$instance; } + /** * Get a session from the session handler. * @@ -323,10 +329,8 @@ class Session implements \Serializable, Utils\ClearableState * @return Session|null The session that is stored in the session handler, or null if the session wasn't * found. */ - public static function getSession($sessionId = null) + public static function getSession(string $sessionId = null): ?Session { - Assert::nullOrString($sessionId); - $sh = SessionHandler::getSessionHandler(); if ($sessionId === null) { @@ -384,6 +388,7 @@ class Session implements \Serializable, Utils\ClearableState return $session; } + /** * Load a given session as the current one. * @@ -401,6 +406,7 @@ class Session implements \Serializable, Utils\ClearableState return self::$instance; } + /** * Use a transient session. * @@ -409,7 +415,7 @@ class Session implements \Serializable, Utils\ClearableState * * @return void */ - public static function useTransientSession() + public static function useTransientSession(): void { if (isset(self::$instance)) { // we already have a session, don't bother with a transient session @@ -419,18 +425,19 @@ class Session implements \Serializable, Utils\ClearableState self::load(new Session(true)); } + /** * Create a new session and cache it. * * @param string $sessionId The new session we should create. * @return void */ - public static function createSession($sessionId) + public static function createSession(string $sessionId): void { - Assert::string($sessionId); self::$sessions[$sessionId] = null; } + /** * Save the session to the store. * @@ -441,7 +448,7 @@ class Session implements \Serializable, Utils\ClearableState * * @return void */ - public function save() + public function save(): void { // clean out old data $this->expireData(); @@ -467,6 +474,7 @@ class Session implements \Serializable, Utils\ClearableState } } + /** * Save the current session and clean any left overs that could interfere with the normal application behaviour. * @@ -475,7 +483,7 @@ class Session implements \Serializable, Utils\ClearableState * * @return void */ - public function cleanup() + public function cleanup() : void { $this->save(); $sh = SessionHandler::getSessionHandler(); @@ -484,6 +492,7 @@ class Session implements \Serializable, Utils\ClearableState } } + /** * Mark this session as dirty. * @@ -491,7 +500,7 @@ class Session implements \Serializable, Utils\ClearableState * * @return void */ - public function markDirty() + public function markDirty() : void { if ($this->isTransient()) { return; @@ -506,67 +515,71 @@ class Session implements \Serializable, Utils\ClearableState $this->callback_registered = header_register_callback([$this, 'save']); } + /** * Destroy the session. * * Destructor for this class. It will save the session to the session handler * in case the session has been marked as dirty. Do nothing otherwise. - * - * @return void */ public function __destruct() { $this->save(); } + /** * Retrieve the session ID of this session. * - * @return string|null The session ID, or null if this is a transient session. + * @return string|null The session ID, or NULL for transient sessions. */ - public function getSessionId() + public function getSessionId() : ?string { return $this->sessionId; } + /** * Retrieve if session is transient. * * @return boolean The session transient flag. */ - public function isTransient() + public function isTransient() : bool { return $this->transient; } + /** * Get a unique ID that will be permanent for this session. * Used for debugging and tracing log files related to a session. * * @return string The unique ID. */ - public function getTrackID() + public function getTrackID() : string { return $this->trackid; } + /** * Get remember me expire time. * * @return integer|null The remember me expire time. */ - public function getRememberMeExpire() + public function getRememberMeExpire() : ?int { return $this->rememberMeExpire; } + /** * Set remember me expire time. * * @param int $expire Unix timestamp when remember me session cookies expire. * @return void */ - public function setRememberMeExpire($expire = null) + public function setRememberMeExpire(int $expire = null) : void { Assert::nullOrInteger($expire); @@ -579,6 +592,7 @@ class Session implements \Serializable, Utils\ClearableState $this->updateSessionCookies($cookieParams); } + /** * Marks the user as logged in with the specified authority. * @@ -590,11 +604,8 @@ class Session implements \Serializable, Utils\ClearableState * * @throws Error\CannotSetCookie If the authentication token cannot be set for some reason. */ - public function doLogin($authority, array $data = null) + public function doLogin(string $authority, array $data = null): void { - Assert::string($authority); - Assert::nullOrArray($data); - Logger::debug('Session: doLogin("' . $authority . '")'); $this->markDirty(); @@ -679,6 +690,7 @@ class Session implements \Serializable, Utils\ClearableState } } + /** * Marks the user as logged out. * @@ -687,7 +699,7 @@ class Session implements \Serializable, Utils\ClearableState * @param string $authority The authentication source we are logging out of. * @return void */ - public function doLogout($authority) + public function doLogout(string $authority) : void { Logger::debug('Session: doLogout(' . var_export($authority, true) . ')'); @@ -707,6 +719,7 @@ class Session implements \Serializable, Utils\ClearableState } } + /** * This function calls all registered logout handlers. * @@ -715,7 +728,7 @@ class Session implements \Serializable, Utils\ClearableState * * @throws \Exception If the handler is not a valid function or method. */ - private function callLogoutHandlers(string $authority) + private function callLogoutHandlers(string $authority): void { Assert::notNull($this->authData[$authority]); @@ -742,6 +755,7 @@ class Session implements \Serializable, Utils\ClearableState unset($this->authData[$authority]['LogoutHandlers']); } + /** * Is the session representing an authenticated user, and is the session still alive. * This function will return false after the user has timed out. @@ -750,10 +764,8 @@ class Session implements \Serializable, Utils\ClearableState * * @return bool True if the user has a valid session, false if not. */ - public function isValid($authority) + public function isValid(string $authority): bool { - Assert::string($authority); - if (!isset($this->authData[$authority])) { Logger::debug( 'Session: ' . var_export($authority, true) . @@ -772,16 +784,15 @@ class Session implements \Serializable, Utils\ClearableState return true; } + /** * Update session cookies. * * @param array $params The parameters for the cookies. * @return void */ - public function updateSessionCookies($params = null) + public function updateSessionCookies(array $params = null): void { - Assert::nullOrArray($params); - $sessionHandler = SessionHandler::getSessionHandler(); if ($this->sessionId !== null) { @@ -799,6 +810,7 @@ class Session implements \Serializable, Utils\ClearableState } } + /** * Set the lifetime for authentication source. * @@ -806,11 +818,8 @@ class Session implements \Serializable, Utils\ClearableState * @param int $expire The number of seconds authentication source is valid. * @return void */ - public function setAuthorityExpire($authority, $expire = null) + public function setAuthorityExpire(string $authority, int $expire = null): void { - Assert::notNull($this->authData[$authority]); - Assert::nullOrInteger($expire); - $this->markDirty(); if ($expire === null) { @@ -820,6 +829,7 @@ class Session implements \Serializable, Utils\ClearableState $this->authData[$authority]['Expire'] = $expire; } + /** * This function registers a logout handler. * @@ -830,7 +840,7 @@ class Session implements \Serializable, Utils\ClearableState * * @throws \Exception If the handler is not a valid function or method. */ - public function registerLogoutHandler($authority, $classname, $functionname) + public function registerLogoutHandler(string $authority, string $classname, string $functionname) : void { Assert::notNull($this->authData[$authority]); @@ -847,6 +857,7 @@ class Session implements \Serializable, Utils\ClearableState $this->markDirty(); } + /** * Delete data from the data store. * @@ -856,11 +867,8 @@ class Session implements \Serializable, Utils\ClearableState * @param string $id The identifier of the data. * @return void */ - public function deleteData($type, $id) + public function deleteData(string $type, string $id): void { - Assert::string($type); - Assert::string($id); - if (!array_key_exists($type, $this->dataStore)) { return; } @@ -869,6 +877,7 @@ class Session implements \Serializable, Utils\ClearableState $this->markDirty(); } + /** * This function stores data in the data store. * @@ -886,10 +895,8 @@ class Session implements \Serializable, Utils\ClearableState * @throws \Exception If the data couldn't be stored. * */ - public function setData($type, $id, $data, $timeout = null) + public function setData(string $type, string $id, $data, $timeout = null): void { - Assert::string($type); - Assert::string($id); Assert::true(is_int($timeout) || $timeout === null || $timeout === self::DATA_TIMEOUT_SESSION_END); if ($timeout === null) { @@ -926,12 +933,13 @@ class Session implements \Serializable, Utils\ClearableState $this->markDirty(); } + /** * This function removes expired data from the data store. * * @return void */ - private function expireData() + private function expireData() : void { $ct = time(); @@ -950,6 +958,7 @@ class Session implements \Serializable, Utils\ClearableState } } + /** * This function retrieves data from the data store. * @@ -961,11 +970,8 @@ class Session implements \Serializable, Utils\ClearableState * * @return mixed The data of the given type with the given id or null if the data doesn't exist in the data store. */ - public function getData($type, $id) + public function getData(string $type, ?string $id) { - Assert::string($type); - Assert::nullOrString($id); - if ($id === null) { return null; } @@ -981,6 +987,7 @@ class Session implements \Serializable, Utils\ClearableState return $this->dataStore[$type][$id]['data']; } + /** * This function retrieves all data of the specified type from the data store. * @@ -994,10 +1001,8 @@ class Session implements \Serializable, Utils\ClearableState * * @return array An associative array with all data of the given type. */ - public function getDataOfType($type) + public function getDataOfType(string $type): array { - Assert::string($type); - if (!array_key_exists($type, $this->dataStore)) { return []; } @@ -1010,6 +1015,7 @@ class Session implements \Serializable, Utils\ClearableState return $ret; } + /** * Get the current persistent authentication state. * @@ -1017,10 +1023,8 @@ class Session implements \Serializable, Utils\ClearableState * * @return array|null The current persistent authentication state, or null if not authenticated. */ - public function getAuthState($authority) + public function getAuthState(string $authority): ?array { - Assert::string($authority); - if (!isset($this->authData[$authority])) { return null; } @@ -1028,6 +1032,7 @@ class Session implements \Serializable, Utils\ClearableState return $this->authData[$authority]; } + /** * Check whether the session cookie is set. * @@ -1035,12 +1040,13 @@ class Session implements \Serializable, Utils\ClearableState * * @return bool true if it was set, false if not. */ - public function hasSessionCookie() + public function hasSessionCookie() : bool { $sh = SessionHandler::getSessionHandler(); return $sh->hasSessionCookie(); } + /** * Add an SP association for an IdP. * @@ -1050,9 +1056,8 @@ class Session implements \Serializable, Utils\ClearableState * @param array $association The association we should add. * @return void */ - public function addAssociation($idp, array $association) + public function addAssociation(string $idp, array $association): void { - Assert::string($idp); Assert::notNull($association['id']); Assert::notNull($association['Handler']); @@ -1069,6 +1074,7 @@ class Session implements \Serializable, Utils\ClearableState $this->markDirty(); } + /** * Retrieve the associations for an IdP. * @@ -1078,10 +1084,8 @@ class Session implements \Serializable, Utils\ClearableState * * @return array The IdP associations. */ - public function getAssociations($idp) + public function getAssociations(string $idp): array { - Assert::string($idp); - if (!isset($this->associations)) { $this->associations = []; } @@ -1104,6 +1108,7 @@ class Session implements \Serializable, Utils\ClearableState return $this->associations[$idp]; } + /** * Remove an SP association for an IdP. * @@ -1113,11 +1118,8 @@ class Session implements \Serializable, Utils\ClearableState * @param string $associationId The id of the association. * @return void */ - public function terminateAssociation($idp, $associationId) + public function terminateAssociation(string $idp, string $associationId): void { - Assert::string($idp); - Assert::string($associationId); - if (!isset($this->associations)) { return; } @@ -1131,6 +1133,7 @@ class Session implements \Serializable, Utils\ClearableState $this->markDirty(); } + /** * Retrieve authentication data. * @@ -1139,17 +1142,15 @@ class Session implements \Serializable, Utils\ClearableState * * @return mixed The value, or null if the value wasn't found. */ - public function getAuthData($authority, $name) + public function getAuthData(string $authority, string $name) { - Assert::string($authority); - Assert::string($name); - if (!isset($this->authData[$authority][$name])) { return null; } return $this->authData[$authority][$name]; } + /** * Retrieve a list of authorities (authentication sources) that are currently valid within * this session. @@ -1172,7 +1173,7 @@ class Session implements \Serializable, Utils\ClearableState * Clear any configuration information cached * @return void */ - public static function clearInternalState() + public static function clearInternalState() : void { self::$config = null; self::$instance = null; diff --git a/lib/SimpleSAML/SessionHandler.php b/lib/SimpleSAML/SessionHandler.php index df9fd6738..db0935990 100644 --- a/lib/SimpleSAML/SessionHandler.php +++ b/lib/SimpleSAML/SessionHandler.php @@ -37,7 +37,7 @@ abstract class SessionHandler * * @throws \Exception If we cannot instantiate the session handler. */ - public static function getSessionHandler() + public static function getSessionHandler() : SessionHandler { if (self::$sessionHandler === null) { self::createSessionHandler(); @@ -62,7 +62,7 @@ abstract class SessionHandler * * @return string The new session id. */ - abstract public function newSessionId(); + abstract public function newSessionId() : string; /** @@ -70,7 +70,7 @@ abstract class SessionHandler * * @return string|null The session id saved in the cookie or null if no session cookie was set. */ - abstract public function getCookieSessionId(); + abstract public function getCookieSessionId() : ?string; /** @@ -78,15 +78,16 @@ abstract class SessionHandler * * @return string The session cookie name. */ - abstract public function getSessionCookieName(); + abstract public function getSessionCookieName() : string; /** * Save the session. * * @param \SimpleSAML\Session $session The session object we should save. + * @return void */ - abstract public function saveSession(Session $session); + abstract public function saveSession(Session $session) : void; /** @@ -96,7 +97,7 @@ abstract class SessionHandler * * @return \SimpleSAML\Session|null The session object, or null if it doesn't exist. */ - abstract public function loadSession($sessionId = null); + abstract public function loadSession(?string $sessionId) : ?Session; /** @@ -106,7 +107,7 @@ abstract class SessionHandler * * @return bool True if it was set, false if not. */ - abstract public function hasSessionCookie(); + abstract public function hasSessionCookie() : bool; /** @@ -115,10 +116,11 @@ abstract class SessionHandler * @param string $sessionName The name of the session. * @param string|null $sessionID The session ID to use. Set to null to delete the cookie. * @param array|null $cookieParams Additional parameters to use for the session cookie. + * @return void * * @throws \SimpleSAML\Error\CannotSetCookie If we can't set the cookie. */ - abstract public function setCookie($sessionName, $sessionID, array $cookieParams = null); + abstract public function setCookie(string $sessionName, ?string $sessionID, array $cookieParams = null) : void; /** @@ -133,7 +135,7 @@ abstract class SessionHandler * * @throws \Exception If we cannot instantiate the session handler. */ - private static function createSessionHandler() + private static function createSessionHandler() : void { $store = Store::getInstance(); if ($store === false) { @@ -150,7 +152,7 @@ abstract class SessionHandler * @return array An array with the cookie parameters. * @link http://www.php.net/manual/en/function.session-get-cookie-params.php */ - public function getCookieParams() + public function getCookieParams() : array { $config = Configuration::getInstance(); diff --git a/lib/SimpleSAML/SessionHandlerCookie.php b/lib/SimpleSAML/SessionHandlerCookie.php index 02c3de3f5..c66112fe6 100644 --- a/lib/SimpleSAML/SessionHandlerCookie.php +++ b/lib/SimpleSAML/SessionHandlerCookie.php @@ -55,7 +55,7 @@ abstract class SessionHandlerCookie extends SessionHandler * * @return string The new session id. */ - public function newSessionId() + public function newSessionId() : string { $this->session_id = self::createSessionID(); Session::createSession($this->session_id); @@ -69,7 +69,7 @@ abstract class SessionHandlerCookie extends SessionHandler * * @return string|null The session id saved in the cookie or null if no session cookie was set. */ - public function getCookieSessionId() + public function getCookieSessionId() : ?string { if ($this->session_id === null) { if ($this->hasSessionCookie()) { @@ -93,7 +93,7 @@ abstract class SessionHandlerCookie extends SessionHandler * * @return string The session cookie name. */ - public function getSessionCookieName() + public function getSessionCookieName() : string { return $this->cookie_name; } @@ -120,7 +120,6 @@ abstract class SessionHandlerCookie extends SessionHandler */ private static function isValidSessionID(string $session_id): bool { - if (strlen($session_id) != 32) { return false; } @@ -140,7 +139,7 @@ abstract class SessionHandlerCookie extends SessionHandler * * @return boolean True if it was set, false otherwise. */ - public function hasSessionCookie() + public function hasSessionCookie(): bool { return array_key_exists($this->cookie_name, $_COOKIE); } @@ -156,11 +155,8 @@ abstract class SessionHandlerCookie extends SessionHandler * * @throws \SimpleSAML\Error\CannotSetCookie If we can't set the cookie. */ - public function setCookie($sessionName, $sessionID, array $cookieParams = null) + public function setCookie(string $sessionName, ?string $sessionID, array $cookieParams = null): void { - Assert::string($sessionName); - Assert::nullOrString($sessionID); - if ($cookieParams !== null) { $params = array_merge($this->getCookieParams(), $cookieParams); } else { diff --git a/lib/SimpleSAML/SessionHandlerPHP.php b/lib/SimpleSAML/SessionHandlerPHP.php index 27fba38a8..ec4257de8 100644 --- a/lib/SimpleSAML/SessionHandlerPHP.php +++ b/lib/SimpleSAML/SessionHandlerPHP.php @@ -123,7 +123,7 @@ class SessionHandlerPHP extends SessionHandler * * @return void */ - public function restorePrevious() + public function restorePrevious() : void { if (empty($this->previous_session)) { return; // nothing to do here @@ -162,7 +162,7 @@ class SessionHandlerPHP extends SessionHandler * * @return string The new session id. */ - public function newSessionId() + public function newSessionId() : string { // generate new (secure) session id if (function_exists('session_create_id')) { @@ -187,7 +187,7 @@ class SessionHandlerPHP extends SessionHandler * * @throws \SimpleSAML\Error\Exception If the cookie is marked as secure but we are not using HTTPS. */ - public function getCookieSessionId() + public function getCookieSessionId() : ?string { if (!$this->hasSessionCookie()) { return null; // there's no session cookie, can't return ID @@ -217,7 +217,7 @@ class SessionHandlerPHP extends SessionHandler * * @return string The session cookie name. */ - public function getSessionCookieName() + public function getSessionCookieName() : string { return $this->cookie_name; } @@ -229,7 +229,7 @@ class SessionHandlerPHP extends SessionHandler * @param \SimpleSAML\Session $session The session object we should save. * @return void */ - public function saveSession(\SimpleSAML\Session $session) + public function saveSession(Session $session): void { $_SESSION['SimpleSAMLphp_SESSION'] = serialize($session); } @@ -245,10 +245,8 @@ class SessionHandlerPHP extends SessionHandler * @throws \SimpleSAML\Error\Exception If it wasn't possible to disable session cookies or we are trying to load a * PHP session with a specific identifier and it doesn't match with the current session identifier. */ - public function loadSession($sessionId = null) + public function loadSession(string $sessionId = null): ?Session { - Assert::nullOrString($sessionId); - if ($sessionId !== null) { if (session_id() === '' && !(version_compare(PHP_VERSION, '7.2', 'ge') && headers_sent())) { // session not initiated with getCookieSessionId(), start session without setting cookie @@ -286,7 +284,7 @@ class SessionHandlerPHP extends SessionHandler * * @return boolean True if it was set, false otherwise. */ - public function hasSessionCookie() + public function hasSessionCookie() : bool { return array_key_exists($this->cookie_name, $_COOKIE); } @@ -303,7 +301,7 @@ class SessionHandlerPHP extends SessionHandler * @throws \SimpleSAML\Error\Exception If both 'session.phpsession.limitedpath' and 'session.cookie.path' options * are set at the same time in the configuration. */ - public function getCookieParams() + public function getCookieParams() : array { $config = Configuration::getInstance(); @@ -336,7 +334,7 @@ class SessionHandlerPHP extends SessionHandler * * @throws \SimpleSAML\Error\CannotSetCookie If we can't set the cookie. */ - public function setCookie($sessionName, $sessionID, array $cookieParams = null) + public function setCookie(string $sessionName, ?string $sessionID, array $cookieParams = null) : void { if ($cookieParams === null) { $cookieParams = session_get_cookie_params(); diff --git a/lib/SimpleSAML/SessionHandlerStore.php b/lib/SimpleSAML/SessionHandlerStore.php index 4f459fa84..b163a5bcc 100644 --- a/lib/SimpleSAML/SessionHandlerStore.php +++ b/lib/SimpleSAML/SessionHandlerStore.php @@ -42,10 +42,8 @@ class SessionHandlerStore extends SessionHandlerCookie * * @return \SimpleSAML\Session|null The session object, or null if it doesn't exist. */ - public function loadSession($sessionId = null) + public function loadSession(?string $sessionId): ?Session { - Assert::nullOrString($sessionId); - if ($sessionId === null) { $sessionId = $this->getCookieSessionId(); if ($sessionId === null) { @@ -70,7 +68,7 @@ class SessionHandlerStore extends SessionHandlerCookie * @param \SimpleSAML\Session $session The session object we should save. * @return void */ - public function saveSession(Session $session) + public function saveSession(Session $session) : void { if ($session->isTransient()) { // transient session, nothing to save diff --git a/lib/SimpleSAML/Stats.php b/lib/SimpleSAML/Stats.php index 7bb0aa33d..f63b46d9b 100644 --- a/lib/SimpleSAML/Stats.php +++ b/lib/SimpleSAML/Stats.php @@ -54,7 +54,7 @@ class Stats * * @return void */ - private static function initOutputs() + private static function initOutputs() : void { $config = Configuration::getInstance(); $outputCfgs = $config->getArray('statistics.out', []); @@ -74,9 +74,8 @@ class Stats * * @return void|boolean False if output is not enabled, void otherwise. */ - public static function log($event, array $data = []) + public static function log(string $event, array $data = []) { - Assert::string($event); Assert::keyNotExists($data, 'op'); Assert::keyNotExists($data, 'time'); Assert::keyNotExists($data, '_id'); diff --git a/lib/SimpleSAML/Store.php b/lib/SimpleSAML/Store.php index 4c2512851..364521df4 100644 --- a/lib/SimpleSAML/Store.php +++ b/lib/SimpleSAML/Store.php @@ -82,7 +82,7 @@ abstract class Store implements Utils\ClearableState * * @return mixed|null The value. */ - abstract public function get($type, $key); + abstract public function get(string $type, string $key); /** @@ -92,8 +92,9 @@ abstract class Store implements Utils\ClearableState * @param string $key The key. * @param mixed $value The value. * @param int|null $expire The expiration time (unix timestamp), or null if it never expires. + * @return void */ - abstract public function set($type, $key, $value, $expire = null); + abstract public function set(string $type, string $key, $value, ?int $expire = null) : void; /** @@ -101,15 +102,16 @@ abstract class Store implements Utils\ClearableState * * @param string $type The data type. * @param string $key The key. + * @return void */ - abstract public function delete($type, $key); + abstract public function delete(string $type, string $key) : void; /** * Clear any SSP specific state, such as SSP environmental variables or cached internals. * @return void */ - public static function clearInternalState() + public static function clearInternalState() : void { self::$instance = null; } diff --git a/lib/_autoload_modules.php b/lib/_autoload_modules.php index 621edabf0..105843a8d 100644 --- a/lib/_autoload_modules.php +++ b/lib/_autoload_modules.php @@ -15,7 +15,7 @@ declare(strict_types=1); * * @param string $className Name of the class. */ -function sspmodAutoloadPSR4(string $className) +function sspmodAutoloadPSR4(string $className): void { $elements = explode('\\', $className); if ($elements[0] === '') { -- GitLab