diff --git a/composer.json b/composer.json index 1f7c36dc..1d340fea 100644 --- a/composer.json +++ b/composer.json @@ -75,6 +75,9 @@ "stan": "@phpstan", "stan-baseline": "tools/phpstan --generate-baseline", "stan-setup": "phive install", + "rector-setup": "cp composer.json composer.backup && composer require --dev rector/rector:\"~2.3.1\" && mv composer.backup composer.json", + "rector-check": "vendor/bin/rector process --dry-run", + "rector-fix": "vendor/bin/rector process", "test": "phpunit", "test-coverage": "phpunit --coverage-clover=clover.xml" } diff --git a/rector.php b/rector.php new file mode 100644 index 00000000..a93e7edc --- /dev/null +++ b/rector.php @@ -0,0 +1,54 @@ +withPaths([ + __DIR__ . '/src', + __DIR__ . '/tests', + ]) + + ->withCache( + cacheClass: FileCacheStorage::class, + cacheDirectory: $cacheDir, + ) + + ->withPhpSets() + ->withAttributesSets() + + ->withSets([ + SetList::CODE_QUALITY, + SetList::CODING_STYLE, + SetList::DEAD_CODE, + SetList::EARLY_RETURN, + SetList::INSTANCEOF, + SetList::TYPE_DECLARATION, + ]) + + ->withSkip([ + ClassPropertyAssignToConstructorPromotionRector::class, + CatchExceptionNameMatchingTypeRector::class, + ClosureToArrowFunctionRector::class, + RemoveUselessReturnTagRector::class, + CompactToVariablesRector::class, + ReturnTypeFromStrictFluentReturnRector::class, + SplitDoubleAssignRector::class, + NewlineAfterStatementRector::class, + ExplicitBoolCompareRector::class, + TypedPropertyFromCreateMockAssignRector::class, + ]); diff --git a/src/AbstractCollection.php b/src/AbstractCollection.php index fcb73571..3e9a009c 100644 --- a/src/AbstractCollection.php +++ b/src/AbstractCollection.php @@ -41,7 +41,7 @@ abstract class AbstractCollection extends ObjectRegistry */ public function __construct(array $config = []) { - $configOptions = array_filter($config, fn($key) => is_string($key), ARRAY_FILTER_USE_KEY); + $configOptions = array_filter($config, is_string(...), ARRAY_FILTER_USE_KEY); $this->setConfig($configOptions); foreach ($config as $key => $value) { @@ -60,6 +60,6 @@ public function __construct(array $config = []) */ public function isEmpty(): bool { - return empty($this->_loaded); + return $this->_loaded === []; } } diff --git a/src/AuthenticationPlugin.php b/src/AuthenticationPlugin.php index 3400bf09..5f32f6ff 100644 --- a/src/AuthenticationPlugin.php +++ b/src/AuthenticationPlugin.php @@ -24,22 +24,16 @@ class AuthenticationPlugin extends BasePlugin { /** * Do bootstrapping or not - * - * @var bool */ protected bool $bootstrapEnabled = false; /** * Load routes or not - * - * @var bool */ protected bool $routesEnabled = false; /** * Console middleware - * - * @var bool */ protected bool $consoleEnabled = false; } diff --git a/src/AuthenticationService.php b/src/AuthenticationService.php index 45c05d15..051a5b79 100644 --- a/src/AuthenticationService.php +++ b/src/AuthenticationService.php @@ -40,22 +40,16 @@ class AuthenticationService implements AuthenticationServiceInterface, Impersona /** * Authenticator collection - * - * @var \Authentication\Authenticator\AuthenticatorCollection|null */ protected ?AuthenticatorCollection $_authenticators = null; /** * Authenticator that successfully authenticated the identity. - * - * @var \Authentication\Authenticator\AuthenticatorInterface|null */ protected ?AuthenticatorInterface $_successfulAuthenticator = null; /** * Result of the last authenticate() call. - * - * @var \Authentication\Authenticator\ResultInterface|null */ protected ?ResultInterface $_result = null; @@ -129,7 +123,7 @@ public function __construct(array $config = []) */ public function authenticators(): AuthenticatorCollection { - if ($this->_authenticators === null) { + if (!$this->_authenticators instanceof AuthenticatorCollection) { $authenticators = $this->getConfig('authenticators'); $this->_authenticators = new AuthenticatorCollection($authenticators); } @@ -259,7 +253,7 @@ public function getAuthenticationProvider(): ?AuthenticatorInterface */ public function getIdentificationProvider(): ?IdentifierInterface { - if ($this->_successfulAuthenticator === null) { + if (!$this->_successfulAuthenticator instanceof AuthenticatorInterface) { return null; } @@ -283,7 +277,7 @@ public function getResult(): ?ResultInterface */ public function getIdentity(): ?IdentityInterface { - if ($this->_result === null) { + if (!$this->_result instanceof ResultInterface) { return null; } @@ -319,16 +313,12 @@ public function buildIdentity(ArrayAccess|array $identityData): IdentityInterfac $class = $this->getConfig('identityClass'); - if (is_callable($class)) { - $identity = $class($identityData); - } else { - $identity = new $class($identityData); - } + $identity = is_callable($class) ? $class($identityData) : new $class($identityData); if (!($identity instanceof IdentityInterface)) { throw new RuntimeException(sprintf( 'Object `%s` does not implement `%s`', - get_class($identity), + $identity::class, IdentityInterface::class, )); } @@ -373,17 +363,17 @@ public function getUnauthenticatedRedirectUrl(ServerRequestInterface $request): if ($uri->getQuery()) { $redirect .= '?' . $uri->getQuery(); } - $query = urlencode($param) . '=' . urlencode($redirect); + $query = urlencode((string)$param) . '=' . urlencode($redirect); /** @var array $url */ - $url = parse_url($target); - if (isset($url['query']) && strlen($url['query'])) { + $url = parse_url((string)$target); + if (isset($url['query']) && strlen((string)$url['query'])) { $url['query'] .= '&' . $query; } else { $url['query'] = $query; } $fragment = isset($url['fragment']) ? '#' . $url['fragment'] : ''; - $url['path'] = $url['path'] ?? '/'; + $url['path'] ??= '/'; return $url['path'] . '?' . $url['query'] . $fragment; } @@ -404,12 +394,12 @@ public function getLoginRedirect(ServerRequestInterface $request): ?string if ( empty($redirectParam) || !isset($params[$redirectParam]) || - strlen($params[$redirectParam]) === 0 + (string)$params[$redirectParam] === '' ) { return null; } - $parsed = parse_url($params[$redirectParam]); + $parsed = parse_url((string)$params[$redirectParam]); if ($parsed === false) { return null; } @@ -418,10 +408,10 @@ public function getLoginRedirect(ServerRequestInterface $request): ?string } $parsed += ['path' => '/', 'query' => '']; if (strlen($parsed['path']) && $parsed['path'][0] !== '/') { - $parsed['path'] = "/{$parsed['path']}"; + $parsed['path'] = '/' . $parsed['path']; } if ($parsed['query']) { - $parsed['query'] = "?{$parsed['query']}"; + $parsed['query'] = '?' . $parsed['query']; } $redirect = $parsed['path'] . $parsed['query']; @@ -525,13 +515,13 @@ public function isImpersonating(ServerRequestInterface $request): bool protected function getImpersonationProvider(): ImpersonationInterface { $provider = $this->getAuthenticationProvider(); - if ($provider === null) { + if (!$provider instanceof AuthenticatorInterface) { throw new InvalidArgumentException('No AuthenticationProvider present.'); } if (!($provider instanceof ImpersonationInterface)) { - $className = get_class($provider); + $className = $provider::class; throw new InvalidArgumentException( - "The {$className} Provider must implement ImpersonationInterface in order to use impersonation.", + sprintf('The %s Provider must implement ImpersonationInterface in order to use impersonation.', $className), ); } diff --git a/src/Authenticator/AbstractAuthenticator.php b/src/Authenticator/AbstractAuthenticator.php index 50824ef5..5595e75e 100644 --- a/src/Authenticator/AbstractAuthenticator.php +++ b/src/Authenticator/AbstractAuthenticator.php @@ -41,8 +41,6 @@ abstract class AbstractAuthenticator implements AuthenticatorInterface /** * Identifier instance. - * - * @var \Authentication\Identifier\IdentifierInterface|null */ protected ?IdentifierInterface $_identifier = null; @@ -69,7 +67,7 @@ public function __construct(?IdentifierInterface $identifier = null, array $conf */ public function getIdentifier(): IdentifierInterface { - if ($this->_identifier === null) { + if (!$this->_identifier instanceof IdentifierInterface) { throw new RuntimeException( sprintf( 'Identifier is required for `%s`. Please provide an identifier instance.', diff --git a/src/Authenticator/AuthenticationRequiredException.php b/src/Authenticator/AuthenticationRequiredException.php index 42901481..78d1aabd 100644 --- a/src/Authenticator/AuthenticationRequiredException.php +++ b/src/Authenticator/AuthenticationRequiredException.php @@ -32,9 +32,6 @@ class AuthenticationRequiredException extends HttpException */ protected array $headers = []; - /** - * @var string - */ protected string $body = ''; /** diff --git a/src/Authenticator/CookieAuthenticator.php b/src/Authenticator/CookieAuthenticator.php index 73d5977f..f53e4f57 100644 --- a/src/Authenticator/CookieAuthenticator.php +++ b/src/Authenticator/CookieAuthenticator.php @@ -66,7 +66,7 @@ class CookieAuthenticator extends AbstractAuthenticator implements PersistenceIn */ public function getIdentifier(): IdentifierInterface { - if ($this->_identifier === null) { + if (!$this->_identifier instanceof IdentifierInterface) { $identifierConfig = []; if ($this->getConfig('fields')) { $identifierConfig['fields'] = $this->getConfig('fields'); @@ -90,11 +90,7 @@ public function authenticate(ServerRequestInterface $request): ResultInterface ]); } - if (is_array($cookies[$cookieName])) { - $token = $cookies[$cookieName]; - } else { - $token = json_decode($cookies[$cookieName], true); - } + $token = is_array($cookies[$cookieName]) ? $cookies[$cookieName] : json_decode((string)$cookies[$cookieName], true); if ($token === null || count($token) !== 2) { return new Result(null, Result::FAILURE_CREDENTIALS_INVALID, [ diff --git a/src/Authenticator/EnvironmentAuthenticator.php b/src/Authenticator/EnvironmentAuthenticator.php index 95f7ca82..14b4db92 100644 --- a/src/Authenticator/EnvironmentAuthenticator.php +++ b/src/Authenticator/EnvironmentAuthenticator.php @@ -120,15 +120,11 @@ protected function _buildLoginUrlErrorResult(ServerRequestInterface $request): R $uri = $request->getUri(); $base = $request->getAttribute('base'); if ($base !== null) { - $uri = $uri->withPath((string)$base . $uri->getPath()); + $uri = $uri->withPath($base . $uri->getPath()); } $checkFullUrl = $this->getConfig('urlChecker.checkFullUrl', false); - if ($checkFullUrl) { - $uri = (string)$uri; - } else { - $uri = $uri->getPath(); - } + $uri = $checkFullUrl ? (string)$uri : $uri->getPath(); $loginUrls = (array)$this->getConfig('loginUrl'); foreach ($loginUrls as $key => $loginUrl) { diff --git a/src/Authenticator/FormAuthenticator.php b/src/Authenticator/FormAuthenticator.php index 4a36cf71..eb0960af 100644 --- a/src/Authenticator/FormAuthenticator.php +++ b/src/Authenticator/FormAuthenticator.php @@ -58,7 +58,7 @@ class FormAuthenticator extends AbstractAuthenticator */ public function getIdentifier(): IdentifierInterface { - if ($this->_identifier === null) { + if (!$this->_identifier instanceof IdentifierInterface) { $identifierConfig = []; if ($this->getConfig('fields')) { $identifierConfig['fields'] = $this->getConfig('fields'); @@ -109,15 +109,11 @@ protected function _buildLoginUrlErrorResult(ServerRequestInterface $request): R $uri = $request->getUri(); $base = $request->getAttribute('base'); if ($base !== null) { - $uri = $uri->withPath((string)$base . $uri->getPath()); + $uri = $uri->withPath($base . $uri->getPath()); } $checkFullUrl = $this->getConfig('urlChecker.checkFullUrl', false); - if ($checkFullUrl) { - $uri = (string)$uri; - } else { - $uri = $uri->getPath(); - } + $uri = $checkFullUrl ? (string)$uri : $uri->getPath(); $loginUrls = (array)$this->getConfig('loginUrl'); foreach ($loginUrls as $key => $loginUrl) { diff --git a/src/Authenticator/HttpBasicAuthenticator.php b/src/Authenticator/HttpBasicAuthenticator.php index f3948f10..af53cdcf 100644 --- a/src/Authenticator/HttpBasicAuthenticator.php +++ b/src/Authenticator/HttpBasicAuthenticator.php @@ -52,7 +52,7 @@ class HttpBasicAuthenticator extends AbstractAuthenticator implements StatelessI */ public function getIdentifier(): IdentifierInterface { - if ($this->_identifier === null) { + if (!$this->_identifier instanceof IdentifierInterface) { $identifierConfig = []; if ($this->getConfig('fields')) { $identifierConfig['fields'] = $this->getConfig('fields'); diff --git a/src/Authenticator/HttpDigestAuthenticator.php b/src/Authenticator/HttpDigestAuthenticator.php index ab4fb60e..f70d5328 100644 --- a/src/Authenticator/HttpDigestAuthenticator.php +++ b/src/Authenticator/HttpDigestAuthenticator.php @@ -76,7 +76,7 @@ public function __construct(?IdentifierInterface $identifier, array $config = [] parent::__construct($identifier, $config); $secret = $this->getConfig('secret'); - if (!is_string($secret) || strlen($secret) === 0) { + if (!is_string($secret) || $secret === '') { throw new InvalidArgumentException('Secret key must be a non-empty string.'); } } @@ -134,8 +134,8 @@ protected function _getDigest(ServerRequestInterface $request): ?array $digest = empty($server['PHP_AUTH_DIGEST']) ? null : $server['PHP_AUTH_DIGEST']; if (!$digest && function_exists('apache_request_headers')) { $headers = apache_request_headers(); - if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) === 'Digest ') { - $digest = substr($headers['Authorization'], 7); + if (!empty($headers['Authorization']) && str_starts_with((string)$headers['Authorization'], 'Digest ')) { + $digest = substr((string)$headers['Authorization'], 7); } } if (!$digest) { @@ -153,7 +153,7 @@ protected function _getDigest(ServerRequestInterface $request): ?array */ public function parseAuthData(string $digest): ?array { - if (substr($digest, 0, 7) === 'Digest ') { + if (str_starts_with($digest, 'Digest ')) { $digest = substr($digest, 7); } $keys = $match = []; @@ -217,7 +217,7 @@ protected function loginHeaders(ServerRequestInterface $request): array 'realm' => $realm, 'qop' => $this->_config['qop'], 'nonce' => $this->generateNonce(), - 'opaque' => $this->_config['opaque'] ?: md5($realm), + 'opaque' => $this->_config['opaque'] ?: md5((string)$realm), ]; $digest = $this->_getDigest($request); @@ -247,7 +247,7 @@ protected function generateNonce(): string { $expiryTime = microtime(true) + $this->getConfig('nonceLifetime'); $secret = $this->getConfig('secret'); - $signatureValue = hash_hmac('sha1', $expiryTime . ':' . $secret, $secret); + $signatureValue = hash_hmac('sha1', $expiryTime . ':' . $secret, (string)$secret); $nonceValue = $expiryTime . ':' . $signatureValue; return base64_encode($nonceValue); @@ -275,7 +275,7 @@ protected function validNonce(string $nonce): bool return false; } $secret = $this->getConfig('secret'); - $check = hash_hmac('sha1', $expires . ':' . $secret, $secret); + $check = hash_hmac('sha1', $expires . ':' . $secret, (string)$secret); return hash_equals($check, $checksum); } diff --git a/src/Authenticator/JwtAuthenticator.php b/src/Authenticator/JwtAuthenticator.php index 56b0e8d9..b96b3f4f 100644 --- a/src/Authenticator/JwtAuthenticator.php +++ b/src/Authenticator/JwtAuthenticator.php @@ -47,8 +47,6 @@ class JwtAuthenticator extends TokenAuthenticator /** * Payload data. - * - * @var object|null */ protected ?object $payload = null; @@ -138,7 +136,7 @@ public function authenticate(ServerRequestInterface $request): ResultInterface */ public function getPayload(?ServerRequestInterface $request = null): ?object { - if (!$request) { + if (!$request instanceof ServerRequestInterface) { return $this->payload; } diff --git a/src/Authenticator/PrimaryKeySessionAuthenticator.php b/src/Authenticator/PrimaryKeySessionAuthenticator.php index f35733eb..78614ae2 100644 --- a/src/Authenticator/PrimaryKeySessionAuthenticator.php +++ b/src/Authenticator/PrimaryKeySessionAuthenticator.php @@ -68,7 +68,7 @@ class PrimaryKeySessionAuthenticator extends SessionAuthenticator */ public function getIdentifier(): IdentifierInterface { - if ($this->_identifier === null) { + if (!$this->_identifier instanceof IdentifierInterface) { $this->_identifier = IdentifierFactory::create([ 'className' => 'Authentication.Token', 'tokenField' => $this->getConfig('idField'), diff --git a/src/Authenticator/Result.php b/src/Authenticator/Result.php index edf7ebff..02e029c9 100644 --- a/src/Authenticator/Result.php +++ b/src/Authenticator/Result.php @@ -26,15 +26,11 @@ class Result implements ResultInterface { /** * Authentication result status - * - * @var string */ protected string $_status; /** * The identity data used in the authentication attempt - * - * @var \ArrayAccess|array|null */ protected ArrayAccess|array|null $_data = null; @@ -42,8 +38,6 @@ class Result implements ResultInterface * An array of string reasons why the authentication attempt was unsuccessful * * If authentication was successful, this should be an empty array. - * - * @var array */ protected array $_errors = []; diff --git a/src/Controller/Component/AuthenticationComponent.php b/src/Controller/Component/AuthenticationComponent.php index 7cdcf335..a631927b 100644 --- a/src/Controller/Component/AuthenticationComponent.php +++ b/src/Controller/Component/AuthenticationComponent.php @@ -19,6 +19,7 @@ use ArrayAccess; use ArrayObject; use Authentication\AuthenticationServiceInterface; +use Authentication\Authenticator\AuthenticatorInterface; use Authentication\Authenticator\ImpersonationInterface; use Authentication\Authenticator\PersistenceInterface; use Authentication\Authenticator\ResultInterface; @@ -75,8 +76,6 @@ class AuthenticationComponent extends Component implements EventDispatcherInterf /** * Authentication service instance. - * - * @var \Authentication\AuthenticationServiceInterface|null */ protected ?AuthenticationServiceInterface $_authentication = null; @@ -103,7 +102,7 @@ public function beforeFilter(): void $provider = $authentication->getAuthenticationProvider(); if ( - $provider !== null && + $provider instanceof AuthenticatorInterface && !$provider instanceof PersistenceInterface && !$provider instanceof StatelessInterface ) { @@ -141,7 +140,7 @@ public function startup(): void */ public function getAuthenticationService(): AuthenticationServiceInterface { - if ($this->_authentication !== null) { + if ($this->_authentication instanceof AuthenticationServiceInterface) { return $this->_authentication; } @@ -269,9 +268,8 @@ public function getIdentifier(): array|string|int|null public function getIdentity(): ?IdentityInterface { $controller = $this->getController(); - $identity = $controller->getRequest()->getAttribute($this->getConfig('identityAttribute')); - return $identity; + return $controller->getRequest()->getAttribute($this->getConfig('identityAttribute')); } /** @@ -285,7 +283,7 @@ public function getIdentityData(string $path): mixed { $identity = $this->getIdentity(); - if ($identity === null) { + if (!$identity instanceof IdentityInterface) { throw new RuntimeException('The identity has not been found.'); } @@ -398,7 +396,7 @@ public function impersonate(ArrayAccess $impersonated) $service = $this->getImpersonationAuthenticationService(); $identity = $this->getIdentity(); - if (!$identity) { + if (!$identity instanceof IdentityInterface) { throw new UnauthenticatedException('You must be logged in before impersonating a user.'); } $impersonator = $identity->getOriginalData(); @@ -462,7 +460,7 @@ public function stopImpersonating() */ public function isImpersonating(): bool { - if (!$this->getIdentity()) { + if (!$this->getIdentity() instanceof IdentityInterface) { return false; } @@ -485,9 +483,9 @@ protected function getImpersonationAuthenticationService(): ImpersonationInterfa { $service = $this->getAuthenticationService(); if (!($service instanceof ImpersonationInterface)) { - $className = get_class($service); + $className = $service::class; throw new InvalidArgumentException( - "The {$className} must implement ImpersonationInterface in order to use impersonation.", + sprintf('The %s must implement ImpersonationInterface in order to use impersonation.', $className), ); } diff --git a/src/Identifier/Ldap/ExtensionAdapter.php b/src/Identifier/Ldap/ExtensionAdapter.php index fae1da54..963f86a7 100644 --- a/src/Identifier/Ldap/ExtensionAdapter.php +++ b/src/Identifier/Ldap/ExtensionAdapter.php @@ -32,8 +32,6 @@ class ExtensionAdapter implements AdapterInterface { /** * LDAP Object - * - * @var \LDAP\Connection|null */ protected ?Connection $_connection = null; @@ -77,7 +75,7 @@ public function bind(string $bind, string $password): bool */ public function getConnection(): Connection { - if ($this->_connection === null) { + if (!$this->_connection instanceof Connection) { throw new RuntimeException('You are not connected to a LDAP server.'); } @@ -95,15 +93,13 @@ public function getConnection(): Connection public function connect(string $host, int $port, array $options): void { $this->_setErrorHandler(); - $resource = ldap_connect("{$host}:{$port}"); + $resource = ldap_connect(sprintf('%s:%d', $host, $port)); if ($resource === false) { throw new RuntimeException('Unable to connect to LDAP server.'); } - if (isset($options['tls']) && $options['tls']) { - //convert the connection to TLS - if (!ldap_start_tls($resource)) { - throw new RuntimeException('Starting TLS failed on connection to LDAP server.'); - } + //convert the connection to TLS + if (isset($options['tls']) && $options['tls'] && !ldap_start_tls($resource)) { + throw new RuntimeException('Starting TLS failed on connection to LDAP server.'); } unset($options['tls']); //don't pass through to PHP LDAP functions $this->_connection = $resource; @@ -160,7 +156,7 @@ public function getDiagnosticMessage(): ?string */ public function unbind(): void { - if ($this->_connection === null) { + if (!$this->_connection instanceof Connection) { return; } diff --git a/src/Identifier/LdapIdentifier.php b/src/Identifier/LdapIdentifier.php index 3237823b..5ae3a19d 100644 --- a/src/Identifier/LdapIdentifier.php +++ b/src/Identifier/LdapIdentifier.php @@ -76,8 +76,6 @@ class LdapIdentifier extends AbstractIdentifier /** * LDAP connection object - * - * @var \Authentication\Identifier\Ldap\AdapterInterface */ protected AdapterInterface $_ldap; @@ -202,7 +200,7 @@ protected function _bindUser(string $username, string $password): ?ArrayAccess $config = $this->getConfig(); try { $ldapBind = $this->_ldap->bind($config['bindDN']($username), $password); - if ($ldapBind === true) { + if ($ldapBind) { $this->_ldap->unbind(); return new ArrayObject([ diff --git a/src/Identifier/PasswordIdentifier.php b/src/Identifier/PasswordIdentifier.php index 1a6475b2..9bbe3c7f 100644 --- a/src/Identifier/PasswordIdentifier.php +++ b/src/Identifier/PasswordIdentifier.php @@ -79,7 +79,7 @@ class PasswordIdentifier extends AbstractIdentifier */ public function getPasswordHasher(): PasswordHasherInterface { - if ($this->_passwordHasher === null) { + if (!$this->_passwordHasher instanceof PasswordHasherInterface) { $passwordHasher = $this->getConfig('passwordHasher'); if ($passwordHasher !== null) { $passwordHasher = PasswordHasherFactory::build($passwordHasher); diff --git a/src/Identifier/Resolver/OrmResolver.php b/src/Identifier/Resolver/OrmResolver.php index 07351ffc..5baad800 100644 --- a/src/Identifier/Resolver/OrmResolver.php +++ b/src/Identifier/Resolver/OrmResolver.php @@ -71,7 +71,7 @@ public function find(array $conditions, string $type = self::TYPE_AND): ArrayAcc foreach ($conditions as $field => $value) { $field = $table->aliasField($field); if (is_array($value)) { - $field = $field . ' IN'; + $field .= ' IN'; } $where[$field] = $value; } diff --git a/src/Identifier/Resolver/ResolverAwareTrait.php b/src/Identifier/Resolver/ResolverAwareTrait.php index 7997d7bf..89e5e634 100644 --- a/src/Identifier/Resolver/ResolverAwareTrait.php +++ b/src/Identifier/Resolver/ResolverAwareTrait.php @@ -24,8 +24,6 @@ trait ResolverAwareTrait { /** * Resolver instance. - * - * @var \Authentication\Identifier\Resolver\ResolverInterface|null */ protected ?ResolverInterface $resolver = null; diff --git a/src/Identifier/Resolver/ResolverInterface.php b/src/Identifier/Resolver/ResolverInterface.php index ce111af1..9a8f147c 100644 --- a/src/Identifier/Resolver/ResolverInterface.php +++ b/src/Identifier/Resolver/ResolverInterface.php @@ -21,6 +21,7 @@ interface ResolverInterface { public const TYPE_OR = 'OR'; + public const TYPE_AND = 'AND'; /** diff --git a/src/Identity.php b/src/Identity.php index 3ecefa59..1ea1c47c 100644 --- a/src/Identity.php +++ b/src/Identity.php @@ -32,8 +32,6 @@ class Identity implements IdentityInterface * Default configuration. * * - `fieldMap` Mapping of fields - * - * @var array */ protected array $_defaultConfig = [ 'fieldMap' => [ diff --git a/src/Middleware/AuthenticationMiddleware.php b/src/Middleware/AuthenticationMiddleware.php index 945af355..46d1870f 100644 --- a/src/Middleware/AuthenticationMiddleware.php +++ b/src/Middleware/AuthenticationMiddleware.php @@ -20,6 +20,7 @@ use Authentication\AuthenticationServiceInterface; use Authentication\AuthenticationServiceProviderInterface; use Authentication\Authenticator\AuthenticationRequiredException; +use Authentication\Authenticator\AuthenticatorInterface; use Authentication\Authenticator\StatelessInterface; use Authentication\Authenticator\UnauthenticatedException; use Cake\Core\ContainerApplicationInterface; @@ -39,15 +40,11 @@ class AuthenticationMiddleware implements MiddlewareInterface { /** * Authentication service or application instance. - * - * @var \Authentication\AuthenticationServiceInterface|\Authentication\AuthenticationServiceProviderInterface */ protected AuthenticationServiceInterface|AuthenticationServiceProviderInterface $subject; /** * The container instance from the application - * - * @var \Cake\Core\ContainerInterface|null */ protected ?ContainerInterface $container; @@ -106,7 +103,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface $response = $handler->handle($request); $authenticator = $service->getAuthenticationProvider(); - if ($authenticator !== null && !$authenticator instanceof StatelessInterface && $result->getData()) { + if ($authenticator instanceof AuthenticatorInterface && !$authenticator instanceof StatelessInterface && $result->getData()) { $return = $service->persistIdentity($request, $response, $result->getData()); $response = $return['response']; } @@ -133,7 +130,7 @@ protected function getAuthenticationService(ServerRequestInterface $request): Au $subject = $this->subject; if ($subject instanceof AuthenticationServiceProviderInterface) { - $subject = $subject->getAuthenticationService($request); + return $subject->getAuthenticationService($request); } return $subject; diff --git a/src/PasswordHasher/AbstractPasswordHasher.php b/src/PasswordHasher/AbstractPasswordHasher.php index f9fbed94..4dd4272b 100644 --- a/src/PasswordHasher/AbstractPasswordHasher.php +++ b/src/PasswordHasher/AbstractPasswordHasher.php @@ -28,8 +28,6 @@ abstract class AbstractPasswordHasher implements PasswordHasherInterface * Default config * * These are merged with user-provided config when the object is used. - * - * @var array */ protected array $_defaultConfig = []; diff --git a/src/PasswordHasher/DefaultPasswordHasher.php b/src/PasswordHasher/DefaultPasswordHasher.php index 0ec08354..973d2233 100644 --- a/src/PasswordHasher/DefaultPasswordHasher.php +++ b/src/PasswordHasher/DefaultPasswordHasher.php @@ -29,8 +29,6 @@ class DefaultPasswordHasher extends AbstractPasswordHasher * argument of `password_hash()`. Defaults to `PASSWORD_DEFAULT` * - `hashOptions` - Associative array of options. Check the PHP manual for * supported options for each hash type. Defaults to empty array. - * - * @var array */ protected array $_defaultConfig = [ 'hashType' => PASSWORD_DEFAULT, diff --git a/src/PasswordHasher/FallbackPasswordHasher.php b/src/PasswordHasher/FallbackPasswordHasher.php index 6aee5378..dbfd4d6d 100644 --- a/src/PasswordHasher/FallbackPasswordHasher.php +++ b/src/PasswordHasher/FallbackPasswordHasher.php @@ -24,8 +24,6 @@ class FallbackPasswordHasher extends AbstractPasswordHasher { /** * Default config for this object. - * - * @var array */ protected array $_defaultConfig = [ 'hashers' => [], @@ -33,8 +31,6 @@ class FallbackPasswordHasher extends AbstractPasswordHasher /** * Holds the list of password hasher objects that will be used - * - * @var array */ protected array $_hashers = []; diff --git a/src/PasswordHasher/LegacyPasswordHasher.php b/src/PasswordHasher/LegacyPasswordHasher.php index 04a86fe0..718d713c 100644 --- a/src/PasswordHasher/LegacyPasswordHasher.php +++ b/src/PasswordHasher/LegacyPasswordHasher.php @@ -31,8 +31,6 @@ class LegacyPasswordHasher extends AbstractPasswordHasher * Default config for this object. * - `hashType` String identifier of the hash type to use on the password. (e.g 'sha256' or 'md5') * - `salt` Boolean flag for salting the password in a hash, or check. - * - * @var array */ protected array $_defaultConfig = [ 'hashType' => null, diff --git a/src/PasswordHasher/PasswordHasherTrait.php b/src/PasswordHasher/PasswordHasherTrait.php index f18c435d..b62b703d 100644 --- a/src/PasswordHasher/PasswordHasherTrait.php +++ b/src/PasswordHasher/PasswordHasherTrait.php @@ -7,16 +7,12 @@ trait PasswordHasherTrait { /** * Password hasher instance. - * - * @var \Authentication\PasswordHasher\PasswordHasherInterface|null */ protected ?PasswordHasherInterface $_passwordHasher = null; /** * Whether the user authenticated by this class * requires their password to be rehashed with another algorithm. - * - * @var bool */ protected bool $_needsPasswordRehash = false; diff --git a/src/UrlChecker/MultiUrlChecker.php b/src/UrlChecker/MultiUrlChecker.php index ea525fdd..a458f5e6 100644 --- a/src/UrlChecker/MultiUrlChecker.php +++ b/src/UrlChecker/MultiUrlChecker.php @@ -47,11 +47,7 @@ public function check(ServerRequestInterface $request, array|string $loginUrls, $options = $this->_mergeDefaultOptions($options); // For a single URL (string or array route), convert to array - if (is_string($loginUrls) || $this->_isSingleRoute($loginUrls)) { - $urls = [$loginUrls]; - } else { - $urls = $loginUrls; - } + $urls = is_string($loginUrls) || $this->_isSingleRoute($loginUrls) ? [$loginUrls] : $loginUrls; if (!$urls) { return true; @@ -81,11 +77,7 @@ protected function _isSingleRoute(array|string $value): bool if (!$value) { return false; } - - // A single route has string keys like ['controller' => 'Users'] - // An array of routes has numeric keys [0 => '/login', 1 => '/signin'] - reset($value); - $firstKey = key($value); + $firstKey = array_key_first($value); return !is_int($firstKey); } diff --git a/src/UrlChecker/StringUrlChecker.php b/src/UrlChecker/StringUrlChecker.php index 15f3ac9c..26026c88 100644 --- a/src/UrlChecker/StringUrlChecker.php +++ b/src/UrlChecker/StringUrlChecker.php @@ -82,7 +82,7 @@ protected function _getChecker(array $options): callable return 'preg_match'; } - return function ($validUrl, $url) { + return function ($validUrl, $url): bool { return $validUrl === $url; }; } diff --git a/src/View/Helper/IdentityHelper.php b/src/View/Helper/IdentityHelper.php index 88da0cd7..89f8ca05 100644 --- a/src/View/Helper/IdentityHelper.php +++ b/src/View/Helper/IdentityHelper.php @@ -39,8 +39,6 @@ class IdentityHelper extends Helper /** * Identity Object - * - * @var \Authentication\IdentityInterface|null */ protected ?IdentityInterface $_identity = null; @@ -64,7 +62,7 @@ public function initialize(array $config): void */ public function getId(): array|string|int|null { - if ($this->_identity === null) { + if (!$this->_identity instanceof IdentityInterface) { return null; } @@ -78,7 +76,7 @@ public function getId(): array|string|int|null */ public function isLoggedIn(): bool { - return $this->_identity !== null; + return $this->_identity instanceof IdentityInterface; } /** @@ -114,7 +112,7 @@ public function is(int|string $id, string $field = 'id'): bool */ public function get(?string $key = null): mixed { - if ($this->_identity === null) { + if (!$this->_identity instanceof IdentityInterface) { return null; } diff --git a/tests/TestCase/AuthenticationServiceTest.php b/tests/TestCase/AuthenticationServiceTest.php index 479d70e6..90a193ba 100644 --- a/tests/TestCase/AuthenticationServiceTest.php +++ b/tests/TestCase/AuthenticationServiceTest.php @@ -46,7 +46,7 @@ class AuthenticationServiceTest extends TestCase * * @return void */ - public function testAuthenticateDeprecated() + public function testAuthenticateDeprecated(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -78,7 +78,7 @@ public function testAuthenticateDeprecated() * * @return void */ - public function testAuthenticate() + public function testAuthenticate(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -110,7 +110,7 @@ public function testAuthenticate() * * @return void */ - public function testAuthenticateWithChallenge() + public function testAuthenticateWithChallenge(): void { $request = ServerRequestFactory::fromGlobals([ 'SERVER_NAME' => 'example.com', @@ -143,7 +143,7 @@ public function testAuthenticateWithChallenge() * * @return void */ - public function testAuthenticateWithChallengeDisabled() + public function testAuthenticateWithChallengeDisabled(): void { $request = ServerRequestFactory::fromGlobals([ 'SERVER_NAME' => 'example.com', @@ -168,7 +168,7 @@ public function testAuthenticateWithChallengeDisabled() /** * testLoadAuthenticatorException */ - public function testLoadAuthenticatorException() + public function testLoadAuthenticatorException(): void { $this->expectException('RuntimeException'); $service = new AuthenticationService(); @@ -180,7 +180,7 @@ public function testLoadAuthenticatorException() * * @return void */ - public function testClearIdentity() + public function testClearIdentity(): void { $service = new AuthenticationService([ 'authenticators' => [ @@ -209,7 +209,7 @@ public function testClearIdentity() * * @return void */ - public function testClearIdentityWithCustomIdentityAttribute() + public function testClearIdentityWithCustomIdentityAttribute(): void { $service = new AuthenticationService([ 'authenticators' => [ @@ -239,7 +239,7 @@ public function testClearIdentityWithCustomIdentityAttribute() * * @return void */ - public function testClearIdentityWithCustomIdentityAttributeShouldPreserveDefault() + public function testClearIdentityWithCustomIdentityAttributeShouldPreserveDefault(): void { $service = new AuthenticationService([ 'authenticators' => [ @@ -274,7 +274,7 @@ public function testClearIdentityWithCustomIdentityAttributeShouldPreserveDefaul * * @return void */ - public function testClearIdentityWithImpersonation() + public function testClearIdentityWithImpersonation(): void { $service = new AuthenticationService([ 'authenticators' => [ @@ -307,7 +307,7 @@ public function testClearIdentityWithImpersonation() * * @return void */ - public function testPersistIdentity() + public function testPersistIdentity(): void { $service = new AuthenticationService([ 'authenticators' => [ @@ -352,7 +352,7 @@ public function testPersistIdentity() * * @return void */ - public function testPersistIdentityWithCustomIdentityAttribute() + public function testPersistIdentityWithCustomIdentityAttribute(): void { $service = new AuthenticationService([ 'authenticators' => [ @@ -400,7 +400,7 @@ public function testPersistIdentityWithCustomIdentityAttribute() * * @return void */ - public function testPersistIdentityWithCustomIdentityAttributeShouldPreserveDefault() + public function testPersistIdentityWithCustomIdentityAttributeShouldPreserveDefault(): void { $service = new AuthenticationService([ 'authenticators' => [ @@ -451,7 +451,7 @@ public function testPersistIdentityWithCustomIdentityAttributeShouldPreserveDefa * * @return void */ - public function testPersistIdentityInterface() + public function testPersistIdentityInterface(): void { $request = new ServerRequest(); $response = new Response(); @@ -469,7 +469,7 @@ public function testPersistIdentityInterface() * * @return void */ - public function testPersistIdentityArray() + public function testPersistIdentityArray(): void { $request = new ServerRequest(); $response = new Response(); @@ -492,7 +492,7 @@ public function testPersistIdentityArray() * * @return void */ - public function testPersistIdentityInstance() + public function testPersistIdentityInstance(): void { $request = new ServerRequest(); $response = new Response(); @@ -510,7 +510,7 @@ public function testPersistIdentityInstance() * * @return void */ - public function testGetResult() + public function testGetResult(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -542,7 +542,7 @@ public function testGetResult() * * @return void */ - public function testNoAuthenticatorsLoadedException() + public function testNoAuthenticatorsLoadedException(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('No authenticators loaded. You need to load at least one authenticator.'); @@ -562,7 +562,7 @@ public function testNoAuthenticatorsLoadedException() * * @return void */ - public function testBuildIdentity() + public function testBuildIdentity(): void { $service = new AuthenticationService([ 'identifiers' => [ @@ -578,7 +578,7 @@ public function testBuildIdentity() * * @return void */ - public function testBuildIdentityWithInstance() + public function testBuildIdentityWithInstance(): void { $service = new AuthenticationService([ 'identifiers' => [ @@ -597,7 +597,7 @@ public function testBuildIdentityWithInstance() * * @return void */ - public function testBuildIdentityRuntimeException() + public function testBuildIdentityRuntimeException(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Object `stdClass` does not implement `Authentication\IdentityInterface`'); @@ -616,7 +616,7 @@ public function testBuildIdentityRuntimeException() * * @return void */ - public function testCallableIdentityProvider() + public function testCallableIdentityProvider(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -624,7 +624,7 @@ public function testCallableIdentityProvider() ['username' => 'mariano', 'password' => 'password'], ); - $callable = function () { + $callable = function (): Identity { return new Identity(new ArrayObject([ 'id' => 'by-callable', ])); @@ -650,7 +650,7 @@ public function testCallableIdentityProvider() * * @return void */ - public function testGetIdentity() + public function testGetIdentity(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -681,7 +681,7 @@ public function testGetIdentity() * * @return void */ - public function testGetIdentityInterface() + public function testGetIdentityInterface(): void { $request = new ServerRequest(); @@ -705,7 +705,7 @@ public function testGetIdentityInterface() * * @return void */ - public function testGetIdentityNull() + public function testGetIdentityNull(): void { $request = new ServerRequest(); @@ -723,13 +723,13 @@ public function testGetIdentityNull() $this->assertNull($service->getIdentity()); } - public function testGetIdentityAttribute() + public function testGetIdentityAttribute(): void { $service = new AuthenticationService(['identityAttribute' => 'user']); $this->assertSame('user', $service->getIdentityAttribute()); } - public function testGetUnauthenticatedRedirectUrlNoValues() + public function testGetUnauthenticatedRedirectUrlNoValues(): void { $service = new AuthenticationService(); $request = new ServerRequest(); @@ -737,7 +737,7 @@ public function testGetUnauthenticatedRedirectUrlNoValues() $this->assertNull($service->getUnauthenticatedRedirectUrl($request)); } - public function testGetUnauthenticatedRedirectUrl() + public function testGetUnauthenticatedRedirectUrl(): void { $service = new AuthenticationService(); $request = ServerRequestFactory::fromGlobals( @@ -765,7 +765,7 @@ public function testGetUnauthenticatedRedirectUrl() ); } - public function testGetUnauthenticatedRedirectUrlForPost() + public function testGetUnauthenticatedRedirectUrlForPost(): void { $service = new AuthenticationService(); $service->setConfig('unauthenticatedRedirect', '/users/login'); @@ -781,7 +781,7 @@ public function testGetUnauthenticatedRedirectUrlForPost() ); } - public function testGetUnauthenticatedRedirectUrlAsArray() + public function testGetUnauthenticatedRedirectUrlAsArray(): void { Router::fullBaseUrl('http://localhost'); @@ -805,7 +805,7 @@ public function testGetUnauthenticatedRedirectUrlAsArray() $this->assertSame('/login', $service->getUnauthenticatedRedirectUrl($request)); } - public function testGetUnauthenticatedRedirectUrlWithBasePath() + public function testGetUnauthenticatedRedirectUrlWithBasePath(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/secrets'], @@ -822,7 +822,7 @@ public function testGetUnauthenticatedRedirectUrlWithBasePath() ); } - public function testGetLoginRedirect() + public function testGetLoginRedirect(): void { $service = new AuthenticationService([ 'unauthenticatedRedirect' => '/users/login', @@ -870,7 +870,7 @@ public function testGetLoginRedirect() * * @return void */ - public function testGetLoginRedirectValidationDisabled() + public function testGetLoginRedirectValidationDisabled(): void { $service = new AuthenticationService([ 'unauthenticatedRedirect' => '/users/login', @@ -896,7 +896,7 @@ public function testGetLoginRedirectValidationDisabled() * * @return void */ - public function testGetLoginRedirectValidationNestedRedirects() + public function testGetLoginRedirectValidationNestedRedirects(): void { $service = new AuthenticationService([ 'unauthenticatedRedirect' => '/users/login', @@ -936,7 +936,7 @@ public function testGetLoginRedirectValidationNestedRedirects() * * @return void */ - public function testGetLoginRedirectValidationEncodingLevels() + public function testGetLoginRedirectValidationEncodingLevels(): void { $service = new AuthenticationService([ 'unauthenticatedRedirect' => '/users/login', @@ -969,7 +969,7 @@ public function testGetLoginRedirectValidationEncodingLevels() * * @return void */ - public function testGetLoginRedirectValidationMaxLength() + public function testGetLoginRedirectValidationMaxLength(): void { $service = new AuthenticationService([ 'unauthenticatedRedirect' => '/users/login', @@ -1004,7 +1004,7 @@ public function testGetLoginRedirectValidationMaxLength() * * @return void */ - public function testGetLoginRedirectValidationWithQueryParameters() + public function testGetLoginRedirectValidationWithQueryParameters(): void { $service = new AuthenticationService([ 'unauthenticatedRedirect' => '/users/login', @@ -1030,7 +1030,7 @@ public function testGetLoginRedirectValidationWithQueryParameters() * * @return void */ - public function testImpersonate() + public function testImpersonate(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -1050,6 +1050,7 @@ public function testImpersonate() ], ]); $service->authenticate($request); + $result = $service->impersonate($request, $response, $impersonator, $impersonated); $this->assertIsArray($result); $this->assertArrayHasKey('request', $result); @@ -1065,7 +1066,7 @@ public function testImpersonate() * * @return void */ - public function testImpersonateAlreadyImpersonating() + public function testImpersonateAlreadyImpersonating(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -1096,7 +1097,7 @@ public function testImpersonateAlreadyImpersonating() * * @return void */ - public function testImpersonateWrongProvider() + public function testImpersonateWrongProvider(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -1125,7 +1126,7 @@ public function testImpersonateWrongProvider() * * @return void */ - public function testStopImpersonating() + public function testStopImpersonating(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -1146,6 +1147,7 @@ public function testStopImpersonating() ], ]); $service->authenticate($request); + $result = $service->stopImpersonating($request, $response); $this->assertIsArray($result); $this->assertArrayHasKey('request', $result); @@ -1161,7 +1163,7 @@ public function testStopImpersonating() * * @return void */ - public function testStopImpersonatingWrongProvider() + public function testStopImpersonatingWrongProvider(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -1189,7 +1191,7 @@ public function testStopImpersonatingWrongProvider() * * @return void */ - public function testIsImpersonatingImpersonating() + public function testIsImpersonatingImpersonating(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -1218,7 +1220,7 @@ public function testIsImpersonatingImpersonating() * * @return void */ - public function testIsImpersonatingNotImpersonating() + public function testIsImpersonatingNotImpersonating(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -1236,6 +1238,7 @@ public function testIsImpersonatingNotImpersonating() ], ]); $service->authenticate($request); + $result = $service->isImpersonating($request); $this->assertFalse($result); } @@ -1245,7 +1248,7 @@ public function testIsImpersonatingNotImpersonating() * * @return void */ - public function testIsImpersonatingWrongProvider() + public function testIsImpersonatingWrongProvider(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -1272,7 +1275,7 @@ public function testIsImpersonatingWrongProvider() * * @return void */ - public function testFormAuthenticatorDefaultIdentifier() + public function testFormAuthenticatorDefaultIdentifier(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], diff --git a/tests/TestCase/AuthenticationTestCase.php b/tests/TestCase/AuthenticationTestCase.php index 28e8bc52..d383548a 100644 --- a/tests/TestCase/AuthenticationTestCase.php +++ b/tests/TestCase/AuthenticationTestCase.php @@ -18,13 +18,12 @@ use Cake\ORM\TableRegistry; use Cake\TestSuite\TestCase; +use TestApp\Model\Table\AuthUsersTable; class AuthenticationTestCase extends TestCase { /** * Fixtures - * - * @var array */ protected array $fixtures = [ 'core.AuthUsers', @@ -34,7 +33,7 @@ class AuthenticationTestCase extends TestCase /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->_setupUsersAndPasswords(); @@ -54,7 +53,7 @@ protected function _setupUsersAndPasswords() $Users->updateAll(['password' => $password], []); $AuthUsers = TableRegistry::getTableLocator()->get('AuthUsers', [ - 'className' => 'TestApp\Model\Table\AuthUsersTable', + 'className' => AuthUsersTable::class, ]); $AuthUsers->updateAll(['password' => $password], []); } diff --git a/tests/TestCase/Authenticator/AbstractAuthenticatorTest.php b/tests/TestCase/Authenticator/AbstractAuthenticatorTest.php index e0fc2831..4da74049 100644 --- a/tests/TestCase/Authenticator/AbstractAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/AbstractAuthenticatorTest.php @@ -31,7 +31,7 @@ class AbstractAuthenticatorTest extends TestCase * * @return void */ - public function testGetIdentifier() + public function testGetIdentifier(): void { $identifier = $this->createMock(IdentifierInterface::class); $authenticator = new class ($identifier) extends AbstractAuthenticator { @@ -49,7 +49,7 @@ public function authenticate($request): Result * * @return void */ - public function testSetIdentifier() + public function testSetIdentifier(): void { $identifier = $this->createMock(IdentifierInterface::class); $authenticator = new class ($identifier) extends AbstractAuthenticator { diff --git a/tests/TestCase/Authenticator/AuthenticatorCollectionTest.php b/tests/TestCase/Authenticator/AuthenticatorCollectionTest.php index 96d23e0b..d1c7cf6f 100644 --- a/tests/TestCase/Authenticator/AuthenticatorCollectionTest.php +++ b/tests/TestCase/Authenticator/AuthenticatorCollectionTest.php @@ -30,7 +30,7 @@ class AuthenticatorCollectionTest extends TestCase * * @return void */ - public function testConstruct() + public function testConstruct(): void { $collection = new AuthenticatorCollection([ 'Authentication.Form' => [ @@ -46,7 +46,7 @@ public function testConstruct() * * @return void */ - public function testLoad() + public function testLoad(): void { $collection = new AuthenticatorCollection(); $result = $collection->load('Authentication.Form', [ @@ -60,7 +60,7 @@ public function testLoad() * * @return void */ - public function testSet() + public function testSet(): void { $authenticator = $this->createMock(AuthenticatorInterface::class); @@ -69,7 +69,7 @@ public function testSet() $this->assertSame($authenticator, $collection->get('Form')); } - public function testLoadException() + public function testLoadException(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Authenticator class `Does-not-exist` was not found.'); @@ -82,7 +82,7 @@ public function testLoadException() * * @return void */ - public function testIsEmpty() + public function testIsEmpty(): void { $collection = new AuthenticatorCollection(); $this->assertTrue($collection->isEmpty()); @@ -98,7 +98,7 @@ public function testIsEmpty() * * @return void */ - public function testIterator() + public function testIterator(): void { $authenticator = $this->createMock(AuthenticatorInterface::class); diff --git a/tests/TestCase/Authenticator/CookieAuthenticatorTest.php b/tests/TestCase/Authenticator/CookieAuthenticatorTest.php index 92cc5223..78ddc54c 100644 --- a/tests/TestCase/Authenticator/CookieAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/CookieAuthenticatorTest.php @@ -32,8 +32,6 @@ class CookieAuthenticatorTest extends TestCase { /** * Fixtures - * - * @var array */ protected array $fixtures = [ 'core.AuthUsers', @@ -43,7 +41,7 @@ class CookieAuthenticatorTest extends TestCase /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { $this->skipIf(!class_exists(Cookie::class)); @@ -57,7 +55,7 @@ public function setUp(): void * * @return void */ - public function testAuthenticateInvalidTokenMissingUsername() + public function testAuthenticateInvalidTokenMissingUsername(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -82,7 +80,7 @@ public function testAuthenticateInvalidTokenMissingUsername() * * @return void */ - public function testAuthenticateSuccess() + public function testAuthenticateSuccess(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -108,7 +106,7 @@ public function testAuthenticateSuccess() * * @return void */ - public function testAuthenticateExpandedCookie() + public function testAuthenticateExpandedCookie(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -133,7 +131,7 @@ public function testAuthenticateExpandedCookie() * * @return void */ - public function testAuthenticateNoSalt() + public function testAuthenticateNoSalt(): void { Configure::delete('Security.salt'); @@ -161,7 +159,7 @@ public function testAuthenticateNoSalt() * * @return void */ - public function testAuthenticateInvalidSalt() + public function testAuthenticateInvalidSalt(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -185,7 +183,7 @@ public function testAuthenticateInvalidSalt() * * @return void */ - public function testAuthenticateUnknownUser() + public function testAuthenticateUnknownUser(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -210,7 +208,7 @@ public function testAuthenticateUnknownUser() * * @return void */ - public function testCredentialsNotPresent() + public function testCredentialsNotPresent(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -230,7 +228,7 @@ public function testCredentialsNotPresent() * * @return void */ - public function testAuthenticateInvalidToken() + public function testAuthenticateInvalidToken(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -255,7 +253,7 @@ public function testAuthenticateInvalidToken() * * @return void */ - public function testPersistIdentity() + public function testPersistIdentity(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -329,7 +327,7 @@ public function testPersistIdentity() * * @return void */ - public function testPersistIdentityLoginUrlMismatch() + public function testPersistIdentityLoginUrlMismatch(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -365,7 +363,7 @@ public function testPersistIdentityLoginUrlMismatch() /** * @return void */ - public function testPersistIdentityInvalidConfig() + public function testPersistIdentityInvalidConfig(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -396,7 +394,7 @@ public function testPersistIdentityInvalidConfig() * * @return void */ - public function testClearIdentity() + public function testClearIdentity(): void { $identifier = IdentifierFactory::create('Authentication.Password'); diff --git a/tests/TestCase/Authenticator/EnvironmentAuthenticatorTest.php b/tests/TestCase/Authenticator/EnvironmentAuthenticatorTest.php index 16b16990..9a1bb6e1 100644 --- a/tests/TestCase/Authenticator/EnvironmentAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/EnvironmentAuthenticatorTest.php @@ -30,8 +30,6 @@ class EnvironmentAuthenticatorTest extends TestCase { /** * Fixtures - * - * @var array */ public array $fixtures = [ 'core.AuthUsers', @@ -48,7 +46,7 @@ class EnvironmentAuthenticatorTest extends TestCase /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -63,10 +61,10 @@ public function setUp(): void * * @return void */ - public function testAuthenticate() + public function testAuthenticate(): void { $identifier = IdentifierFactory::create('Authentication.Callback', [ - 'callback' => function ($data) { + 'callback' => function (array $data): ?Result { if (isset($data['USER_ID']) && isset($data['ATTRIBUTE'])) { return new Result($data, RESULT::SUCCESS); } @@ -98,7 +96,7 @@ public function testAuthenticate() * * @return void */ - public function testFailedAuthentication() + public function testFailedAuthentication(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '/secure', @@ -124,7 +122,7 @@ public function testFailedAuthentication() * * @return void */ - public function testWithoutFieldConfig() + public function testWithoutFieldConfig(): void { $envAuth = new EnvironmentAuthenticator($this->identifier); @@ -138,7 +136,7 @@ public function testWithoutFieldConfig() * * @return void */ - public function testWithIncorrectFieldConfig() + public function testWithIncorrectFieldConfig(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '/secure', @@ -164,7 +162,7 @@ public function testWithIncorrectFieldConfig() * * @return void */ - public function testCredentialsEmpty() + public function testCredentialsEmpty(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '/secure', @@ -190,10 +188,10 @@ public function testCredentialsEmpty() * * @return void */ - public function testOptionalFields() + public function testOptionalFields(): void { $identifier = IdentifierFactory::create('Authentication.Callback', [ - 'callback' => function ($data) { + 'callback' => function (array $data): ?Result { if (isset($data['USER_ID']) && isset($data['OPTIONAL_FIELD'])) { return new Result($data, RESULT::SUCCESS); } @@ -229,7 +227,7 @@ public function testOptionalFields() * * @return void */ - public function testSingleLoginUrlMismatch() + public function testSingleLoginUrlMismatch(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '/secure', @@ -256,7 +254,7 @@ public function testSingleLoginUrlMismatch() * * @return void */ - public function testMultipleLoginUrlMismatch() + public function testMultipleLoginUrlMismatch(): void { Router::createRouteBuilder('/') ->connect('/{lang}/secure', ['controller' => 'Users', 'action' => 'login']); @@ -290,7 +288,7 @@ public function testMultipleLoginUrlMismatch() * * @return void */ - public function testSingleLoginUrlSuccess() + public function testSingleLoginUrlSuccess(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '/en/secure', @@ -316,7 +314,7 @@ public function testSingleLoginUrlSuccess() * * @return void */ - public function testMultipleLoginUrlSuccess() + public function testMultipleLoginUrlSuccess(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'urlChecker' => 'Authentication.Multi', @@ -347,7 +345,7 @@ public function testMultipleLoginUrlSuccess() * * @return void */ - public function testLoginUrlSuccessWithBase() + public function testLoginUrlSuccessWithBase(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '/base/fr/secure', @@ -375,7 +373,7 @@ public function testLoginUrlSuccessWithBase() * * @return void */ - public function testRegexLoginUrlSuccess() + public function testRegexLoginUrlSuccess(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '%^/[a-z]{2}/users/secure/?$%', @@ -406,7 +404,7 @@ public function testRegexLoginUrlSuccess() * * @return void */ - public function testFullRegexLoginUrlFailure() + public function testFullRegexLoginUrlFailure(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '%auth\.localhost/[a-z]{2}/users/secure/?$%', @@ -438,7 +436,7 @@ public function testFullRegexLoginUrlFailure() * * @return void */ - public function testFullRegexLoginUrlSuccess() + public function testFullRegexLoginUrlSuccess(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '%auth\.localhost/[a-z]{2}/users/secure/?$%', @@ -471,7 +469,7 @@ public function testFullRegexLoginUrlSuccess() * * @return void */ - public function testFullLoginUrlFailureWithoutCheckFullUrlOption() + public function testFullLoginUrlFailureWithoutCheckFullUrlOption(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => 'http://localhost/secure', @@ -498,7 +496,7 @@ public function testFullLoginUrlFailureWithoutCheckFullUrlOption() * * @return void */ - public function testAuthenticateMissingChecker() + public function testAuthenticateMissingChecker(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '/secure', @@ -525,7 +523,7 @@ public function testAuthenticateMissingChecker() * * @return void */ - public function testAuthenticateInvalidChecker() + public function testAuthenticateInvalidChecker(): void { $envAuth = new EnvironmentAuthenticator($this->identifier, [ 'loginUrl' => '/secure', diff --git a/tests/TestCase/Authenticator/FormAuthenticatorTest.php b/tests/TestCase/Authenticator/FormAuthenticatorTest.php index b0bd80b7..ffeee385 100644 --- a/tests/TestCase/Authenticator/FormAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/FormAuthenticatorTest.php @@ -31,8 +31,6 @@ class FormAuthenticatorTest extends TestCase { /** * Fixtures - * - * @var array */ protected array $fixtures = [ 'core.AuthUsers', @@ -44,7 +42,7 @@ class FormAuthenticatorTest extends TestCase * * @return void */ - public function testAuthenticate() + public function testAuthenticate(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -66,7 +64,7 @@ public function testAuthenticate() * * @return void */ - public function testCredentialsNotPresent() + public function testCredentialsNotPresent(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -90,7 +88,7 @@ public function testCredentialsNotPresent() * * @return void */ - public function testCredentialsEmpty() + public function testCredentialsEmpty(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -109,7 +107,7 @@ public function testCredentialsEmpty() $this->assertEquals([0 => 'Login credentials not found'], $result->getErrors()); } - public function testIdentityNotFound() + public function testIdentityNotFound(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -133,7 +131,7 @@ public function testIdentityNotFound() * * @return void */ - public function testSingleLoginUrlMismatch() + public function testSingleLoginUrlMismatch(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -159,7 +157,7 @@ public function testSingleLoginUrlMismatch() * * @return void */ - public function testMultipleLoginUrlMismatch() + public function testMultipleLoginUrlMismatch(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -192,7 +190,7 @@ public function testMultipleLoginUrlMismatch() * * @return void */ - public function testLoginUrlMismatchWithBase() + public function testLoginUrlMismatchWithBase(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -219,7 +217,7 @@ public function testLoginUrlMismatchWithBase() * * @return void */ - public function testSingleLoginUrlSuccess() + public function testSingleLoginUrlSuccess(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -245,7 +243,7 @@ public function testSingleLoginUrlSuccess() * * @return void */ - public function testMultipleLoginUrlSuccess() + public function testMultipleLoginUrlSuccess(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -275,7 +273,7 @@ public function testMultipleLoginUrlSuccess() * * @return void */ - public function testLoginUrlSuccessWithBase() + public function testLoginUrlSuccessWithBase(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -302,7 +300,7 @@ public function testLoginUrlSuccessWithBase() * * @return void */ - public function testRegexLoginUrlSuccess() + public function testRegexLoginUrlSuccess(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -332,7 +330,7 @@ public function testRegexLoginUrlSuccess() * * @return void */ - public function testFullRegexLoginUrlFailure() + public function testFullRegexLoginUrlFailure(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -365,7 +363,7 @@ public function testFullRegexLoginUrlFailure() * * @return void */ - public function testFullRegexLoginUrlSuccess() + public function testFullRegexLoginUrlSuccess(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -399,7 +397,7 @@ public function testFullRegexLoginUrlSuccess() * * @return void */ - public function testFullLoginUrlFailureWithoutCheckFullUrlOption() + public function testFullLoginUrlFailureWithoutCheckFullUrlOption(): void { $identifier = IdentifierFactory::create('Authentication.Password'); @@ -428,7 +426,7 @@ public function testFullLoginUrlFailureWithoutCheckFullUrlOption() * * @return void */ - public function testAuthenticateCustomFields() + public function testAuthenticateCustomFields(): void { $identifier = $this->createMock(IdentifierInterface::class); @@ -465,7 +463,7 @@ public function testAuthenticateCustomFields() * * @return void */ - public function testAuthenticateValidData() + public function testAuthenticateValidData(): void { $identifier = $this->createMock(IdentifierInterface::class); @@ -498,7 +496,7 @@ public function testAuthenticateValidData() * * @return void */ - public function testAuthenticateMissingChecker() + public function testAuthenticateMissingChecker(): void { $identifier = $this->createMock(IdentifierInterface::class); @@ -524,7 +522,7 @@ public function testAuthenticateMissingChecker() * * @return void */ - public function testAuthenticateInvalidChecker() + public function testAuthenticateInvalidChecker(): void { $identifier = $this->createMock(IdentifierInterface::class); @@ -553,7 +551,7 @@ public function testAuthenticateInvalidChecker() * * @return void */ - public function testDefaultPasswordIdentifier() + public function testDefaultPasswordIdentifier(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -562,7 +560,7 @@ public function testDefaultPasswordIdentifier() ); // FormAuthenticator should automatically configure a Password identifier when null is passed - $form = new FormAuthenticator(null); + $form = new FormAuthenticator(); $result = $form->authenticate($request); $this->assertInstanceOf(Result::class, $result); @@ -578,7 +576,7 @@ public function testDefaultPasswordIdentifier() * * @return void */ - public function testExplicitIdentifierNotOverridden() + public function testExplicitIdentifierNotOverridden(): void { // Create an identifier explicitly $identifier = IdentifierFactory::create('Authentication.Password', [ @@ -600,7 +598,7 @@ public function testExplicitIdentifierNotOverridden() * * @return void */ - public function testDefaultIdentifierInheritsFieldsConfig() + public function testDefaultIdentifierInheritsFieldsConfig(): void { // Configure authenticator with custom fields mapping // Also set a loginUrl that won't match, so authenticate() returns early diff --git a/tests/TestCase/Authenticator/HttpBasicAuthenticatorTest.php b/tests/TestCase/Authenticator/HttpBasicAuthenticatorTest.php index 71ddd053..a6908278 100644 --- a/tests/TestCase/Authenticator/HttpBasicAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/HttpBasicAuthenticatorTest.php @@ -29,8 +29,6 @@ class HttpBasicAuthenticatorTest extends TestCase { /** * Fixtures - * - * @var array */ protected array $fixtures = [ 'core.AuthUsers', @@ -50,7 +48,7 @@ class HttpBasicAuthenticatorTest extends TestCase /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -64,7 +62,7 @@ public function setUp(): void * * @return void */ - public function testConstructor() + public function testConstructor(): void { $object = new HttpBasicAuthenticator($this->identifier, [ 'userModel' => 'AuthUser', @@ -83,7 +81,7 @@ public function testConstructor() * * @return void */ - public function testAuthenticateNoData() + public function testAuthenticateNoData(): void { $request = ServerRequestFactory::fromGlobals( [ @@ -101,7 +99,7 @@ public function testAuthenticateNoData() * * @return void */ - public function testAuthenticateNoUsername() + public function testAuthenticateNoUsername(): void { $request = ServerRequestFactory::fromGlobals( [ @@ -120,7 +118,7 @@ public function testAuthenticateNoUsername() * * @return void */ - public function testAuthenticateNoPassword() + public function testAuthenticateNoPassword(): void { $request = ServerRequestFactory::fromGlobals( [ @@ -139,7 +137,7 @@ public function testAuthenticateNoPassword() * * @return void */ - public function testAuthenticateInjection() + public function testAuthenticateInjection(): void { $request = ServerRequestFactory::fromGlobals( [ @@ -159,7 +157,7 @@ public function testAuthenticateInjection() * * @return void */ - public function testAuthenticateUsernameZero() + public function testAuthenticateUsernameZero(): void { $User = TableRegistry::getTableLocator()->get('Users'); $User->updateAll(['username' => '0'], ['username' => 'mariano']); @@ -201,7 +199,7 @@ public function testAuthenticateUsernameZero() * * @return void */ - public function testAuthenticateChallenge() + public function testAuthenticateChallenge(): void { $request = ServerRequestFactory::fromGlobals( [ @@ -225,7 +223,7 @@ public function testAuthenticateChallenge() * * @return void */ - public function testAuthenticateSuccess() + public function testAuthenticateSuccess(): void { $request = ServerRequestFactory::fromGlobals( [ diff --git a/tests/TestCase/Authenticator/HttpDigestAuthenticatorTest.php b/tests/TestCase/Authenticator/HttpDigestAuthenticatorTest.php index 2eedcb77..d67526f3 100644 --- a/tests/TestCase/Authenticator/HttpDigestAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/HttpDigestAuthenticatorTest.php @@ -35,8 +35,6 @@ class HttpDigestAuthenticatorTest extends TestCase { /** * Fixtures - * - * @var array */ protected array $fixtures = [ 'core.AuthUsers', @@ -58,7 +56,7 @@ class HttpDigestAuthenticatorTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -81,7 +79,7 @@ public function setUp(): void * * @return void */ - public function testConstructor() + public function testConstructor(): void { $object = new HttpDigestAuthenticator($this->identifier, [ 'userModel' => 'AuthUser', @@ -102,7 +100,7 @@ public function testConstructor() * * @return void */ - public function testAuthenticateNoData() + public function testAuthenticateNoData(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/posts/index'], @@ -118,7 +116,7 @@ public function testAuthenticateNoData() * * @return void */ - public function testAuthenticateWrongUsername() + public function testAuthenticateWrongUsername(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/posts/index'], @@ -148,7 +146,7 @@ public function testAuthenticateWrongUsername() * * @return void */ - public function testAuthenticateSuccess() + public function testAuthenticateSuccess(): void { $data = [ 'username' => 'mariano', @@ -191,7 +189,7 @@ public function testAuthenticateSuccess() * * @return void */ - public function testAuthenticateFailsOnBadNonce() + public function testAuthenticateFailsOnBadNonce(): void { $data = [ 'username' => 'mariano', @@ -222,7 +220,7 @@ public function testAuthenticateFailsOnBadNonce() * * @return void */ - public function testAuthenticateFailsNonceWithTooManyParts() + public function testAuthenticateFailsNonceWithTooManyParts(): void { $data = [ 'username' => 'mariano', @@ -253,7 +251,7 @@ public function testAuthenticateFailsNonceWithTooManyParts() * * @return void */ - public function testAuthenticateFailsOnStaleNonce() + public function testAuthenticateFailsOnStaleNonce(): void { $request = ServerRequestFactory::fromGlobals([ 'REQUEST_URI' => '/posts/index', @@ -280,7 +278,7 @@ public function testAuthenticateFailsOnStaleNonce() * * @return void */ - public function testUnauthorizedChallenge() + public function testUnauthorizedChallenge(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/posts/index', 'REQUEST_METHOD' => 'GET'], @@ -304,7 +302,7 @@ public function testUnauthorizedChallenge() * * @return void */ - public function testUnauthorizedFailReChallenge() + public function testUnauthorizedFailReChallenge(): void { $this->auth->setConfig('scope.username', 'nate'); @@ -347,7 +345,7 @@ public function testUnauthorizedFailReChallenge() * * @return void */ - public function testUnauthorizedChallengeIncludesStaleAttributeOnStaleNonce() + public function testUnauthorizedChallengeIncludesStaleAttributeOnStaleNonce(): void { $request = ServerRequestFactory::fromGlobals([ 'REQUEST_URI' => '/posts/index', @@ -378,7 +376,7 @@ public function testUnauthorizedChallengeIncludesStaleAttributeOnStaleNonce() * * @return void */ - public function testParseAuthData() + public function testParseAuthData(): void { $digest = << 'mariano', 'realm' => 'localhost', 'opaque' => '123abc', ]; - $digest = <<request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -115,7 +114,7 @@ public function testAuthenticateViaHeaderToken() * * @return void */ - public function testAuthenticateViaQueryParamToken() + public function testAuthenticateViaQueryParamToken(): void { $this->request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -138,7 +137,7 @@ public function testAuthenticateViaQueryParamToken() * * @return void */ - public function testAuthenticationViaIdentifierAndSubject() + public function testAuthenticationViaIdentifierAndSubject(): void { $this->request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -177,7 +176,7 @@ public function testAuthenticationViaIdentifierAndSubject() * * @return void */ - public function testAuthenticateInvalidPayloadNotAnObject() + public function testAuthenticateInvalidPayloadNotAnObject(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -208,7 +207,7 @@ public function testAuthenticateInvalidPayloadNotAnObject() * * @return void */ - public function testAuthenticateInvalidPayloadEmpty() + public function testAuthenticateInvalidPayloadEmpty(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -234,7 +233,7 @@ public function testAuthenticateInvalidPayloadEmpty() $this->assertNUll($result->getData()); } - public function testInvalidToken() + public function testInvalidToken(): void { $this->request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -260,7 +259,7 @@ public function testInvalidToken() * * @return void */ - public function testGetPayloadHS256() + public function testGetPayloadHS256(): void { $this->request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], @@ -292,7 +291,7 @@ public function testGetPayloadHS256() * * @return void */ - public function testGetPayloadRS256() + public function testGetPayloadRS256(): void { $this->request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/'], diff --git a/tests/TestCase/Authenticator/PrimaryKeySessionAuthenticatorTest.php b/tests/TestCase/Authenticator/PrimaryKeySessionAuthenticatorTest.php index ce704aae..bbade753 100644 --- a/tests/TestCase/Authenticator/PrimaryKeySessionAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/PrimaryKeySessionAuthenticatorTest.php @@ -20,12 +20,14 @@ use Authentication\Authenticator\PrimaryKeySessionAuthenticator; use Authentication\Authenticator\Result; use Authentication\Identifier\IdentifierFactory; +use Authentication\Identifier\IdentifierInterface; use Authentication\Identifier\TokenIdentifier; use Cake\Http\Exception\UnauthorizedException; use Cake\Http\Response; use Cake\Http\ServerRequestFactory; use Cake\Http\Session; use Cake\TestSuite\TestCase; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -39,20 +41,14 @@ class PrimaryKeySessionAuthenticatorTest extends TestCase 'core.Users', ]; - /** - * @var \Authentication\Identifier\IdentifierInterface - */ - protected $identifier; + protected IdentifierInterface $identifier; - /** - * @var \Cake\Http\Session&\PHPUnit\Framework\MockObject\MockObject - */ - protected $sessionMock; + protected MockObject|Session $sessionMock; /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -72,7 +68,7 @@ public function setUp(): void * * @return void */ - public function testAuthenticateSuccess() + public function testAuthenticateSuccess(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); @@ -95,7 +91,7 @@ public function testAuthenticateSuccess() * * @return void */ - public function testAuthenticateSuccessWithDefaultIdentifier() + public function testAuthenticateSuccessWithDefaultIdentifier(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); @@ -107,7 +103,7 @@ public function testAuthenticateSuccessWithDefaultIdentifier() $request = $request->withAttribute('session', $this->sessionMock); // No identifier passed - should use the default TokenIdentifier - $authenticator = new PrimaryKeySessionAuthenticator(null); + $authenticator = new PrimaryKeySessionAuthenticator(); $result = $authenticator->authenticate($request); $this->assertInstanceOf(Result::class, $result); @@ -119,9 +115,9 @@ public function testAuthenticateSuccessWithDefaultIdentifier() * * @return void */ - public function testGetIdentifierReturnsDefaultWhenNotConfigured() + public function testGetIdentifierReturnsDefaultWhenNotConfigured(): void { - $authenticator = new PrimaryKeySessionAuthenticator(null); + $authenticator = new PrimaryKeySessionAuthenticator(); $identifier = $authenticator->getIdentifier(); $this->assertInstanceOf(TokenIdentifier::class, $identifier); @@ -134,7 +130,7 @@ public function testGetIdentifierReturnsDefaultWhenNotConfigured() * * @return void */ - public function testGetIdentifierUsesCustomConfig() + public function testGetIdentifierUsesCustomConfig(): void { $authenticator = new PrimaryKeySessionAuthenticator(null, [ 'idField' => 'uuid', @@ -152,7 +148,7 @@ public function testGetIdentifierUsesCustomConfig() * * @return void */ - public function testAuthenticateSuccessCustomFinder() + public function testAuthenticateSuccessCustomFinder(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); @@ -191,7 +187,7 @@ public function testAuthenticateSuccessCustomFinder() * * @return void */ - public function testAuthenticateFailure() + public function testAuthenticateFailure(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); @@ -214,7 +210,7 @@ public function testAuthenticateFailure() * * @return void */ - public function testVerifyByDatabaseFailure() + public function testVerifyByDatabaseFailure(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); @@ -238,10 +234,11 @@ public function testVerifyByDatabaseFailure() * * @return void */ - public function testPersistIdentity() + public function testPersistIdentity(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new PrimaryKeySessionAuthenticator($this->identifier); @@ -280,10 +277,11 @@ public function testPersistIdentity() * * @return void */ - public function testClearIdentity() + public function testClearIdentity(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new PrimaryKeySessionAuthenticator($this->identifier); @@ -309,10 +307,11 @@ public function testClearIdentity() * * @return void */ - public function testImpersonate() + public function testImpersonate(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new PrimaryKeySessionAuthenticator($this->identifier); @@ -322,6 +321,7 @@ public function testImpersonate() 'password' => 'password', ]); $impersonator->id = 123; + $impersonated = $usersTable->newEntity(['username' => 'larry']); $impersonated->id = 456; @@ -350,10 +350,11 @@ public function testImpersonate() * * @return void */ - public function testImpersonateAlreadyImpersonating() + public function testImpersonateAlreadyImpersonating(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new PrimaryKeySessionAuthenticator($this->identifier); @@ -384,10 +385,11 @@ public function testImpersonateAlreadyImpersonating() * * @return void */ - public function testStopImpersonating() + public function testStopImpersonating(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new PrimaryKeySessionAuthenticator($this->identifier); @@ -431,10 +433,11 @@ public function testStopImpersonating() * * @return void */ - public function testStopImpersonatingNotImpersonating() + public function testStopImpersonatingNotImpersonating(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new PrimaryKeySessionAuthenticator($this->identifier); @@ -469,7 +472,7 @@ public function testStopImpersonatingNotImpersonating() * * @return void */ - public function testIsImpersonating() + public function testIsImpersonating(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); diff --git a/tests/TestCase/Authenticator/ResultTest.php b/tests/TestCase/Authenticator/ResultTest.php index 4bad3083..4264e7e2 100644 --- a/tests/TestCase/Authenticator/ResultTest.php +++ b/tests/TestCase/Authenticator/ResultTest.php @@ -27,7 +27,7 @@ class ResultTest extends TestCase * * @return void */ - public function testConstructorEmptyData() + public function testConstructorEmptyData(): void { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage('Identity data can not be empty with status success.'); @@ -39,7 +39,7 @@ public function testConstructorEmptyData() * * @return void */ - public function testIsValid() + public function testIsValid(): void { $result = new Result(null, Result::FAILURE_CREDENTIALS_INVALID); $this->assertFalse($result->isValid()); @@ -63,7 +63,7 @@ public function testIsValid() * * @return void */ - public function testGetIdentity() + public function testGetIdentity(): void { $entity = new Entity(['user' => 'florian']); $result = new Result($entity, Result::SUCCESS); @@ -75,7 +75,7 @@ public function testGetIdentity() * * @return void */ - public function testGetIdentityArray() + public function testGetIdentityArray(): void { $data = ['user' => 'florian']; $result = new Result($data, Result::SUCCESS); @@ -87,7 +87,7 @@ public function testGetIdentityArray() * * @return void */ - public function testGetCode() + public function testGetCode(): void { $result = new Result(null, Result::FAILURE_IDENTITY_NOT_FOUND); $this->assertSame(Result::FAILURE_IDENTITY_NOT_FOUND, $result->getStatus()); @@ -102,7 +102,7 @@ public function testGetCode() * * @return void */ - public function testGetErrors() + public function testGetErrors(): void { $messages = [ 'Out of coffee!', diff --git a/tests/TestCase/Authenticator/SessionAuthenticatorTest.php b/tests/TestCase/Authenticator/SessionAuthenticatorTest.php index 88ef913b..3d46d656 100644 --- a/tests/TestCase/Authenticator/SessionAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/SessionAuthenticatorTest.php @@ -25,6 +25,7 @@ use Cake\Http\ServerRequestFactory; use Cake\Http\Session; use Cake\ORM\TableRegistry; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -32,20 +33,18 @@ class SessionAuthenticatorTest extends TestCase { /** * Fixtures - * - * @var array */ protected array $fixtures = [ 'core.AuthUsers', 'core.Users', ]; - protected $sessionMock; + protected MockObject|Session $sessionMock; /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -60,7 +59,7 @@ public function setUp(): void * * @return void */ - public function testAuthenticateSuccess() + public function testAuthenticateSuccess(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); @@ -86,7 +85,7 @@ public function testAuthenticateSuccess() * * @return void */ - public function testAuthenticateFailure() + public function testAuthenticateFailure(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); @@ -109,10 +108,11 @@ public function testAuthenticateFailure() * * @return void */ - public function testPersistIdentity() + public function testPersistIdentity(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new SessionAuthenticator(); @@ -151,10 +151,11 @@ public function testPersistIdentity() * * @return void */ - public function testClearIdentity() + public function testClearIdentity(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new SessionAuthenticator(); @@ -180,10 +181,11 @@ public function testClearIdentity() * * @return void */ - public function testImpersonate() + public function testImpersonate(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new SessionAuthenticator(); @@ -219,10 +221,11 @@ public function testImpersonate() * * @return void */ - public function testImpersonateAlreadyImpersonating() + public function testImpersonateAlreadyImpersonating(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new SessionAuthenticator(); @@ -253,10 +256,11 @@ public function testImpersonateAlreadyImpersonating() * * @return void */ - public function testStopImpersonating() + public function testStopImpersonating(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new SessionAuthenticator(); @@ -300,10 +304,11 @@ public function testStopImpersonating() * * @return void */ - public function testStopImpersonatingNotImpersonating() + public function testStopImpersonatingNotImpersonating(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); + $response = new Response(); $authenticator = new SessionAuthenticator(); @@ -338,7 +343,7 @@ public function testStopImpersonatingNotImpersonating() * * @return void */ - public function testIsImpersonating() + public function testIsImpersonating(): void { $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/']); $request = $request->withAttribute('session', $this->sessionMock); diff --git a/tests/TestCase/Authenticator/TokenAuthenticatorTest.php b/tests/TestCase/Authenticator/TokenAuthenticatorTest.php index 8b2a4725..8b241575 100644 --- a/tests/TestCase/Authenticator/TokenAuthenticatorTest.php +++ b/tests/TestCase/Authenticator/TokenAuthenticatorTest.php @@ -26,8 +26,6 @@ class TokenAuthenticatorTest extends TestCase { /** * Fixtures - * - * @var array */ protected array $fixtures = [ 'core.AuthUsers', @@ -47,7 +45,7 @@ class TokenAuthenticatorTest extends TestCase /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -67,7 +65,7 @@ public function setUp(): void * * @return void */ - public function testAuthenticateViaHeaderToken() + public function testAuthenticateViaHeaderToken(): void { // Test without token $tokenAuth = new TokenAuthenticator($this->identifier, [ @@ -92,7 +90,7 @@ public function testAuthenticateViaHeaderToken() * * @return void */ - public function testViaQueryParamToken() + public function testViaQueryParamToken(): void { // Test with query param token $requestWithParams = $this->request->withQueryParams(['token' => 'mariano']); @@ -118,7 +116,7 @@ public function testViaQueryParamToken() * * @return void */ - public function testTokenPrefix() + public function testTokenPrefix(): void { //valid prefix $requestWithHeaders = $this->request->withAddedHeader('Token', 'identity mariano'); @@ -165,7 +163,7 @@ public function testTokenPrefix() * * @return void */ - public function testWithoutQueryParamConfig() + public function testWithoutQueryParamConfig(): void { $tokenAuth = new TokenAuthenticator($this->identifier, [ 'header' => 'Token', @@ -181,7 +179,7 @@ public function testWithoutQueryParamConfig() * * @return void */ - public function testWithoutHeaderConfig() + public function testWithoutHeaderConfig(): void { $tokenAuth = new TokenAuthenticator($this->identifier, [ 'queryParam' => 'token', @@ -197,7 +195,7 @@ public function testWithoutHeaderConfig() * * @return void */ - public function testWithoutAnyConfig() + public function testWithoutAnyConfig(): void { $tokenAuth = new TokenAuthenticator($this->identifier); diff --git a/tests/TestCase/Controller/Component/AuthenticationComponentTest.php b/tests/TestCase/Controller/Component/AuthenticationComponentTest.php index 19313987..3c953bea 100644 --- a/tests/TestCase/Controller/Component/AuthenticationComponentTest.php +++ b/tests/TestCase/Controller/Component/AuthenticationComponentTest.php @@ -67,7 +67,7 @@ class AuthenticationComponentTest extends TestCase /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -101,7 +101,7 @@ public function setUp(): void * * @return void */ - public function testGetAuthenticationService() + public function testGetAuthenticationService(): void { $service = new AuthenticationService(); $request = $this->request->withAttribute('authentication', $service); @@ -117,7 +117,7 @@ public function testGetAuthenticationService() * * @return void */ - public function testGetAuthenticationServiceMissingServiceAttribute() + public function testGetAuthenticationServiceMissingServiceAttribute(): void { $this->expectException('Exception'); $this->expectExceptionMessage('The request object does not contain the required `authentication` attribute'); @@ -132,7 +132,7 @@ public function testGetAuthenticationServiceMissingServiceAttribute() * * @return void */ - public function testGetAuthenticationServiceInvalidServiceObject() + public function testGetAuthenticationServiceInvalidServiceObject(): void { $this->expectException('Exception'); $this->expectExceptionMessage('Authentication service does not implement Authentication\AuthenticationServiceInterface'); @@ -164,7 +164,7 @@ public function testGetId(): void * * @eturn void */ - public function testGetIdentity() + public function testGetIdentity(): void { $request = $this->request ->withAttribute('identity', $this->identity) @@ -184,7 +184,7 @@ public function testGetIdentity() * * @eturn void */ - public function testGetIdentityWithCustomAttribute() + public function testGetIdentityWithCustomAttribute(): void { $this->request = $this->request->withAttribute('customIdentity', $this->identity); $this->request = $this->request->withAttribute('authentication', $this->service); @@ -205,7 +205,7 @@ public function testGetIdentityWithCustomAttribute() * * @eturn void */ - public function testSetIdentity() + public function testSetIdentity(): void { $request = $this->request->withAttribute('authentication', $this->service); @@ -214,6 +214,7 @@ public function testSetIdentity() $component = new AuthenticationComponent($registry); $component->setIdentity($this->identityData); + $result = $component->getIdentity(); $this->assertSame($this->identityData, $result->getOriginalData()); @@ -229,7 +230,7 @@ public function testSetIdentity() * * @eturn void */ - public function testSetIdentityInstance() + public function testSetIdentityInstance(): void { $request = $this->request->withAttribute('authentication', $this->service); @@ -248,7 +249,7 @@ public function testSetIdentityInstance() * * @eturn void */ - public function testSetIdentityOverwrite() + public function testSetIdentityOverwrite(): void { $request = $this->request->withAttribute('authentication', $this->service); @@ -257,6 +258,7 @@ public function testSetIdentityOverwrite() $component = new AuthenticationComponent($registry); $component->setIdentity($this->identityData); + $result = $component->getIdentity(); $this->assertSame($this->identityData, $result->getOriginalData()); $this->assertSame( @@ -283,7 +285,7 @@ public function testSetIdentityOverwrite() * * @eturn void */ - public function testGetIdentityData() + public function testGetIdentityData(): void { $request = $this->request ->withAttribute('identity', $this->identity) @@ -302,7 +304,7 @@ public function testGetIdentityData() * * @eturn void */ - public function testGetMissingIdentityData() + public function testGetMissingIdentityData(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('The identity has not been found.'); @@ -320,7 +322,7 @@ public function testGetMissingIdentityData() * * @return void */ - public function testGetResult() + public function testGetResult(): void { $request = $this->request ->withAttribute('identity', $this->identity) @@ -337,10 +339,10 @@ public function testGetResult() * * @return void */ - public function testLogout() + public function testLogout(): void { $result = null; - EventManager::instance()->on('Authentication.logout', function (Event $event) use (&$result) { + EventManager::instance()->on('Authentication.logout', function (Event $event) use (&$result): void { $result = $event; }); @@ -364,7 +366,7 @@ public function testLogout() * * @eturn void */ - public function testGetLoginRedirect() + public function testGetLoginRedirect(): void { Configure::write('App.base', '/cakephp'); $url = ['controller' => 'Users', 'action' => 'dashboard']; @@ -400,10 +402,10 @@ public function testGetLoginRedirect() * * @return void */ - public function testAfterIdentifyEvent() + public function testAfterIdentifyEvent(): void { $result = null; - EventManager::instance()->on('Authentication.afterIdentify', function (Event $event) use (&$result) { + EventManager::instance()->on('Authentication.afterIdentify', function (Event $event) use (&$result): void { $result = $event; }); @@ -430,7 +432,7 @@ public function testAfterIdentifyEvent() * * @return void */ - public function testUnauthenticatedActions() + public function testUnauthenticatedActions(): void { $request = $this->request ->withParam('action', 'view') @@ -461,7 +463,7 @@ public function testUnauthenticatedActions() * * @return void */ - public function testUnauthenticatedActionsOk() + public function testUnauthenticatedActionsOk(): void { $request = $this->request ->withParam('action', 'view') @@ -480,7 +482,7 @@ public function testUnauthenticatedActionsOk() * * @return void */ - public function testUnauthenticatedActionsMismatchAction() + public function testUnauthenticatedActionsMismatchAction(): void { $request = $this->request ->withParam('action', 'view') @@ -500,7 +502,7 @@ public function testUnauthenticatedActionsMismatchAction() * * @return void */ - public function testUnauthenticatedActionsNoActionsFails() + public function testUnauthenticatedActionsNoActionsFails(): void { $request = $this->request ->withParam('action', 'view') @@ -519,7 +521,7 @@ public function testUnauthenticatedActionsNoActionsFails() * * @return void */ - public function testUnauthenticatedActionsDisabledOptions() + public function testUnauthenticatedActionsDisabledOptions(): void { $request = $this->request ->withParam('action', 'view') @@ -541,7 +543,7 @@ public function testUnauthenticatedActionsDisabledOptions() * * @return void */ - public function testUnauthenticatedActionsDisabledOptionsCall() + public function testUnauthenticatedActionsDisabledOptionsCall(): void { $request = $this->request ->withParam('action', 'view') @@ -562,7 +564,7 @@ public function testUnauthenticatedActionsDisabledOptionsCall() * * @return void */ - public function testIdentityCheckInBeforeFilter() + public function testIdentityCheckInBeforeFilter(): void { $request = $this->request ->withAttribute('authentication', $this->service); @@ -580,7 +582,7 @@ public function testIdentityCheckInBeforeFilter() $component->beforeFilter(); } - public function testCustomUnauthenticatedMessage() + public function testCustomUnauthenticatedMessage(): void { $request = $this->request ->withAttribute('authentication', $this->service); @@ -605,7 +607,7 @@ public function testCustomUnauthenticatedMessage() * * @return void */ - public function testImpersonate() + public function testImpersonate(): void { $impersonator = new ArrayObject(['username' => 'mariano']); $impersonated = new ArrayObject(['username' => 'larry']); @@ -635,7 +637,7 @@ public function testImpersonate() * * @return void */ - public function testImpersonateDecoratorIgnored() + public function testImpersonateDecoratorIgnored(): void { $impersonator = ['username' => 'mariano']; $impersonated = new ArrayObject(['username' => 'larry']); @@ -666,7 +668,7 @@ public function testImpersonateDecoratorIgnored() * * @return void */ - public function testImpersonateNoIdentity() + public function testImpersonateNoIdentity(): void { $impersonated = new ArrayObject(['username' => 'larry']); $request = $this->request @@ -684,7 +686,7 @@ public function testImpersonateNoIdentity() * * @return void */ - public function testImpersonateFailure() + public function testImpersonateFailure(): void { $impersonator = new ArrayObject(['username' => 'mariano']); $impersonated = new ArrayObject(['username' => 'larry']); @@ -713,7 +715,7 @@ public function testImpersonateFailure() * * @return void */ - public function testStopImpersonating() + public function testStopImpersonating(): void { $impersonator = new ArrayObject(['username' => 'mariano']); $impersonated = new ArrayObject(['username' => 'larry']); @@ -736,7 +738,7 @@ public function testStopImpersonating() * * @return void */ - public function testStopImpersonatingFailure() + public function testStopImpersonatingFailure(): void { $impersonator = new ArrayObject(['username' => 'mariano']); $service = $this->getMockBuilder(AuthenticationService::class) @@ -764,7 +766,7 @@ public function testStopImpersonatingFailure() * * @return void */ - public function testIsImpersonating() + public function testIsImpersonating(): void { $impersonator = new ArrayObject(['username' => 'mariano']); $impersonated = new ArrayObject(['username' => 'larry']); @@ -790,7 +792,7 @@ public function testIsImpersonating() * * @return void */ - public function testGetImpersonationAuthenticationServiceFailure() + public function testGetImpersonationAuthenticationServiceFailure(): void { $service = $this->getMockBuilder(AuthenticationServiceInterface::class)->getMock(); @@ -803,8 +805,8 @@ public function testGetImpersonationAuthenticationServiceFailure() $component = new AuthenticationComponent($registry); $this->expectException(InvalidArgumentException::class); - $classname = get_class($service); - $this->expectExceptionMessage("The $classname must implement ImpersonationInterface in order to use impersonation."); + $classname = $service::class; + $this->expectExceptionMessage(sprintf('The %s must implement ImpersonationInterface in order to use impersonation.', $classname)); $component->isImpersonating(); } @@ -813,7 +815,7 @@ public function testGetImpersonationAuthenticationServiceFailure() * * @return void */ - public function testIsImpersonatingNotImpersonating() + public function testIsImpersonatingNotImpersonating(): void { $user = new ArrayObject(['username' => 'mariano']); $this->request->getSession()->write('Auth', $user); diff --git a/tests/TestCase/Identifier/CallbackIdentifierTest.php b/tests/TestCase/Identifier/CallbackIdentifierTest.php index df838b7d..c4d94f7a 100644 --- a/tests/TestCase/Identifier/CallbackIdentifierTest.php +++ b/tests/TestCase/Identifier/CallbackIdentifierTest.php @@ -31,9 +31,9 @@ class CallbackIdentifierTest extends TestCase * * @return void */ - public function testIdentify() + public function testIdentify(): void { - $callback = function ($data) { + $callback = function (array $data): ?Entity { if (isset($data['username']) && $data['username'] === 'florian') { return new Entity($data); } @@ -60,10 +60,10 @@ public function testIdentify() * * @return void */ - public function testValidCallable() + public function testValidCallable(): void { $identifier = new CallbackIdentifier([ - 'callback' => function () { + 'callback' => function (): Entity { return new Entity(); }, ]); @@ -72,7 +72,7 @@ public function testValidCallable() $this->assertInstanceOf(ArrayAccess::class, $result); $identifier = new CallbackIdentifier([ - 'callback' => [MyCallback::class, 'callme'], + 'callback' => MyCallback::callme(...), ]); $result = $identifier->identify([]); @@ -82,7 +82,7 @@ public function testValidCallable() /** * testInvalidCallbackType */ - public function testInvalidCallbackTypeString() + public function testInvalidCallbackTypeString(): void { $this->expectException('InvalidArgumentException'); new CallbackIdentifier([ @@ -93,7 +93,7 @@ public function testInvalidCallbackTypeString() /** * testInvalidCallbackTypeObject */ - public function testInvalidCallbackTypeObject() + public function testInvalidCallbackTypeObject(): void { $this->expectException('InvalidArgumentException'); new CallbackIdentifier([ @@ -104,11 +104,11 @@ public function testInvalidCallbackTypeObject() /** * testInvalidCallbackTypeObject */ - public function testInvalidReturnValue() + public function testInvalidReturnValue(): void { $this->expectException('RuntimeException'); $identifier = new CallbackIdentifier([ - 'callback' => function ($data) { + 'callback' => function ($data): string { return 'no'; }, ]); @@ -120,10 +120,10 @@ public function testInvalidReturnValue() * * @return void */ - public function testResultReturn() + public function testResultReturn(): void { $identifier = new CallbackIdentifier([ - 'callback' => function ($data) { + 'callback' => function (array $data): Result { if (isset($data['username']) && $data['username'] === 'florian') { return new Result(new Entity($data), Result::SUCCESS); } diff --git a/tests/TestCase/Identifier/LdapIdentifierTest.php b/tests/TestCase/Identifier/LdapIdentifierTest.php index b9cc2260..67f83d62 100644 --- a/tests/TestCase/Identifier/LdapIdentifierTest.php +++ b/tests/TestCase/Identifier/LdapIdentifierTest.php @@ -33,10 +33,10 @@ class LdapIdentifierTest extends TestCase * * @return void */ - public function testIdentify() + public function testIdentify(): void { $host = 'ldap.example.com'; - $bind = function ($username) { + $bind = function (string $username): string { return 'cn=' . $username . ',dc=example,dc=com'; }; $options = [ @@ -73,7 +73,7 @@ public function testIdentify() * * @return void */ - public function testIdentifyMissingCredentials() + public function testIdentifyMissingCredentials(): void { $ldap = $this->createMock(AdapterInterface::class); $ldap->method('bind') @@ -81,7 +81,7 @@ public function testIdentifyMissingCredentials() $identifier = new LdapIdentifier([ 'host' => 'ldap.example.com', - 'bindDN' => function () { + 'bindDN' => function (): string { return 'dc=example,dc=com'; }, 'ldap' => $ldap, @@ -102,13 +102,13 @@ public function testIdentifyMissingCredentials() * * @return void */ - public function testLdapExtensionAdapter() + public function testLdapExtensionAdapter(): void { $this->skipIf(!extension_loaded('ldap'), 'LDAP extension is not loaded.'); $identifier = new LdapIdentifier([ 'host' => 'ldap.example.com', - 'bindDN' => function () { + 'bindDN' => function (): string { return 'dc=example,dc=com'; }, ]); @@ -121,7 +121,7 @@ public function testLdapExtensionAdapter() * * @return void */ - public function testWrongLdapObject() + public function testWrongLdapObject(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Option `ldap` must implement `Authentication\Identifier\Ldap\AdapterInterface`.'); @@ -130,7 +130,7 @@ public function testWrongLdapObject() new LdapIdentifier([ 'host' => 'ldap.example.com', - 'bindDN' => function () { + 'bindDN' => function (): string { return 'dc=example,dc=com'; }, 'ldap' => $notLdap, @@ -142,7 +142,7 @@ public function testWrongLdapObject() * * @return void */ - public function testMissingBindDN() + public function testMissingBindDN(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Config `bindDN` is not set.'); @@ -157,7 +157,7 @@ public function testMissingBindDN() * * @return void */ - public function testUncallableDN() + public function testUncallableDN(): void { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage('The `bindDN` config is not a callable. Got `string` instead.'); @@ -173,13 +173,13 @@ public function testUncallableDN() * * @return void */ - public function testMissingHost() + public function testMissingHost(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Config `host` is not set.'); new LdapIdentifier([ - 'bindDN' => function () { + 'bindDN' => function (): string { return 'dc=example,dc=com'; }, ]); @@ -190,7 +190,7 @@ public function testMissingHost() * * @return void */ - public function testHandleError() + public function testHandleError(): void { $ldap = $this->createMock(AdapterInterface::class); $ldap->method('bind') @@ -200,7 +200,7 @@ public function testHandleError() $identifier = new LdapIdentifier([ 'host' => 'ldap.example.com', - 'bindDN' => function () { + 'bindDN' => function (): string { return 'dc=example,dc=com'; }, 'ldap' => $ldap, diff --git a/tests/TestCase/Identifier/PasswordIdentifierTest.php b/tests/TestCase/Identifier/PasswordIdentifierTest.php index 2a7e51bf..f1c4c36b 100644 --- a/tests/TestCase/Identifier/PasswordIdentifierTest.php +++ b/tests/TestCase/Identifier/PasswordIdentifierTest.php @@ -33,7 +33,7 @@ class PasswordIdentifierTest extends TestCase * * @return void */ - public function testIdentifyValid() + public function testIdentifyValid(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -70,7 +70,7 @@ public function testIdentifyValid() * * @return void */ - public function testIdentifyNeedsRehash() + public function testIdentifyNeedsRehash(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -108,7 +108,7 @@ public function testIdentifyNeedsRehash() * * @return void */ - public function testIdentifyInvalidUser() + public function testIdentifyInvalidUser(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -139,7 +139,7 @@ public function testIdentifyInvalidUser() * * @return void */ - public function testIdentifyInvalidPassword() + public function testIdentifyInvalidPassword(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -175,7 +175,7 @@ public function testIdentifyInvalidPassword() * * @return void */ - public function testIdentifyPasswordAgainstNullValue() + public function testIdentifyPasswordAgainstNullValue(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -209,7 +209,7 @@ public function testIdentifyPasswordAgainstNullValue() * * @return void */ - public function testIdentifyEmptyPassword() + public function testIdentifyEmptyPassword(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -245,7 +245,7 @@ public function testIdentifyEmptyPassword() * * @return void */ - public function testIdentifyNoPassword() + public function testIdentifyNoPassword(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -278,7 +278,7 @@ public function testIdentifyNoPassword() * * @return void */ - public function testIdentifyMissingCredentials() + public function testIdentifyMissingCredentials(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -302,7 +302,7 @@ public function testIdentifyMissingCredentials() * * @return void */ - public function testIdentifyMultiField() + public function testIdentifyMultiField(): void { $resolver = $this->createMock(ResolverInterface::class); $hasher = $this->createMock(PasswordHasherInterface::class); @@ -349,7 +349,7 @@ public function testIdentifyMultiField() * * @return void */ - public function testDefaultPasswordHasher() + public function testDefaultPasswordHasher(): void { $identifier = new PasswordIdentifier(); $hasher = $identifier->getPasswordHasher(); @@ -361,7 +361,7 @@ public function testDefaultPasswordHasher() * * @return void */ - public function testCustomPasswordHasher() + public function testCustomPasswordHasher(): void { $identifier = new PasswordIdentifier([ 'passwordHasher' => 'Authentication.Legacy', diff --git a/tests/TestCase/Identifier/Resolver/OrmResolverTest.php b/tests/TestCase/Identifier/Resolver/OrmResolverTest.php index a9cd0de9..03d6c263 100644 --- a/tests/TestCase/Identifier/Resolver/OrmResolverTest.php +++ b/tests/TestCase/Identifier/Resolver/OrmResolverTest.php @@ -22,7 +22,7 @@ class OrmResolverTest extends AuthenticationTestCase { - public function testFindDefault() + public function testFindDefault(): void { $resolver = new OrmResolver(); @@ -34,7 +34,7 @@ public function testFindDefault() $this->assertSame('mariano', $user['username']); } - public function testFindConfig() + public function testFindConfig(): void { $resolver = new OrmResolver([ 'userModel' => 'AuthUsers', @@ -51,7 +51,7 @@ public function testFindConfig() $this->assertNotEmpty($user->created); } - public function testFindAnd() + public function testFindAnd(): void { $resolver = new OrmResolver(); @@ -63,7 +63,7 @@ public function testFindAnd() $this->assertSame(1, $user['id']); } - public function testFindOr() + public function testFindOr(): void { $resolver = new OrmResolver(); @@ -75,7 +75,7 @@ public function testFindOr() $this->assertSame(1, $user['id']); } - public function testFindMissing() + public function testFindMissing(): void { $resolver = new OrmResolver(); @@ -87,7 +87,7 @@ public function testFindMissing() $this->assertNull($user); } - public function testFindMultipleValues() + public function testFindMultipleValues(): void { $resolver = new OrmResolver(); diff --git a/tests/TestCase/Identifier/Resolver/ResolverAwareTraitTest.php b/tests/TestCase/Identifier/Resolver/ResolverAwareTraitTest.php index 375f473c..b83b65dc 100644 --- a/tests/TestCase/Identifier/Resolver/ResolverAwareTraitTest.php +++ b/tests/TestCase/Identifier/Resolver/ResolverAwareTraitTest.php @@ -25,12 +25,12 @@ #[AllowMockObjectsWithoutExpectations] class ResolverAwareTraitTest extends TestCase { - public function testBuildResolverFromClassName() + public function testBuildResolverFromClassName(): void { $object = new class { use ResolverAwareTrait; - public function getConfig() + public function getConfig(): string { return 'Test'; } @@ -40,12 +40,12 @@ public function getConfig() $this->assertInstanceOf(TestResolver::class, $resolver); } - public function testBuildResolverFromArray() + public function testBuildResolverFromArray(): void { $object = new class { use ResolverAwareTrait; - public function getConfig() + public function getConfig(): array { return [ 'className' => 'Test', @@ -57,14 +57,14 @@ public function getConfig() $this->assertInstanceOf(TestResolver::class, $resolver); } - public function testBuildResolverInvalid() + public function testBuildResolverInvalid(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Resolver must implement `Authentication\Identifier\Resolver\ResolverInterface`.'); $object = new class { use ResolverAwareTrait; - public function getConfig() + public function getConfig(): string { return 'Invalid'; } @@ -73,14 +73,14 @@ public function getConfig() $object->getResolver(); } - public function testBuildResolverMissing() + public function testBuildResolverMissing(): void { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage('Resolver class `Missing` does not exist.'); $object = new class { use ResolverAwareTrait; - public function getConfig() + public function getConfig(): string { return 'Missing'; } @@ -89,14 +89,14 @@ public function getConfig() $object->getResolver(); } - public function testBuildResolverMissingClassNameOption() + public function testBuildResolverMissingClassNameOption(): void { $this->expectException('InvalidArgumentException'); $this->expectExceptionMessage('Option `className` is not present.'); $object = new class { use ResolverAwareTrait; - public function getConfig() + public function getConfig(): array { return []; } @@ -105,7 +105,7 @@ public function getConfig() $object->getResolver(); } - public function testGetResolverNotSet() + public function testGetResolverNotSet(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Resolver has not been set.'); @@ -121,7 +121,7 @@ public function getConfig() $object->getResolver(); } - public function testSetResolver() + public function testSetResolver(): void { $object = new class { use ResolverAwareTrait; diff --git a/tests/TestCase/Identifier/TokenIdentifierTest.php b/tests/TestCase/Identifier/TokenIdentifierTest.php index 73baf3d5..a54874b8 100644 --- a/tests/TestCase/Identifier/TokenIdentifierTest.php +++ b/tests/TestCase/Identifier/TokenIdentifierTest.php @@ -28,7 +28,7 @@ class TokenIdentifierTest extends TestCase * * @return void */ - public function testIdentify() + public function testIdentify(): void { $resolver = $this->createMock(ResolverInterface::class); @@ -58,7 +58,7 @@ public function testIdentify() * * @return void */ - public function testIdentifyMissingData() + public function testIdentifyMissingData(): void { $resolver = $this->createMock(ResolverInterface::class); @@ -77,7 +77,7 @@ public function testIdentifyMissingData() * * @return void */ - public function testIdentifyHashed() + public function testIdentifyHashed(): void { $resolver = $this->createMock(ResolverInterface::class); diff --git a/tests/TestCase/IdentityTest.php b/tests/TestCase/IdentityTest.php index 4f8ba363..6215c324 100644 --- a/tests/TestCase/IdentityTest.php +++ b/tests/TestCase/IdentityTest.php @@ -29,7 +29,7 @@ class IdentityTest extends TestCase * * @return void */ - public function testGetIdentifier() + public function testGetIdentifier(): void { $data = [ 'id' => 1, @@ -66,7 +66,7 @@ public function testGet(): void * * @return void */ - public function testFieldMapping() + public function testFieldMapping(): void { $data = [ 'id' => 1, @@ -99,7 +99,7 @@ public function testFieldMapping() * * @return void */ - public function testOffsetUnsetError() + public function testOffsetUnsetError(): void { $this->expectException(BadMethodCallException::class); $data = [ @@ -116,7 +116,7 @@ public function testOffsetUnsetError() * * @return void */ - public function testOffsetSetError() + public function testOffsetSetError(): void { $this->expectException(BadMethodCallException::class); $data = [ @@ -129,7 +129,7 @@ public function testOffsetSetError() /** * Test array data. */ - public function testBuildArray() + public function testBuildArray(): void { $data = ['username' => 'robert']; $identity = new Identity($data); @@ -141,7 +141,7 @@ public function testBuildArray() * * @return void */ - public function testGetOriginalData() + public function testGetOriginalData(): void { $data = new ArrayObject(['email' => 'info@cakephp.org']); diff --git a/tests/TestCase/Middleware/AuthenticationMiddlewareTest.php b/tests/TestCase/Middleware/AuthenticationMiddlewareTest.php index b1d14ffa..60426fe7 100644 --- a/tests/TestCase/Middleware/AuthenticationMiddlewareTest.php +++ b/tests/TestCase/Middleware/AuthenticationMiddlewareTest.php @@ -59,7 +59,7 @@ class AuthenticationMiddlewareTest extends TestCase /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); $this->service = new AuthenticationService([ @@ -72,7 +72,7 @@ public function setUp(): void $this->application = new Application('config'); } - public function testApplicationAuthentication() + public function testApplicationAuthentication(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -91,7 +91,7 @@ public function testApplicationAuthentication() $this->assertTrue($service->authenticators()->has('Form')); } - public function testProviderAuthentication() + public function testProviderAuthentication(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -117,7 +117,7 @@ public function testProviderAuthentication() $this->assertTrue($service->authenticators()->has('Form')); } - public function testApplicationAuthenticationRequestResponse() + public function testApplicationAuthenticationRequestResponse(): void { $request = ServerRequestFactory::fromGlobals(); $handler = new TestRequestHandler(); @@ -147,7 +147,7 @@ public function testApplicationAuthenticationRequestResponse() * * @return void */ - public function testSuccessfulAuthentication() + public function testSuccessfulAuthentication(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -171,7 +171,7 @@ public function testSuccessfulAuthentication() * * @return void */ - public function testAuthenticationAndClearIdentityInteraction() + public function testAuthenticationAndClearIdentityInteraction(): void { $request = ServerRequestFactory::fromGlobals([ 'REQUEST_URI' => '/testpath', @@ -206,7 +206,7 @@ public function testAuthenticationAndClearIdentityInteraction() * * @return void */ - public function testSuccessfulAuthenticationWithCustomIdentityAttribute() + public function testSuccessfulAuthenticationWithCustomIdentityAttribute(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -221,6 +221,7 @@ public function testSuccessfulAuthenticationWithCustomIdentityAttribute() $middleware = new AuthenticationMiddleware($this->service); $middleware->process($request, $handler); + $identity = $handler->request->getAttribute('customIdentity'); $service = $handler->request->getAttribute('authentication'); @@ -234,7 +235,7 @@ public function testSuccessfulAuthenticationWithCustomIdentityAttribute() * * @return void */ - public function testSuccessfulAuthenticationApplicationHook() + public function testSuccessfulAuthenticationApplicationHook(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -246,6 +247,7 @@ public function testSuccessfulAuthenticationApplicationHook() $middleware = new AuthenticationMiddleware($this->application); $middleware->process($request, $handler); + $identity = $handler->request->getAttribute('identity'); $service = $handler->request->getAttribute('authentication'); @@ -259,7 +261,7 @@ public function testSuccessfulAuthenticationApplicationHook() * * @return void */ - public function testSuccessfulAuthenticationPersistIdentity() + public function testSuccessfulAuthenticationPersistIdentity(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -274,7 +276,7 @@ public function testSuccessfulAuthenticationPersistIdentity() ]); $middleware = new AuthenticationMiddleware($this->service); - $handler = new TestRequestHandler(function ($request) { + $handler = new TestRequestHandler(function ($request): Response { $request->getAttribute('authentication'); $this->assertNull($request->getAttribute('session')->read('Auth')); @@ -293,7 +295,7 @@ public function testSuccessfulAuthenticationPersistIdentity() * * @return void */ - public function testNonSuccessfulAuthentication() + public function testNonSuccessfulAuthentication(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -305,6 +307,7 @@ public function testNonSuccessfulAuthentication() $middleware = new AuthenticationMiddleware($this->service); $middleware->process($request, $handler); + $identity = $handler->request->getAttribute('identity'); $service = $handler->request->getAttribute('authentication'); @@ -318,7 +321,7 @@ public function testNonSuccessfulAuthentication() * * @return void */ - public function testNonSuccessfulAuthenticationWithChallenge() + public function testNonSuccessfulAuthenticationWithChallenge(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath', 'SERVER_NAME' => 'localhost'], @@ -347,14 +350,14 @@ public function testNonSuccessfulAuthenticationWithChallenge() * * @return void */ - public function testUnauthenticatedNoRedirectMiddlewareConfiguration() + public function testUnauthenticatedNoRedirectMiddlewareConfiguration(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], [], ['username' => 'mariano', 'password' => 'password'], ); - $handler = new TestRequestHandler(function ($request) { + $handler = new TestRequestHandler(function ($request): void { throw new UnauthenticatedException(); }); @@ -363,6 +366,7 @@ public function testUnauthenticatedNoRedirectMiddlewareConfiguration() $service = $this->service; $service->setConfig(['unauthenticatedRedirect' => null]); + $middleware = new AuthenticationMiddleware($service); $middleware->process($request, $handler); } @@ -372,7 +376,7 @@ public function testUnauthenticatedNoRedirectMiddlewareConfiguration() * * @return void */ - public function testUnauthenticatedNoRedirect() + public function testUnauthenticatedNoRedirect(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -383,7 +387,7 @@ public function testUnauthenticatedNoRedirect() $this->expectException(UnauthenticatedException::class); $this->expectExceptionCode(401); - $handler = new TestRequestHandler(function () { + $handler = new TestRequestHandler(function (): void { throw new UnauthenticatedException(); }); $middleware = new AuthenticationMiddleware($this->service); @@ -395,14 +399,14 @@ public function testUnauthenticatedNoRedirect() * * @return void */ - public function testUnauthenticatedRedirect() + public function testUnauthenticatedRedirect(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], [], ['username' => 'mariano', 'password' => 'password'], ); - $handler = new TestRequestHandler(function ($request) { + $handler = new TestRequestHandler(function ($request): void { throw new UnauthenticatedException(); }); @@ -421,14 +425,14 @@ public function testUnauthenticatedRedirect() * * @return void */ - public function testUnauthenticatedRedirectWithQueryBackwardsCompatible() + public function testUnauthenticatedRedirectWithQueryBackwardsCompatible(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], [], ['username' => 'mariano', 'password' => 'password'], ); - $handler = new TestRequestHandler(function ($request) { + $handler = new TestRequestHandler(function ($request): void { throw new UnauthenticatedException(); }); @@ -449,14 +453,14 @@ public function testUnauthenticatedRedirectWithQueryBackwardsCompatible() * * @return void */ - public function testUnauthenticatedRedirectWithExistingQuery() + public function testUnauthenticatedRedirectWithExistingQuery(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], [], ['username' => 'mariano', 'password' => 'password'], ); - $handler = new TestRequestHandler(function ($request) { + $handler = new TestRequestHandler(function ($request): void { throw new UnauthenticatedException(); }); @@ -477,7 +481,7 @@ public function testUnauthenticatedRedirectWithExistingQuery() * * @return void */ - public function testUnauthenticatedRedirectWithFragment() + public function testUnauthenticatedRedirectWithFragment(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -487,7 +491,7 @@ public function testUnauthenticatedRedirectWithFragment() $middleware = new AuthenticationMiddleware($this->service); - $handler = new TestRequestHandler(function ($request) { + $handler = new TestRequestHandler(function ($request): void { throw new UnauthenticatedException(); }); @@ -511,7 +515,7 @@ public function testUnauthenticatedRedirectWithFragment() * * @return void */ - public function testUnauthenticatedRedirectWithBase() + public function testUnauthenticatedRedirectWithBase(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath'], @@ -519,7 +523,8 @@ public function testUnauthenticatedRedirectWithBase() ['username' => 'mariano', 'password' => 'password'], ); $request = $request->withAttribute('base', '/base'); - $handler = new TestRequestHandler(function ($request) { + + $handler = new TestRequestHandler(function ($request): void { throw new UnauthenticatedException(); }); @@ -540,7 +545,7 @@ public function testUnauthenticatedRedirectWithBase() * * @return void */ - public function testUnauthenticatedRedirectWithQueryStringData() + public function testUnauthenticatedRedirectWithQueryStringData(): void { $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/testpath', 'QUERY_STRING' => 'a=b&c=d'], @@ -553,7 +558,7 @@ public function testUnauthenticatedRedirectWithQueryStringData() 'queryParam' => 'redirect', ]); - $handler = new TestRequestHandler(function ($request) { + $handler = new TestRequestHandler(function ($request): void { throw new UnauthenticatedException(); }); $middleware = new AuthenticationMiddleware($this->service); @@ -569,7 +574,7 @@ public function testUnauthenticatedRedirectWithQueryStringData() * * @return void */ - public function testJwtTokenAuthorizationThroughTheMiddlewareStack() + public function testJwtTokenAuthorizationThroughTheMiddlewareStack(): void { $data = [ 'sub' => 3, @@ -598,6 +603,7 @@ public function testJwtTokenAuthorizationThroughTheMiddlewareStack() $middleware = new AuthenticationMiddleware($this->service); $middleware->process($request, $handler); + $identity = $handler->request->getAttribute('identity'); $service = $handler->request->getAttribute('authentication'); @@ -612,7 +618,7 @@ public function testJwtTokenAuthorizationThroughTheMiddlewareStack() * * @return void */ - public function testCookieAuthorizationThroughTheMiddlewareStack() + public function testCookieAuthorizationThroughTheMiddlewareStack(): void { $this->service = new AuthenticationService([ 'authenticators' => [ diff --git a/tests/TestCase/PasswordHasher/DefaultPasswordHasherTest.php b/tests/TestCase/PasswordHasher/DefaultPasswordHasherTest.php index e9728337..5eb58f01 100644 --- a/tests/TestCase/PasswordHasher/DefaultPasswordHasherTest.php +++ b/tests/TestCase/PasswordHasher/DefaultPasswordHasherTest.php @@ -29,7 +29,7 @@ class DefaultPasswordHasherTest extends TestCase * * @return void */ - public function testNeedsRehash() + public function testNeedsRehash(): void { $hasher = new DefaultPasswordHasher(); $this->assertTrue($hasher->needsRehash(md5('foo'))); @@ -43,7 +43,7 @@ public function testNeedsRehash() * * @return void */ - public function testNeedsRehashWithDifferentOptions() + public function testNeedsRehashWithDifferentOptions(): void { $defaultHasher = new DefaultPasswordHasher(['hashType' => PASSWORD_BCRYPT, 'hashOptions' => ['cost' => 10]]); $updatedHasher = new DefaultPasswordHasher(['hashType' => PASSWORD_BCRYPT, 'hashOptions' => ['cost' => 12]]); diff --git a/tests/TestCase/PasswordHasher/FallbackPasswordHasherTest.php b/tests/TestCase/PasswordHasher/FallbackPasswordHasherTest.php index 61a78840..40a23853 100644 --- a/tests/TestCase/PasswordHasher/FallbackPasswordHasherTest.php +++ b/tests/TestCase/PasswordHasher/FallbackPasswordHasherTest.php @@ -30,7 +30,7 @@ class FallbackPasswordHasherTest extends TestCase * * @return void */ - public function testHash() + public function testHash(): void { $hasher = new FallbackPasswordHasher(['hashers' => ['Authentication.Legacy', 'Authentication.Default']]); $legacy = new LegacyPasswordHasher(); @@ -46,7 +46,7 @@ public function testHash() * * @return void */ - public function testCheck() + public function testCheck(): void { $hasher = new FallbackPasswordHasher(['hashers' => ['Authentication.Legacy', 'Authentication.Default']]); $legacy = new LegacyPasswordHasher(); @@ -64,7 +64,7 @@ public function testCheck() * * @return void */ - public function testCheckWithConfigs() + public function testCheckWithConfigs(): void { $hasher = new FallbackPasswordHasher(['hashers' => ['Authentication.Default', 'Authentication.Legacy' => ['hashType' => 'md5']]]); $legacy = new LegacyPasswordHasher(['hashType' => 'md5']); @@ -82,7 +82,7 @@ public function testCheckWithConfigs() * * @return void */ - public function testNeedsRehash() + public function testNeedsRehash(): void { $hasher = new FallbackPasswordHasher(['hashers' => ['Authentication.Default', 'Authentication.Legacy']]); $legacy = new LegacyPasswordHasher(); diff --git a/tests/TestCase/PasswordHasher/LegacyPasswordHasherTest.php b/tests/TestCase/PasswordHasher/LegacyPasswordHasherTest.php index b11b7796..f6a83801 100644 --- a/tests/TestCase/PasswordHasher/LegacyPasswordHasherTest.php +++ b/tests/TestCase/PasswordHasher/LegacyPasswordHasherTest.php @@ -29,7 +29,7 @@ class LegacyPasswordHasherTest extends TestCase * * @return void */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -42,7 +42,7 @@ public function setUp(): void * * @return void */ - public function testNeedsRehash() + public function testNeedsRehash(): void { $hasher = new LegacyPasswordHasher(); $this->assertTrue($hasher->needsRehash(md5('foo'))); @@ -59,10 +59,11 @@ public function testNeedsRehash() * * @return void */ - public function testHashAndCheck() + public function testHashAndCheck(): void { $hasher = new LegacyPasswordHasher(); $hasher->setConfig('hashType', 'md5'); + $password = $hasher->hash('foo'); $this->assertTrue($hasher->check('foo', $password)); $this->assertFalse($hasher->check('bar', $password)); diff --git a/tests/TestCase/PasswordHasher/PasswordHasherFactoryTest.php b/tests/TestCase/PasswordHasher/PasswordHasherFactoryTest.php index 9ac007d9..6880ec35 100644 --- a/tests/TestCase/PasswordHasher/PasswordHasherFactoryTest.php +++ b/tests/TestCase/PasswordHasher/PasswordHasherFactoryTest.php @@ -15,8 +15,10 @@ */ namespace Authentication\Test\TestCase\PasswordHasher; +use Authentication\PasswordHasher\DefaultPasswordHasher; use Authentication\PasswordHasher\PasswordHasherFactory; use Cake\TestSuite\TestCase; +use TestPlugin\PasswordHasher\LegacyPasswordHasher; /** * Test case for PasswordHasherFactory @@ -28,21 +30,21 @@ class PasswordHasherFactoryTest extends TestCase * * @return void */ - public function testBuild() + public function testBuild(): void { $hasher = PasswordHasherFactory::build('Authentication.Default'); - $this->assertInstanceof('Authentication\PasswordHasher\DefaultPasswordHasher', $hasher); + $this->assertInstanceof(DefaultPasswordHasher::class, $hasher); $hasher = PasswordHasherFactory::build([ 'className' => 'Authentication.Default', 'hashOptions' => ['foo' => 'bar'], ]); - $this->assertInstanceof('Authentication\PasswordHasher\DefaultPasswordHasher', $hasher); + $this->assertInstanceof(DefaultPasswordHasher::class, $hasher); $this->assertEquals(['foo' => 'bar'], $hasher->getConfig('hashOptions')); $this->loadPlugins(['TestPlugin']); $hasher = PasswordHasherFactory::build('TestPlugin.Legacy'); - $this->assertInstanceof('TestPlugin\PasswordHasher\LegacyPasswordHasher', $hasher); + $this->assertInstanceof(LegacyPasswordHasher::class, $hasher); } /** @@ -50,7 +52,7 @@ public function testBuild() * * @return void */ - public function testBuildMissingHasher() + public function testBuildMissingHasher(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Password hasher class `FooBar` was not found.'); @@ -62,7 +64,7 @@ public function testBuildMissingHasher() * * @return void */ - public function testBuildInvalidHasher() + public function testBuildInvalidHasher(): void { $this->expectException('RuntimeException'); $this->expectExceptionMessage('Password hasher must implement PasswordHasherInterface.'); diff --git a/tests/TestCase/PasswordHasher/PasswordHasherTraitTest.php b/tests/TestCase/PasswordHasher/PasswordHasherTraitTest.php index 268af66d..bf48a3c2 100644 --- a/tests/TestCase/PasswordHasher/PasswordHasherTraitTest.php +++ b/tests/TestCase/PasswordHasher/PasswordHasherTraitTest.php @@ -32,7 +32,7 @@ class PasswordHasherTraitTest extends TestCase * * @return void */ - public function testGetPasswordHasher() + public function testGetPasswordHasher(): void { $object = new class { use PasswordHasherTrait; @@ -47,7 +47,7 @@ public function testGetPasswordHasher() * * @return void */ - public function testSetPasswordHasher() + public function testSetPasswordHasher(): void { $hasher = $this->createMock(PasswordHasherInterface::class); $object = new class { @@ -55,6 +55,7 @@ public function testSetPasswordHasher() }; $object->setPasswordHasher($hasher); + $passwordHasher = $object->getPasswordHasher(); $this->assertSame($hasher, $passwordHasher); } diff --git a/tests/TestCase/UrlChecker/DefaultUrlCheckerTest.php b/tests/TestCase/UrlChecker/DefaultUrlCheckerTest.php index a0be5877..ebfc01e1 100644 --- a/tests/TestCase/UrlChecker/DefaultUrlCheckerTest.php +++ b/tests/TestCase/UrlChecker/DefaultUrlCheckerTest.php @@ -19,6 +19,7 @@ use Authentication\Test\TestCase\AuthenticationTestCase as TestCase; use Authentication\UrlChecker\DefaultUrlChecker; use Cake\Http\ServerRequestFactory; +use Cake\Routing\Exception\MissingRouteException; use Cake\Routing\Router; /** @@ -29,7 +30,7 @@ class DefaultUrlCheckerTest extends TestCase /** * @inheritDoc */ - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -57,7 +58,7 @@ public function setUp(): void * * @return void */ - public function testCheckSimple() + public function testCheckSimple(): void { $checker = new DefaultUrlChecker(); $request = ServerRequestFactory::fromGlobals( @@ -75,7 +76,7 @@ public function testCheckSimple() * * @return void */ - public function testCheckFullUrls() + public function testCheckFullUrls(): void { $url = [ 'controller' => 'users', @@ -127,7 +128,7 @@ public function testCheckFullUrls() * * @return void */ - public function testStringUrl() + public function testStringUrl(): void { $checker = new DefaultUrlChecker(); $request = ServerRequestFactory::fromGlobals( @@ -148,7 +149,7 @@ public function testStringUrl() * * @return void */ - public function testNamedRoute() + public function testNamedRoute(): void { $checker = new DefaultUrlChecker(); $request = ServerRequestFactory::fromGlobals( @@ -161,9 +162,9 @@ public function testNamedRoute() /** * testInvalidNamedRoute */ - public function testInvalidNamedRoute() + public function testInvalidNamedRoute(): void { - $this->expectException('Cake\Routing\Exception\MissingRouteException'); + $this->expectException(MissingRouteException::class); $checker = new DefaultUrlChecker(); $request = ServerRequestFactory::fromGlobals( ['REQUEST_URI' => '/login'], diff --git a/tests/TestCase/UrlChecker/StringUrlCheckerTest.php b/tests/TestCase/UrlChecker/StringUrlCheckerTest.php index f865bc27..9784a74a 100644 --- a/tests/TestCase/UrlChecker/StringUrlCheckerTest.php +++ b/tests/TestCase/UrlChecker/StringUrlCheckerTest.php @@ -30,7 +30,7 @@ class StringUrlCheckerTest extends TestCase * * @return void */ - public function testCheckFailure() + public function testCheckFailure(): void { $checker = new StringUrlChecker(); @@ -47,7 +47,7 @@ public function testCheckFailure() * * @return void */ - public function testCheckSimple() + public function testCheckSimple(): void { $checker = new StringUrlChecker(); $request = ServerRequestFactory::fromGlobals( @@ -65,7 +65,7 @@ public function testCheckSimple() * * @return void */ - public function testCheckRegexp() + public function testCheckRegexp(): void { $checker = new StringUrlChecker(); $request = ServerRequestFactory::fromGlobals( @@ -83,7 +83,7 @@ public function testCheckRegexp() * * @return void */ - public function testCheckFull() + public function testCheckFull(): void { $checker = new StringUrlChecker(); $request = ServerRequestFactory::fromGlobals( @@ -101,7 +101,7 @@ public function testCheckFull() * * @return void */ - public function testCheckBase() + public function testCheckBase(): void { $checker = new StringUrlChecker(); $request = ServerRequestFactory::fromGlobals( diff --git a/tests/TestCase/View/Helper/IdentityHelperTest.php b/tests/TestCase/View/Helper/IdentityHelperTest.php index b41f0162..584336d3 100644 --- a/tests/TestCase/View/Helper/IdentityHelperTest.php +++ b/tests/TestCase/View/Helper/IdentityHelperTest.php @@ -32,7 +32,7 @@ class IdentityHelperTest extends TestCase * * @return void */ - public function testWithIdentity() + public function testWithIdentity(): void { $identity = new Identity([ 'id' => 1, @@ -56,7 +56,7 @@ public function testWithIdentity() $this->assertFalse($helper->is(2)); } - public function testIdentityWithCustomAttribute() + public function testIdentityWithCustomAttribute(): void { $identity = new Identity([ 'id' => 1, @@ -77,7 +77,7 @@ public function testIdentityWithCustomAttribute() * * @return void */ - public function testWithOutIdentity() + public function testWithOutIdentity(): void { $request = new ServerRequest(); $view = new View($request); @@ -94,7 +94,7 @@ public function testWithOutIdentity() $this->assertNull($helper->getIdentity()); } - public function testGetIdentity() + public function testGetIdentity(): void { $identity = new Identity([ 'id' => 1, diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 002405fd..6cea8bed 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -24,10 +24,10 @@ use Cake\Utility\Security; use function Cake\Core\env; -$findRoot = function ($root) { +$findRoot = function ($root): string { do { $lastRoot = $root; - $root = dirname($root); + $root = dirname((string)$root); if (is_dir($root . '/vendor/cakephp/cakephp')) { return $root; } @@ -38,7 +38,7 @@ unset($findRoot); chdir($root); -require_once 'vendor/autoload.php'; +require_once __DIR__ . '/../vendor/autoload.php'; define('ROOT', $root . DS . 'tests' . DS . 'test_app' . DS); define('APP', ROOT . 'App' . DS); diff --git a/tests/test_app/TestApp/Application.php b/tests/test_app/TestApp/Application.php index 9dbe9f36..b4848789 100644 --- a/tests/test_app/TestApp/Application.php +++ b/tests/test_app/TestApp/Application.php @@ -27,7 +27,7 @@ public function middleware(MiddlewareQueue $middleware): MiddlewareQueue return $middleware; } - public function authentication(AuthenticationServiceInterface $service) + public function authentication(AuthenticationServiceInterface $service): AuthenticationServiceInterface { $service->loadAuthenticator('Authentication.Form', [ 'identifier' => 'Authentication.Password', @@ -36,7 +36,7 @@ public function authentication(AuthenticationServiceInterface $service) return $service; } - public function authenticationApi(AuthenticationServiceInterface $service) + public function authenticationApi(AuthenticationServiceInterface $service): AuthenticationServiceInterface { $service->loadAuthenticator('Authentication.Token', [ 'identifier' => 'Authentication.Token', diff --git a/tests/test_app/TestApp/Callback/MyCallback.php b/tests/test_app/TestApp/Callback/MyCallback.php index 2a7f331d..cf726c0a 100644 --- a/tests/test_app/TestApp/Callback/MyCallback.php +++ b/tests/test_app/TestApp/Callback/MyCallback.php @@ -17,7 +17,7 @@ class MyCallback { - public static function callme($data) + public static function callme($data): Entity { return new Entity(); } diff --git a/tests/test_app/TestApp/Http/TestRequestHandler.php b/tests/test_app/TestApp/Http/TestRequestHandler.php index b63b7e73..ede54da5 100644 --- a/tests/test_app/TestApp/Http/TestRequestHandler.php +++ b/tests/test_app/TestApp/Http/TestRequestHandler.php @@ -21,13 +21,16 @@ class TestRequestHandler implements RequestHandlerInterface { + /** + * @var callable + */ public $callable; public $request; public function __construct(?callable $callable = null) { - $this->callable = $callable ?: function ($request) { + $this->callable = $callable ?: function ($request): Response { return new Response(); }; }