From f77a9bc242d4e296ab7db233d3af1e383ee0a8fe Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 31 Dec 2024 14:39:43 +0100 Subject: [PATCH 1/2] fix code style issues --- src/Controller/Connect/AbstractController.php | 4 +-- src/Controller/Connect/ConnectController.php | 5 +-- src/Controller/Connect/RegisterController.php | 11 ++++--- src/Controller/LoginController.php | 5 +-- .../RedirectToServiceController.php | 5 +-- .../ResourceOwnerCompilerPass.php | 5 +-- src/DependencyInjection/Configuration.php | 8 +++-- src/DependencyInjection/HWIOAuthExtension.php | 17 ++++++---- .../Factory/OAuthAuthenticatorFactory.php | 7 ++-- src/HWIOAuthBundle.php | 3 +- .../Exception/HttpTransportException.php | 3 +- .../Exception/StateRetrievalException.php | 6 ++-- .../RequestDataStorage/SessionStorage.php | 10 +++--- .../ResourceOwner/AbstractResourceOwner.php | 8 +++-- .../ResourceOwner/AppleResourceOwner.php | 10 +++--- .../ResourceOwner/AzureResourceOwner.php | 9 ++--- .../ResourceOwner/DropboxResourceOwner.php | 2 +- .../GenericOAuth1ResourceOwner.php | 10 +++--- .../GenericOAuth2ResourceOwner.php | 7 ++-- .../ResourceOwner/GitHubResourceOwner.php | 2 +- .../OdnoklassnikiResourceOwner.php | 4 +-- src/OAuth/ResourceOwner/QQResourceOwner.php | 2 +- .../ResourceOwner/RedditResourceOwner.php | 2 +- .../ResourceOwner/TelegramResourceOwner.php | 2 +- src/OAuth/ResourceOwnerInterface.php | 3 +- src/OAuth/Response/AbstractUserResponse.php | 3 +- src/OAuth/Response/PathUserResponse.php | 6 ++-- .../Response/SensioConnectUserResponse.php | 33 +++++++++++-------- src/OAuth/State/State.php | 12 ++++--- .../Authentication/Provider/OAuthProvider.php | 4 +-- .../Token/AbstractOAuthToken.php | 5 +-- .../Exception/AccountNotLinkedException.php | 2 +- src/Security/Core/User/EntityUserProvider.php | 11 ++++--- src/Security/Core/User/OAuthUserProvider.php | 2 +- .../Http/Authenticator/OAuthAuthenticator.php | 10 +++--- .../Http/EntryPoint/OAuthEntryPoint.php | 5 +-- src/Security/Http/Firewall/OAuthListener.php | 2 +- .../Firewall/RefreshAccessTokenListener.php | 9 ++--- .../RefreshAccessTokenListenerOld.php | 2 +- src/Security/Http/ResourceOwnerMap.php | 2 +- src/Security/OAuthErrorHandler.php | 2 +- src/Security/OAuthUtils.php | 17 +++++----- .../GenericOAuth1ResourceOwnerTestCase.php | 3 +- .../GenericOAuth2ResourceOwnerTestCase.php | 8 +++-- .../ResourceOwner/ResourceOwnerTestCase.php | 5 +-- tests/App/AppKernel.php | 3 +- .../Connect/ConnectControllerTest.php | 2 +- .../Connect/RegistrationControllerTest.php | 7 ++-- .../HWIOAuthExtensionTest.php | 7 ++-- tests/Fixtures/OAuthAwareException.php | 3 +- .../RequestDataStorage/SessionStorageTest.php | 10 +++--- .../ResourceOwner/AppleResourceOwnerTest.php | 5 +-- .../TelegramResourceOwnerTest.php | 2 +- tests/OAuth/Response/PathUserResponseTest.php | 3 +- tests/OAuth/State/StateTest.php | 3 +- .../Provider/OAuthProviderTest.php | 2 +- .../Core/User/EntityUserProviderTest.php | 3 +- .../Authenticator/OAuthAuthenticatorTest.php | 2 +- tests/Security/OAuthUtilsTest.php | 7 ++-- 59 files changed, 206 insertions(+), 146 deletions(-) diff --git a/src/Controller/Connect/AbstractController.php b/src/Controller/Connect/AbstractController.php index 0d4ef1528..b0dfb0162 100644 --- a/src/Controller/Connect/AbstractController.php +++ b/src/Controller/Connect/AbstractController.php @@ -57,7 +57,7 @@ public function __construct( TokenStorageInterface $tokenStorage, UserCheckerInterface $userChecker, Environment $twig, - ?AccountConnectorInterface $accountConnector + ?AccountConnectorInterface $accountConnector, ) { $this->resourceOwnerMapLocator = $resourceOwnerMapLocator; $this->requestStack = $requestStack; @@ -81,7 +81,7 @@ protected function getResourceOwnerByName(string $name): ResourceOwnerInterface } } - throw new NotFoundHttpException(sprintf("No resource owner with name '%s'.", $name)); + throw new NotFoundHttpException(\sprintf("No resource owner with name '%s'.", $name)); } /** diff --git a/src/Controller/Connect/ConnectController.php b/src/Controller/Connect/ConnectController.php index 481174c44..e45a1602c 100644 --- a/src/Controller/Connect/ConnectController.php +++ b/src/Controller/Connect/ConnectController.php @@ -11,6 +11,7 @@ namespace HWI\Bundle\OAuthBundle\Controller\Connect; +use Exception; use HWI\Bundle\OAuthBundle\Connect\AccountConnectorInterface; use HWI\Bundle\OAuthBundle\Event\GetResponseUserEvent; use HWI\Bundle\OAuthBundle\HWIOAuthEvents; @@ -62,7 +63,7 @@ public function __construct( bool $failedUseReferer, string $failedAuthPath, bool $enableConnectConfirmation, - ?AccountConnectorInterface $accountConnector + ?AccountConnectorInterface $accountConnector, ) { parent::__construct( $resourceOwnerMapLocator, @@ -89,7 +90,7 @@ public function __construct( * * @param string $service name of the resource owner to connect to * - * @throws \Exception + * @throws Exception * @throws NotFoundHttpException if `connect` functionality was not enabled * @throws AccessDeniedException if no user is authenticated */ diff --git a/src/Controller/Connect/RegisterController.php b/src/Controller/Connect/RegisterController.php index c90e37d35..58137b057 100644 --- a/src/Controller/Connect/RegisterController.php +++ b/src/Controller/Connect/RegisterController.php @@ -11,6 +11,7 @@ namespace HWI\Bundle\OAuthBundle\Controller\Connect; +use Exception; use HWI\Bundle\OAuthBundle\Connect\AccountConnectorInterface; use HWI\Bundle\OAuthBundle\Event\FilterUserResponseEvent; use HWI\Bundle\OAuthBundle\Event\FormEvent; @@ -19,6 +20,8 @@ use HWI\Bundle\OAuthBundle\HWIOAuthEvents; use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException; use HWI\Bundle\OAuthBundle\Security\Http\ResourceOwnerMapLocator; +use InvalidArgumentException; +use RuntimeException; use Symfony\Component\Form\FormFactoryInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; @@ -58,7 +61,7 @@ public function __construct( string $grantRule, ?string $registrationForm, ?AccountConnectorInterface $accountConnector, - ?RegistrationFormHandlerInterface $formHandler + ?RegistrationFormHandlerInterface $formHandler, ) { parent::__construct( $resourceOwnerMapLocator, @@ -85,7 +88,7 @@ public function __construct( * * @throws NotFoundHttpException if `connect` functionality was not enabled * @throws AccessDeniedException if any user is authenticated - * @throws \RuntimeException + * @throws RuntimeException */ public function registrationAction(Request $request, string $key): Response { @@ -109,11 +112,11 @@ public function registrationAction(Request $request, string $key): Response } if (!$error instanceof AccountNotLinkedException) { - throw new \RuntimeException('Cannot register an account.', 0, $error instanceof \Exception ? $error : null); + throw new RuntimeException('Cannot register an account.', 0, $error instanceof Exception ? $error : null); } if (!$this->registrationForm) { - throw new \InvalidArgumentException('Registration form class must be set.'); + throw new InvalidArgumentException('Registration form class must be set.'); } $userInformation = $this diff --git a/src/Controller/LoginController.php b/src/Controller/LoginController.php index fc22c7d39..8a0e344b0 100644 --- a/src/Controller/LoginController.php +++ b/src/Controller/LoginController.php @@ -12,6 +12,7 @@ namespace HWI\Bundle\OAuthBundle\Controller; use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException; +use LogicException; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; @@ -46,7 +47,7 @@ public function __construct( RequestStack $requestStack, Environment $twig, bool $connect, - string $grantRule + string $grantRule, ) { $this->authenticationUtils = $authenticationUtils; $this->router = $router; @@ -61,7 +62,7 @@ public function __construct( * Action that handles the login 'form'. If connecting is enabled the * user will be redirected to the appropriate login urls or registration forms. * - * @throws \LogicException + * @throws LogicException */ public function connectAction(Request $request): Response { diff --git a/src/Controller/RedirectToServiceController.php b/src/Controller/RedirectToServiceController.php index 06585acc0..13e2a11c4 100644 --- a/src/Controller/RedirectToServiceController.php +++ b/src/Controller/RedirectToServiceController.php @@ -14,6 +14,7 @@ use HWI\Bundle\OAuthBundle\Security\Http\ResourceOwnerMapLocator; use HWI\Bundle\OAuthBundle\Security\OAuthUtils; use HWI\Bundle\OAuthBundle\Util\DomainWhitelist; +use RuntimeException; use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; @@ -33,7 +34,7 @@ public function __construct( private readonly ResourceOwnerMapLocator $resourceOwnerMapLocator, private readonly ?string $targetPathParameter, private readonly bool $failedUseReferer, - private readonly bool $useReferer + private readonly bool $useReferer, ) { } @@ -44,7 +45,7 @@ public function redirectToServiceAction(Request $request, string $service): Redi { try { $authorizationUrl = $this->oauthUtils->getAuthorizationUrl($request, $service); - } catch (\RuntimeException $e) { + } catch (RuntimeException $e) { throw new NotFoundHttpException($e->getMessage(), $e); } diff --git a/src/DependencyInjection/CompilerPass/ResourceOwnerCompilerPass.php b/src/DependencyInjection/CompilerPass/ResourceOwnerCompilerPass.php index aa642edb3..bc822b972 100644 --- a/src/DependencyInjection/CompilerPass/ResourceOwnerCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/ResourceOwnerCompilerPass.php @@ -13,6 +13,7 @@ use HWI\Bundle\OAuthBundle\DependencyInjection\Configuration; use HWI\Bundle\OAuthBundle\DependencyInjection\HWIOAuthExtension; +use InvalidArgumentException; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -75,9 +76,9 @@ private function registerResourceOwnerTypeClassParameters(ContainerBuilder $cont } if (!Configuration::isResourceOwnerSupported($match['type'])) { - $e = new \InvalidArgumentException(sprintf('Unknown resource owner type "%s"', $match['type'])); + $e = new InvalidArgumentException(\sprintf('Unknown resource owner type "%s"', $match['type'])); - throw new InvalidConfigurationException(sprintf('Invalid configuration for path "hwi_oauth.resource_owners.%s.type": %s', $resourceOwnerName, $e->getMessage()), $e->getCode(), $e); + throw new InvalidConfigurationException(\sprintf('Invalid configuration for path "hwi_oauth.resource_owners.%s.type": %s', $resourceOwnerName, $e->getMessage()), $e->getCode(), $e); } } } diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index dea103330..b59cafc55 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -14,6 +14,8 @@ use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\GenericOAuth1ResourceOwner; use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\GenericOAuth2ResourceOwner; use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface; +use LogicException; +use ReflectionClass; use Symfony\Component\Config\Definition\BaseNode; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; @@ -73,9 +75,9 @@ public static function isResourceOwnerSupported(string $resourceOwner): bool public static function registerResourceOwner(string $resourceOwnerClass): void { - $reflection = new \ReflectionClass($resourceOwnerClass); + $reflection = new ReflectionClass($resourceOwnerClass); if (!$reflection->implementsInterface(ResourceOwnerInterface::class)) { - throw new \LogicException('Resource owner class should implement "ResourceOwnerInterface", or extended class "GenericOAuth1ResourceOwner"/"GenericOAuth2ResourceOwner".'); + throw new LogicException('Resource owner class should implement "ResourceOwnerInterface", or extended class "GenericOAuth1ResourceOwner"/"GenericOAuth2ResourceOwner".'); } $type = \defined("$resourceOwnerClass::TYPE") ? $resourceOwnerClass::TYPE : null; @@ -83,7 +85,7 @@ public static function registerResourceOwner(string $resourceOwnerClass): void if (preg_match('~(?P[^\\\\]+)ResourceOwner$~', $resourceOwnerClass, $match)) { $type = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $match['resource_owner'])); } else { - throw new \LogicException(sprintf('Resource owner class either should have "TYPE" const defined or end with "ResourceOwner" so that type can be calculated by converting its class name without suffix to "snake_case". Given class name is "%s"', $resourceOwnerClass)); + throw new LogicException(\sprintf('Resource owner class either should have "TYPE" const defined or end with "ResourceOwner" so that type can be calculated by converting its class name without suffix to "snake_case". Given class name is "%s"', $resourceOwnerClass)); } } diff --git a/src/DependencyInjection/HWIOAuthExtension.php b/src/DependencyInjection/HWIOAuthExtension.php index b4325e7e6..bcdf2764d 100644 --- a/src/DependencyInjection/HWIOAuthExtension.php +++ b/src/DependencyInjection/HWIOAuthExtension.php @@ -11,7 +11,10 @@ namespace HWI\Bundle\OAuthBundle\DependencyInjection; +use ArrayIterator; +use Exception; use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface; +use RuntimeException; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Config\Definition\Processor; use Symfony\Component\Config\FileLocator; @@ -35,15 +38,15 @@ final class HWIOAuthExtension extends Extension { /** - * @var \ArrayIterator + * @var ArrayIterator */ - private \ArrayIterator $firewallNames; + private ArrayIterator $firewallNames; private bool $refreshTokenListenerEnabled = false; public function __construct() { - $this->firewallNames = new \ArrayIterator(); + $this->firewallNames = new ArrayIterator(); } public function getConfiguration(array $config, ContainerBuilder $container): Configuration @@ -54,8 +57,8 @@ public function getConfiguration(array $config, ContainerBuilder $container): Co /** * {@inheritdoc} * - * @throws \Exception - * @throws \RuntimeException + * @throws Exception + * @throws RuntimeException * @throws InvalidConfigurationException * @throws BadMethodCallException * @throws InvalidArgumentException @@ -138,7 +141,7 @@ public function createResourceOwnerService(ContainerBuilder $container, string $ // handle external resource owners with given class if (isset($options['class'])) { if (!is_subclass_of($options['class'], ResourceOwnerInterface::class, true)) { - throw new InvalidConfigurationException(sprintf('Class "%s" must implement interface "HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface".', $options['class'])); + throw new InvalidConfigurationException(\sprintf('Class "%s" must implement interface "HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface".', $options['class'])); } $definition = new Definition($options['class']); @@ -166,7 +169,7 @@ public function getAlias(): string return 'hwi_oauth'; } - public function getFirewallNames(): \ArrayIterator + public function getFirewallNames(): ArrayIterator { return $this->firewallNames; } diff --git a/src/DependencyInjection/Security/Factory/OAuthAuthenticatorFactory.php b/src/DependencyInjection/Security/Factory/OAuthAuthenticatorFactory.php index 615988b46..30523c0e3 100644 --- a/src/DependencyInjection/Security/Factory/OAuthAuthenticatorFactory.php +++ b/src/DependencyInjection/Security/Factory/OAuthAuthenticatorFactory.php @@ -11,6 +11,7 @@ namespace HWI\Bundle\OAuthBundle\DependencyInjection\Security\Factory; +use ArrayIterator; use HWI\Bundle\OAuthBundle\Security\Http\Authenticator\OAuthAuthenticator; use HWI\Bundle\OAuthBundle\Security\Http\Firewall\RefreshAccessTokenListener; use HWI\Bundle\OAuthBundle\Security\Http\Firewall\RefreshAccessTokenListenerOld; @@ -31,7 +32,7 @@ */ final class OAuthAuthenticatorFactory extends AbstractFactory implements AuthenticatorFactoryInterface, FirewallListenerFactoryInterface { - public function __construct(private \ArrayIterator $firewallNames) + public function __construct(private ArrayIterator $firewallNames) { } @@ -58,7 +59,7 @@ public function createAuthenticator( ContainerBuilder $container, string $firewallName, array $config, - string $userProviderId + string $userProviderId, ): string { $authenticatorId = 'security.authenticator.oauth.'.$firewallName; @@ -130,7 +131,7 @@ public function getPosition(): string return 'http'; } - public function getFirewallNames(): \ArrayIterator + public function getFirewallNames(): ArrayIterator { return $this->firewallNames; } diff --git a/src/HWIOAuthBundle.php b/src/HWIOAuthBundle.php index 1deae2c6a..8bb6405e5 100644 --- a/src/HWIOAuthBundle.php +++ b/src/HWIOAuthBundle.php @@ -14,6 +14,7 @@ use HWI\Bundle\OAuthBundle\DependencyInjection\CompilerPass\EnableRefreshOAuthTokenListenerCompilerPass; use HWI\Bundle\OAuthBundle\DependencyInjection\CompilerPass\ResourceOwnerCompilerPass; use HWI\Bundle\OAuthBundle\DependencyInjection\Security\Factory\OAuthAuthenticatorFactory; +use RuntimeException; use Symfony\Bundle\SecurityBundle\DependencyInjection\SecurityExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; @@ -43,7 +44,7 @@ public function build(ContainerBuilder $container): void // Symfony < 5.4 BC layer $extension->addSecurityListenerFactory(new OAuthAuthenticatorFactory($firewallNames)); } else { - throw new \RuntimeException('Unsupported Symfony Security component version'); + throw new RuntimeException('Unsupported Symfony Security component version'); } $container->addCompilerPass(new ResourceOwnerCompilerPass()); diff --git a/src/OAuth/Exception/HttpTransportException.php b/src/OAuth/Exception/HttpTransportException.php index b80348dc7..063799291 100644 --- a/src/OAuth/Exception/HttpTransportException.php +++ b/src/OAuth/Exception/HttpTransportException.php @@ -12,12 +12,13 @@ namespace HWI\Bundle\OAuthBundle\OAuth\Exception; use Symfony\Component\Security\Core\Exception\AuthenticationException; +use Throwable; final class HttpTransportException extends AuthenticationException { private string $ownerName; - public function __construct(string $message, string $ownerName, int $code = 0, ?\Throwable $previous = null) + public function __construct(string $message, string $ownerName, int $code = 0, ?Throwable $previous = null) { parent::__construct($message, $code, $previous); $this->ownerName = $ownerName; diff --git a/src/OAuth/Exception/StateRetrievalException.php b/src/OAuth/Exception/StateRetrievalException.php index 6e9790c72..3e03156ea 100644 --- a/src/OAuth/Exception/StateRetrievalException.php +++ b/src/OAuth/Exception/StateRetrievalException.php @@ -11,13 +11,15 @@ namespace HWI\Bundle\OAuthBundle\OAuth\Exception; -final class StateRetrievalException extends \InvalidArgumentException +use InvalidArgumentException; + +final class StateRetrievalException extends InvalidArgumentException { /** * @param string $key The provided string key */ public static function forKey(string $key): self { - return new static(sprintf('No value found in state for key [%s]', $key)); + return new static(\sprintf('No value found in state for key [%s]', $key)); } } diff --git a/src/OAuth/RequestDataStorage/SessionStorage.php b/src/OAuth/RequestDataStorage/SessionStorage.php index 8e2fb29c8..07799b003 100644 --- a/src/OAuth/RequestDataStorage/SessionStorage.php +++ b/src/OAuth/RequestDataStorage/SessionStorage.php @@ -13,6 +13,8 @@ use HWI\Bundle\OAuthBundle\OAuth\RequestDataStorageInterface; use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface; +use InvalidArgumentException; +use LogicException; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\SessionInterface; @@ -39,7 +41,7 @@ public function fetch(ResourceOwnerInterface $resourceOwner, $key, $type = 'toke { $key = $this->generateKey($resourceOwner, $key, $type); if (null === $data = $this->getSession()->get($key)) { - throw new \InvalidArgumentException('No data available in storage.'); + throw new InvalidArgumentException('No data available in storage.'); } // Request tokens are one time use only @@ -57,7 +59,7 @@ public function save(ResourceOwnerInterface $resourceOwner, $value, $type = 'tok { if ('token' === $type) { if (!\is_array($value) || !isset($value['oauth_token'])) { - throw new \InvalidArgumentException('Invalid request token.'); + throw new InvalidArgumentException('Invalid request token.'); } $key = $this->generateKey($resourceOwner, $value['oauth_token'], 'token'); @@ -73,7 +75,7 @@ public function save(ResourceOwnerInterface $resourceOwner, $value, $type = 'tok */ private function generateKey(ResourceOwnerInterface $resourceOwner, string $key, string $type): string { - return sprintf('_hwi_oauth.%s.%s.%s.%s', $resourceOwner->getName(), $resourceOwner->getOption('client_id'), $type, $key); + return \sprintf('_hwi_oauth.%s.%s.%s.%s', $resourceOwner->getName(), $resourceOwner->getOption('client_id'), $type, $key); } /** @@ -116,6 +118,6 @@ private function getSession(): SessionInterface return $request->getSession(); } - throw new \LogicException('There is currently no session available.'); + throw new LogicException('There is currently no session available.'); } } diff --git a/src/OAuth/ResourceOwner/AbstractResourceOwner.php b/src/OAuth/ResourceOwner/AbstractResourceOwner.php index 8c085bac1..6f0227358 100644 --- a/src/OAuth/ResourceOwner/AbstractResourceOwner.php +++ b/src/OAuth/ResourceOwner/AbstractResourceOwner.php @@ -18,6 +18,7 @@ use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface; use HWI\Bundle\OAuthBundle\OAuth\State\State; use HWI\Bundle\OAuthBundle\OAuth\StateInterface; +use InvalidArgumentException; use Symfony\Component\HttpClient\Exception\JsonException; use Symfony\Component\HttpFoundation\Request as HttpRequest; use Symfony\Component\OptionsResolver\Exception\AccessException; @@ -28,6 +29,7 @@ use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; use Symfony\Contracts\HttpClient\ResponseInterface; +use Throwable; /** * @author Geoffrey Bachelet @@ -60,7 +62,7 @@ public function __construct( HttpUtils $httpUtils, array $options, string $name, - RequestDataStorageInterface $storage + RequestDataStorageInterface $storage, ) { $this->httpClient = $httpClient; $this->httpUtils = $httpUtils; @@ -109,7 +111,7 @@ public function getName() public function getOption($name) { if (!\array_key_exists($name, $this->options)) { - throw new \InvalidArgumentException(sprintf('Unknown option "%s"', $name)); + throw new InvalidArgumentException(\sprintf('Unknown option "%s"', $name)); } return $this->options[$name]; @@ -135,7 +137,7 @@ public function getState(): StateInterface // lazy-loading for stored states try { $storedData = $this->storage->fetch($this, State::class, 'state'); - } catch (\Throwable $e) { + } catch (Throwable $e) { $storedData = null; } if (null !== $storedData && false !== $storedState = unserialize($storedData)) { diff --git a/src/OAuth/ResourceOwner/AppleResourceOwner.php b/src/OAuth/ResourceOwner/AppleResourceOwner.php index 940dbb395..4cbead476 100644 --- a/src/OAuth/ResourceOwner/AppleResourceOwner.php +++ b/src/OAuth/ResourceOwner/AppleResourceOwner.php @@ -14,6 +14,8 @@ use Firebase\JWT\JWT; use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken; use HWI\Bundle\OAuthBundle\Security\OAuthErrorHandler; +use InvalidArgumentException; +use RuntimeException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -52,7 +54,7 @@ public function getAuthorizationUrl($redirectUri, array $extraParameters = []) public function getUserInformation(array $accessToken, array $extraParameters = []) { if (!isset($accessToken['id_token'])) { - throw new \InvalidArgumentException('Undefined index id_token'); + throw new InvalidArgumentException('Undefined index id_token'); } $jwt = self::jwtDecode($accessToken['id_token']); @@ -163,7 +165,7 @@ private static function jwtDecode(string $idToken) $jwt .= '='; break; default: - throw new \InvalidArgumentException('Invalid base64 format sent back'); + throw new InvalidArgumentException('Invalid base64 format sent back'); } return $jwt; @@ -176,11 +178,11 @@ private function getClientSecret(): string } if (!isset($this->options['auth_key'], $this->options['key_id'], $this->options['team_id'])) { - throw new \InvalidArgumentException('Options "auth_key", "key_id" and "team_id" must be defined to use automatic "client_secret" generation.'); + throw new InvalidArgumentException('Options "auth_key", "key_id" and "team_id" must be defined to use automatic "client_secret" generation.'); } if (!class_exists(JWT::class)) { - throw new \RuntimeException('PHP-JWT library is required to use automatic "client_secret" generation. Please try "composer require firebase/php-jwt".'); + throw new RuntimeException('PHP-JWT library is required to use automatic "client_secret" generation. Please try "composer require firebase/php-jwt".'); } $payload = [ diff --git a/src/OAuth/ResourceOwner/AzureResourceOwner.php b/src/OAuth/ResourceOwner/AzureResourceOwner.php index 077e94d5e..0400062a6 100644 --- a/src/OAuth/ResourceOwner/AzureResourceOwner.php +++ b/src/OAuth/ResourceOwner/AzureResourceOwner.php @@ -11,6 +11,7 @@ namespace HWI\Bundle\OAuthBundle\OAuth\ResourceOwner; +use InvalidArgumentException; use Symfony\Component\OptionsResolver\OptionsResolver; /** @@ -38,14 +39,14 @@ final class AzureResourceOwner extends GenericOAuth2ResourceOwner */ public function configure() { - $this->options['access_token_url'] = sprintf($this->options['access_token_url'], $this->options['application']); - $this->options['authorization_url'] = sprintf($this->options['authorization_url'], $this->options['application']); + $this->options['access_token_url'] = \sprintf($this->options['access_token_url'], $this->options['application']); + $this->options['authorization_url'] = \sprintf($this->options['authorization_url'], $this->options['application']); } /** * {@inheritdoc} * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function getUserInformation(array $accessToken, array $extraParameters = []) { @@ -66,7 +67,7 @@ public function getUserInformation(array $accessToken, array $extraParameters = break; default: - throw new \InvalidArgumentException('Invalid base64 format sent back'); + throw new InvalidArgumentException('Invalid base64 format sent back'); } $response = parent::getUserInformation($accessToken, $extraParameters); diff --git a/src/OAuth/ResourceOwner/DropboxResourceOwner.php b/src/OAuth/ResourceOwner/DropboxResourceOwner.php index 289034b62..37c5d5e3d 100644 --- a/src/OAuth/ResourceOwner/DropboxResourceOwner.php +++ b/src/OAuth/ResourceOwner/DropboxResourceOwner.php @@ -41,7 +41,7 @@ final class DropboxResourceOwner extends GenericOAuth2ResourceOwner * @return UserResponseInterface */ public function getUserInformation(array $accessToken, - array $extraParameters = [] + array $extraParameters = [], ) { if ($this->options['use_bearer_authorization']) { $content = $this->httpRequest( diff --git a/src/OAuth/ResourceOwner/GenericOAuth1ResourceOwner.php b/src/OAuth/ResourceOwner/GenericOAuth1ResourceOwner.php index be3d39d1b..7dbeb1929 100644 --- a/src/OAuth/ResourceOwner/GenericOAuth1ResourceOwner.php +++ b/src/OAuth/ResourceOwner/GenericOAuth1ResourceOwner.php @@ -15,6 +15,8 @@ use HWI\Bundle\OAuthBundle\Security\Helper\NonceGenerator; use HWI\Bundle\OAuthBundle\Security\OAuthErrorHandler; use HWI\Bundle\OAuthBundle\Security\OAuthUtils; +use InvalidArgumentException; +use RuntimeException; use Symfony\Component\HttpFoundation\Request as HttpRequest; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Security\Core\Exception\AuthenticationException; @@ -79,9 +81,9 @@ public function getAccessToken(HttpRequest $request, $redirectUri, array $extraP try { if (null === $requestToken = $this->storage->fetch($this, $request->query->get('oauth_token'))) { - throw new \RuntimeException('No request token found in the storage.'); + throw new RuntimeException('No request token found in the storage.'); } - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { throw new AuthenticationException('Given token is not valid.'); } @@ -109,7 +111,7 @@ public function getAccessToken(HttpRequest $request, $redirectUri, array $extraP $response = $this->getResponseContent($response); if (isset($response['oauth_problem'])) { - throw new AuthenticationException(sprintf('OAuth error: "%s"', $response['oauth_problem'])); + throw new AuthenticationException(\sprintf('OAuth error: "%s"', $response['oauth_problem'])); } if (!isset($response['oauth_token'], $response['oauth_token_secret'])) { @@ -167,7 +169,7 @@ public function getRequestToken($redirectUri, array $extraParameters = []) $response = $this->getResponseContent($apiResponse); if (isset($response['oauth_problem'])) { - throw new AuthenticationException(sprintf('OAuth error: "%s"', $response['oauth_problem'])); + throw new AuthenticationException(\sprintf('OAuth error: "%s"', $response['oauth_problem'])); } if (isset($response['oauth_callback_confirmed']) && 'true' !== $response['oauth_callback_confirmed']) { diff --git a/src/OAuth/ResourceOwner/GenericOAuth2ResourceOwner.php b/src/OAuth/ResourceOwner/GenericOAuth2ResourceOwner.php index 267a16ed3..d86b7a04d 100644 --- a/src/OAuth/ResourceOwner/GenericOAuth2ResourceOwner.php +++ b/src/OAuth/ResourceOwner/GenericOAuth2ResourceOwner.php @@ -15,6 +15,7 @@ use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken; use HWI\Bundle\OAuthBundle\Security\Helper\NonceGenerator; use HWI\Bundle\OAuthBundle\Security\OAuthErrorHandler; +use InvalidArgumentException; use Symfony\Component\HttpClient\Exception\JsonException; use Symfony\Component\HttpFoundation\Request as HttpRequest; use Symfony\Component\OptionsResolver\Options; @@ -166,7 +167,7 @@ public function isCsrfTokenValid($csrfToken) try { return null !== $this->storage->fetch($this, urldecode($csrfToken), 'csrf_state'); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { throw new AuthenticationException('Given CSRF token is not valid.'); } } @@ -213,11 +214,11 @@ protected function doGetUserInformationRequest($url, array $parameters = []) protected function validateResponseContent($response) { if (isset($response['error_description'])) { - throw new AuthenticationException(sprintf('OAuth error: "%s"', $response['error_description'])); + throw new AuthenticationException(\sprintf('OAuth error: "%s"', $response['error_description'])); } if (isset($response['error'])) { - throw new AuthenticationException(sprintf('OAuth error: "%s"', $response['error']['message'] ?? $response['error'])); + throw new AuthenticationException(\sprintf('OAuth error: "%s"', $response['error']['message'] ?? $response['error'])); } if (!isset($response['access_token'])) { diff --git a/src/OAuth/ResourceOwner/GitHubResourceOwner.php b/src/OAuth/ResourceOwner/GitHubResourceOwner.php index 83afe3df7..fbb66ef8c 100644 --- a/src/OAuth/ResourceOwner/GitHubResourceOwner.php +++ b/src/OAuth/ResourceOwner/GitHubResourceOwner.php @@ -66,7 +66,7 @@ public function getUserInformation(array $accessToken, array $extraParameters = public function revokeToken($token) { $response = $this->httpRequest( - sprintf($this->options['revoke_token_url'], $this->options['client_id']), + \sprintf($this->options['revoke_token_url'], $this->options['client_id']), json_encode(['access_token' => $token]), [ 'Authorization' => 'Basic '.base64_encode($this->options['client_id'].':'.$this->options['client_secret']), diff --git a/src/OAuth/ResourceOwner/OdnoklassnikiResourceOwner.php b/src/OAuth/ResourceOwner/OdnoklassnikiResourceOwner.php index f88bee784..d92ff7f74 100644 --- a/src/OAuth/ResourceOwner/OdnoklassnikiResourceOwner.php +++ b/src/OAuth/ResourceOwner/OdnoklassnikiResourceOwner.php @@ -63,14 +63,14 @@ public function getUserInformation(array $accessToken, array $extraParameters = if ($this->options['fields']) { $parameters['fields'] = $this->options['fields']; - $parameters['sig'] = md5(sprintf( + $parameters['sig'] = md5(\sprintf( 'application_key=%sfields=%smethod=users.getCurrentUser%s', $this->options['application_key'], $this->options['fields'], md5($accessToken['access_token'].$this->options['client_secret']) )); } else { - $parameters['sig'] = md5(sprintf( + $parameters['sig'] = md5(\sprintf( 'application_key=%smethod=users.getCurrentUser%s', $this->options['application_key'], md5($accessToken['access_token'].$this->options['client_secret']) diff --git a/src/OAuth/ResourceOwner/QQResourceOwner.php b/src/OAuth/ResourceOwner/QQResourceOwner.php index 3278e5cf7..8722cd6de 100644 --- a/src/OAuth/ResourceOwner/QQResourceOwner.php +++ b/src/OAuth/ResourceOwner/QQResourceOwner.php @@ -64,7 +64,7 @@ public function getUserInformation(?array $accessToken = null, array $extraParam if (isset($content['ret']) && 0 === $content['ret']) { $content['openid'] = $openid; } else { - throw new AuthenticationException(sprintf('OAuth error: %s', isset($content['ret']) ? $content['msg'] : 'invalid response')); + throw new AuthenticationException(\sprintf('OAuth error: %s', isset($content['ret']) ? $content['msg'] : 'invalid response')); } $response = $this->getUserResponse(); diff --git a/src/OAuth/ResourceOwner/RedditResourceOwner.php b/src/OAuth/ResourceOwner/RedditResourceOwner.php index 6459a3656..c7f2cb58d 100644 --- a/src/OAuth/ResourceOwner/RedditResourceOwner.php +++ b/src/OAuth/ResourceOwner/RedditResourceOwner.php @@ -39,7 +39,7 @@ protected function doGetTokenRequest($url, array $parameters = []) $url, http_build_query($parameters, '', '&'), [ - 'Authorization' => 'Basic '.base64_encode(sprintf('%s:%s', $this->options['client_id'], $this->options['client_secret'])), + 'Authorization' => 'Basic '.base64_encode(\sprintf('%s:%s', $this->options['client_id'], $this->options['client_secret'])), ], 'POST' ); diff --git a/src/OAuth/ResourceOwner/TelegramResourceOwner.php b/src/OAuth/ResourceOwner/TelegramResourceOwner.php index 8404852ed..6b23f9919 100644 --- a/src/OAuth/ResourceOwner/TelegramResourceOwner.php +++ b/src/OAuth/ResourceOwner/TelegramResourceOwner.php @@ -74,7 +74,7 @@ public function getAccessToken(Request $request, $redirectUri, array $extraParam ksort($authData); $dataCheckStr = ''; foreach ($authData as $k => $v) { - $dataCheckStr .= sprintf("\n%s=%s", $k, $v); + $dataCheckStr .= \sprintf("\n%s=%s", $k, $v); } $dataCheckStr = substr($dataCheckStr, 1); $secretKey = hash('sha256', $botToken, true); diff --git a/src/OAuth/ResourceOwnerInterface.php b/src/OAuth/ResourceOwnerInterface.php index 475dcd8f5..332291099 100644 --- a/src/OAuth/ResourceOwnerInterface.php +++ b/src/OAuth/ResourceOwnerInterface.php @@ -13,6 +13,7 @@ use HWI\Bundle\OAuthBundle\OAuth\Exception\HttpTransportException; use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface; +use InvalidArgumentException; use Symfony\Component\HttpFoundation\Request as HttpRequest; use Symfony\Component\Security\Core\Exception\AuthenticationException; @@ -84,7 +85,7 @@ public function getName(); * * @return mixed The option value * - * @throws \InvalidArgumentException When the option does not exist + * @throws InvalidArgumentException When the option does not exist */ public function getOption($name); diff --git a/src/OAuth/Response/AbstractUserResponse.php b/src/OAuth/Response/AbstractUserResponse.php index cef07ff94..79e4ebf31 100644 --- a/src/OAuth/Response/AbstractUserResponse.php +++ b/src/OAuth/Response/AbstractUserResponse.php @@ -13,6 +13,7 @@ use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface; use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken; +use JsonException; use Symfony\Component\Security\Core\Exception\AuthenticationException; /** @@ -126,7 +127,7 @@ public function setData($data) try { $this->data = json_decode($data, true, 512, \JSON_THROW_ON_ERROR); - } catch (\JsonException $exception) { + } catch (JsonException $exception) { throw new AuthenticationException('Response is not a valid JSON code.'); } } diff --git a/src/OAuth/Response/PathUserResponse.php b/src/OAuth/Response/PathUserResponse.php index 83f2d88e8..2281a167d 100644 --- a/src/OAuth/Response/PathUserResponse.php +++ b/src/OAuth/Response/PathUserResponse.php @@ -11,6 +11,8 @@ namespace HWI\Bundle\OAuthBundle\OAuth\Response; +use InvalidArgumentException; + /** * Class parsing the properties by given path options. * @@ -40,7 +42,7 @@ public function getUserIdentifier(): string { $value = $this->getValueForPath('identifier'); if (null === $value) { - throw new \InvalidArgumentException('User identifier was not found in response.'); + throw new InvalidArgumentException('User identifier was not found in response.'); } return (string) $value; @@ -53,7 +55,7 @@ public function getUsername() { try { return $this->getUserIdentifier(); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { // @phpstan-ignore-next-line BC compatibility return null; } diff --git a/src/OAuth/Response/SensioConnectUserResponse.php b/src/OAuth/Response/SensioConnectUserResponse.php index 2bfc43f5d..fb066a8bf 100644 --- a/src/OAuth/Response/SensioConnectUserResponse.php +++ b/src/OAuth/Response/SensioConnectUserResponse.php @@ -11,6 +11,13 @@ namespace HWI\Bundle\OAuthBundle\OAuth\Response; +use DOMAttr; +use DOMDocument; +use DOMNode; +use DOMXPath; +use ErrorException; +use Exception; +use InvalidArgumentException; use Symfony\Component\Security\Core\Exception\AuthenticationException; /** @@ -20,21 +27,21 @@ final class SensioConnectUserResponse extends AbstractUserResponse { /** - * @var \DOMNode + * @var DOMNode */ protected $data; - private ?\DOMXPath $xpath; + private ?DOMXPath $xpath; /** * {@inheritdoc} */ public function getUserIdentifier(): string { - /** @var \DOMAttr|null $attribute */ + /** @var DOMAttr|null $attribute */ $attribute = $this->data->attributes->getNamedItem('id'); if (null === $attribute) { - throw new \InvalidArgumentException('User identifier was not found in response.'); + throw new InvalidArgumentException('User identifier was not found in response.'); } return $attribute->value; @@ -47,7 +54,7 @@ public function getUsername(): ?string { try { return $this->getUserIdentifier(); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { // @phpstan-ignore-next-line BC compatibility return null; } @@ -61,7 +68,7 @@ public function getNickname() $username = null; $accounts = $this->xpath->query('./foaf:account/foaf:OnlineAccount', $this->data); for ($i = 0; $i < $accounts->length; ++$i) { - /** @var \DOMNode $account */ + /** @var DOMNode $account */ $account = $accounts->item($i); if ('SensioLabs Connect' === $this->getNodeValue('./foaf:name', $account)) { $username = $this->getNodeValue('foaf:accountName', $account); @@ -118,16 +125,16 @@ public function getProfilePicture(): ?string */ public function setData($data): void { - $dom = new \DOMDocument(); + $dom = new DOMDocument(); try { if (!$dom->loadXML($data)) { - throw new \ErrorException('Could not transform this xml to a \DOMDocument instance.'); + throw new ErrorException('Could not transform this xml to a \DOMDocument instance.'); } - } catch (\Exception $e) { + } catch (Exception $e) { throw new AuthenticationException('Could not retrieve valid user info.'); } - $this->xpath = new \DOMXPath($dom); + $this->xpath = new DOMXPath($dom); $nodes = $this->xpath->evaluate('/api/root'); $user = $this->xpath->query('./foaf:Person', $nodes->item(0)); @@ -135,7 +142,7 @@ public function setData($data): void throw new AuthenticationException('Could not retrieve user info.'); } - /** @var \DOMNode $userElement */ + /** @var DOMNode $userElement */ $userElement = $user->item(0); $this->data = $userElement; @@ -144,14 +151,14 @@ public function setData($data): void /** * @return mixed|null */ - private function getNodeValue(string $query, \DOMNode $element, string $nodeType = 'normal') + private function getNodeValue(string $query, DOMNode $element, string $nodeType = 'normal') { $nodeList = $this->xpath->query($query, $element); if ($nodeList && $nodeList->length > 0) { $node = $nodeList->item(0); switch ($nodeType) { case 'link': - /** @var \DOMAttr $attribute */ + /** @var DOMAttr $attribute */ $attribute = $node->attributes->getNamedItem('href'); $nodeValue = $attribute->value; break; diff --git a/src/OAuth/State/State.php b/src/OAuth/State/State.php index fbd0db864..8de69e98e 100644 --- a/src/OAuth/State/State.php +++ b/src/OAuth/State/State.php @@ -13,6 +13,8 @@ use HWI\Bundle\OAuthBundle\OAuth\Exception\StateRetrievalException; use HWI\Bundle\OAuthBundle\OAuth\StateInterface; +use InvalidArgumentException; +use JsonException; use Symfony\Component\Config\Definition\Exception\DuplicateKeyException; final class State implements StateInterface @@ -29,7 +31,7 @@ final class State implements StateInterface * @param string|array|null $parameters The state parameter as a string or assoc array * @param bool $keepCsrf Whether to keep the CSRF token in the state or not * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function __construct($parameters, bool $keepCsrf = true) { @@ -39,7 +41,7 @@ public function __construct($parameters, bool $keepCsrf = true) if (null !== $parameters) { if (!$this->isAssociatedArray($parameters)) { - throw new \InvalidArgumentException('Constructor argument should be a non-empty, associative array'); + throw new InvalidArgumentException('Constructor argument should be a non-empty, associative array'); } foreach ($parameters as $key => $value) { @@ -69,7 +71,7 @@ public function __unserialize(array $data): void public function add(string $key, string $value): void { if (isset($this->values[$key])) { - throw new DuplicateKeyException(sprintf('State key [%s] is already set.', $key)); + throw new DuplicateKeyException(\sprintf('State key [%s] is already set.', $key)); } $this->values[$key] = $value; @@ -136,7 +138,7 @@ private function parseStringParameter(?string $queryParameter = null): ?array try { $values = json_decode(base64_decode($urlDecoded), true, 512, \JSON_THROW_ON_ERROR); - } catch (\JsonException $e) { + } catch (JsonException $e) { $values = null; } @@ -154,7 +156,7 @@ private function encodeValues(): string { try { return base64_encode(json_encode($this->values, \JSON_THROW_ON_ERROR)); - } catch (\JsonException $e) { + } catch (JsonException $e) { return ''; } } diff --git a/src/Security/Core/Authentication/Provider/OAuthProvider.php b/src/Security/Core/Authentication/Provider/OAuthProvider.php index a1874c436..230463932 100644 --- a/src/Security/Core/Authentication/Provider/OAuthProvider.php +++ b/src/Security/Core/Authentication/Provider/OAuthProvider.php @@ -38,7 +38,7 @@ public function __construct( OAuthAwareUserProviderInterface $userProvider, ResourceOwnerMapInterface $resourceOwnerMap, UserCheckerInterface $userChecker, - TokenStorageInterface $tokenStorage + TokenStorageInterface $tokenStorage, ) { $this->userProvider = $userProvider; $this->resourceOwnerMap = $resourceOwnerMap; @@ -135,7 +135,7 @@ private function refreshToken(TokenInterface $expiredToken, ResourceOwnerInterfa private function createOAuthToken( $data, OAuthToken $oldToken, - ?UserInterface $user + ?UserInterface $user, ): OAuthToken { $tokenClass = $oldToken::class; if (null !== $user) { diff --git a/src/Security/Core/Authentication/Token/AbstractOAuthToken.php b/src/Security/Core/Authentication/Token/AbstractOAuthToken.php index 20fefd04d..5bee723a4 100644 --- a/src/Security/Core/Authentication/Token/AbstractOAuthToken.php +++ b/src/Security/Core/Authentication/Token/AbstractOAuthToken.php @@ -11,6 +11,7 @@ namespace HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token; +use InvalidArgumentException; use Symfony\Component\Security\Core\Authentication\Token\AbstractToken; /** @@ -112,7 +113,7 @@ public function getAccessToken() /** * @param array|string $token The OAuth token * - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function setRawToken($token) { @@ -122,7 +123,7 @@ public function setRawToken($token) } elseif (isset($token['oauth_token'])) { $this->accessToken = $token['oauth_token']; } else { - throw new \InvalidArgumentException('Access token was not found.'); + throw new InvalidArgumentException('Access token was not found.'); } if (isset($token['refresh_token'])) { diff --git a/src/Security/Core/Exception/AccountNotLinkedException.php b/src/Security/Core/Exception/AccountNotLinkedException.php index a1b870865..c88c6d389 100644 --- a/src/Security/Core/Exception/AccountNotLinkedException.php +++ b/src/Security/Core/Exception/AccountNotLinkedException.php @@ -36,7 +36,7 @@ public function __unserialize(array $data): void { [ $this->resourceOwnerName, - $parentData + $parentData, ] = $data; parent::__unserialize($parentData); diff --git a/src/Security/Core/User/EntityUserProvider.php b/src/Security/Core/User/EntityUserProvider.php index 33b5882fe..4ab5d94a8 100644 --- a/src/Security/Core/User/EntityUserProvider.php +++ b/src/Security/Core/User/EntityUserProvider.php @@ -16,6 +16,7 @@ use Doctrine\Persistence\ObjectRepository; use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface; use HWI\Bundle\OAuthBundle\Security\Core\Exception\AccountNotLinkedException; +use RuntimeException; use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UserNotFoundException; @@ -57,7 +58,7 @@ public function loadUserByIdentifier(string $identifier): UserInterface $user = $this->findUser(['username' => $identifier]); if (!$user) { - throw $this->createUserNotFoundException($identifier, sprintf("User '%s' not found.", $identifier)); + throw $this->createUserNotFoundException($identifier, \sprintf("User '%s' not found.", $identifier)); } return $user; @@ -80,12 +81,12 @@ public function loadUserByOAuthUserResponse(UserResponseInterface $response): ?U $resourceOwnerName = $response->getResourceOwner()->getName(); if (!isset($this->properties[$resourceOwnerName])) { - throw new \RuntimeException(sprintf("No property defined for entity for resource owner '%s'.", $resourceOwnerName)); + throw new RuntimeException(\sprintf("No property defined for entity for resource owner '%s'.", $resourceOwnerName)); } $username = method_exists($response, 'getUserIdentifier') ? $response->getUserIdentifier() : $response->getUsername(); if (null === $user = $this->findUser([$this->properties[$resourceOwnerName] => $username])) { - throw $this->createUserNotFoundException($username, sprintf("User '%s' not found.", $username)); + throw $this->createUserNotFoundException($username, \sprintf("User '%s' not found.", $username)); } return $user; @@ -96,7 +97,7 @@ public function refreshUser(UserInterface $user): UserInterface $accessor = PropertyAccess::createPropertyAccessor(); $identifier = $this->properties['identifier']; if (!$accessor->isReadable($user, $identifier) || !$this->supportsClass($user::class)) { - throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class)); + throw new UnsupportedUserException(\sprintf('Instances of "%s" are not supported.', $user::class)); } $userId = $accessor->getValue($user, $identifier); @@ -104,7 +105,7 @@ public function refreshUser(UserInterface $user): UserInterface $username = $user->getUserIdentifier(); if (null === $user = $this->findUser([$identifier => $userId])) { - throw $this->createUserNotFoundException($username, sprintf('User with ID "%d" could not be reloaded.', $userId)); + throw $this->createUserNotFoundException($username, \sprintf('User with ID "%d" could not be reloaded.', $userId)); } return $user; diff --git a/src/Security/Core/User/OAuthUserProvider.php b/src/Security/Core/User/OAuthUserProvider.php index 8ae6ca175..e766ec6ed 100644 --- a/src/Security/Core/User/OAuthUserProvider.php +++ b/src/Security/Core/User/OAuthUserProvider.php @@ -46,7 +46,7 @@ public function loadUserByOAuthUserResponse(UserResponseInterface $response): Us public function refreshUser(UserInterface $user): UserInterface { if (!$this->supportsClass($user::class)) { - throw new UnsupportedUserException(sprintf('Unsupported user class "%s"', $user::class)); + throw new UnsupportedUserException(\sprintf('Unsupported user class "%s"', $user::class)); } // @phpstan-ignore-next-line Symfony <5.4 BC layer diff --git a/src/Security/Http/Authenticator/OAuthAuthenticator.php b/src/Security/Http/Authenticator/OAuthAuthenticator.php index 00369504f..f24ba0d02 100644 --- a/src/Security/Http/Authenticator/OAuthAuthenticator.php +++ b/src/Security/Http/Authenticator/OAuthAuthenticator.php @@ -18,6 +18,7 @@ use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface; use HWI\Bundle\OAuthBundle\Security\Http\Authenticator\Passport\Badge\OAuthTokenBadge; use HWI\Bundle\OAuthBundle\Security\Http\ResourceOwnerMapInterface; +use LogicException; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -54,7 +55,7 @@ public function __construct( private readonly AuthenticationSuccessHandlerInterface $successHandler, private readonly AuthenticationFailureHandlerInterface $failureHandler, private readonly HttpKernelInterface $kernel, - private readonly array $options + private readonly array $options, ) { } @@ -108,7 +109,7 @@ public function authenticate(Request $request): Passport if ($request->query->has('authenticated') && $resourceOwner->getOption('auth_with_one_url')) { $request->attributes->set('service', $resourceOwner->getName()); - throw new LazyResponseException(new RedirectResponse(sprintf('%s?code=%s&authenticated=true', $this->httpUtils->generateUri($request, 'hwi_oauth_connect_service'), $request->query->get('code')))); + throw new LazyResponseException(new RedirectResponse(\sprintf('%s?code=%s&authenticated=true', $this->httpUtils->generateUri($request, 'hwi_oauth_connect_service'), $request->query->get('code')))); } $resourceOwner->isCsrfTokenValid( @@ -198,8 +199,7 @@ public function refreshToken(OAuthToken $token): OAuthToken /** * @template T of OAuthToken * - * @param T $token - * @param ?UserInterface $user + * @param T $token * * @return T */ @@ -249,7 +249,7 @@ public function createAuthenticatedToken($passport, string $firewallName): Token return $badge->getToken(); } - throw new \LogicException(sprintf('Given passport must contain instance of "%s".', OAuthTokenBadge::class)); + throw new LogicException(\sprintf('Given passport must contain instance of "%s".', OAuthTokenBadge::class)); } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response diff --git a/src/Security/Http/EntryPoint/OAuthEntryPoint.php b/src/Security/Http/EntryPoint/OAuthEntryPoint.php index 296fe5e61..04e4ba997 100644 --- a/src/Security/Http/EntryPoint/OAuthEntryPoint.php +++ b/src/Security/Http/EntryPoint/OAuthEntryPoint.php @@ -11,6 +11,7 @@ namespace HWI\Bundle\OAuthBundle\Security\Http\EntryPoint; +use ArrayIterator; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; @@ -32,7 +33,7 @@ public function __construct( private readonly HttpKernelInterface $kernel, private readonly HttpUtils $httpUtils, private readonly string $loginPath, - private readonly bool $useForward = false + private readonly bool $useForward = false, ) { } @@ -44,7 +45,7 @@ public function start(Request $request, ?AuthenticationException $authException if ($this->useForward) { $subRequest = $this->httpUtils->createRequest($request, $this->loginPath); - /** @var \ArrayIterator $iterator */ + /** @var ArrayIterator $iterator */ $iterator = $request->query->getIterator(); $subRequest->query->add($iterator->getArrayCopy()); diff --git a/src/Security/Http/Firewall/OAuthListener.php b/src/Security/Http/Firewall/OAuthListener.php index e822b91c4..67080f664 100644 --- a/src/Security/Http/Firewall/OAuthListener.php +++ b/src/Security/Http/Firewall/OAuthListener.php @@ -82,7 +82,7 @@ protected function attemptAuthentication(Request $request) if ($request->query->has('authenticated') && $resourceOwner->getOption('auth_with_one_url')) { $request->attributes->set('service', $resourceOwner->getName()); - return new RedirectResponse(sprintf('%s?code=%s&authenticated=true', $this->httpUtils->generateUri($request, 'hwi_oauth_connect_service'), $request->query->get('code'))); + return new RedirectResponse(\sprintf('%s?code=%s&authenticated=true', $this->httpUtils->generateUri($request, 'hwi_oauth_connect_service'), $request->query->get('code'))); } $resourceOwner->isCsrfTokenValid( diff --git a/src/Security/Http/Firewall/RefreshAccessTokenListener.php b/src/Security/Http/Firewall/RefreshAccessTokenListener.php index d64343b6b..2407f4b73 100644 --- a/src/Security/Http/Firewall/RefreshAccessTokenListener.php +++ b/src/Security/Http/Firewall/RefreshAccessTokenListener.php @@ -13,6 +13,7 @@ use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken; use HWI\Bundle\OAuthBundle\Security\Http\Authenticator\OAuthAuthenticator; +use RuntimeException; use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface; use Symfony\Component\Security\Http\Authenticator\Debug\TraceableAuthenticator; @@ -21,7 +22,7 @@ class RefreshAccessTokenListener extends AbstractRefreshAccessTokenListener private AuthenticatorInterface $authenticator; public function __construct( - AuthenticatorInterface $authenticator + AuthenticatorInterface $authenticator, ) { $this->authenticator = $authenticator; } @@ -38,15 +39,15 @@ protected function refreshToken(OAuthToken $token): OAuthToken if ($this->authenticator instanceof OAuthAuthenticator) { return $this->authenticator->refreshToken($token); } - + if ($this->authenticator instanceof TraceableAuthenticator) { $authenticator = $this->authenticator->getAuthenticator(); - + if ($authenticator instanceof OAuthAuthenticator) { return $authenticator->refreshToken($token); } } - throw new \RuntimeException('Unsupported authenticator, expecting OAuthAuthenticator, got ' . get_class($this->authenticator)); + throw new RuntimeException('Unsupported authenticator, expecting OAuthAuthenticator, got '.\get_class($this->authenticator)); } } diff --git a/src/Security/Http/Firewall/RefreshAccessTokenListenerOld.php b/src/Security/Http/Firewall/RefreshAccessTokenListenerOld.php index 477fd3870..823928f2d 100644 --- a/src/Security/Http/Firewall/RefreshAccessTokenListenerOld.php +++ b/src/Security/Http/Firewall/RefreshAccessTokenListenerOld.php @@ -23,7 +23,7 @@ class RefreshAccessTokenListenerOld extends RefreshAccessTokenListener public function __construct( /* @phpstan-ignore-next-line */ - AuthenticationProviderInterface $oAuthProvider + AuthenticationProviderInterface $oAuthProvider, ) { $this->oAuthProvider = $oAuthProvider; } diff --git a/src/Security/Http/ResourceOwnerMap.php b/src/Security/Http/ResourceOwnerMap.php index 76154bdfe..a73139fad 100644 --- a/src/Security/Http/ResourceOwnerMap.php +++ b/src/Security/Http/ResourceOwnerMap.php @@ -34,7 +34,7 @@ public function __construct( private readonly HttpUtils $httpUtils, private readonly array $possibleResourceOwners, private readonly array $resourceOwners, - private readonly ServiceLocator $locator + private readonly ServiceLocator $locator, ) { } diff --git a/src/Security/OAuthErrorHandler.php b/src/Security/OAuthErrorHandler.php index ed10b6386..0b3f0c958 100644 --- a/src/Security/OAuthErrorHandler.php +++ b/src/Security/OAuthErrorHandler.php @@ -61,7 +61,7 @@ public static function handleOAuthError(Request $request): void } if (null !== $error) { - $error = self::$translatedOAuthErrors[$error] ?? sprintf('Unknown OAuth error: "%s".', $error); + $error = self::$translatedOAuthErrors[$error] ?? \sprintf('Unknown OAuth error: "%s".', $error); throw new AuthenticationException($error); } diff --git a/src/Security/OAuthUtils.php b/src/Security/OAuthUtils.php index 099ccb718..f799c69c2 100644 --- a/src/Security/OAuthUtils.php +++ b/src/Security/OAuthUtils.php @@ -14,6 +14,7 @@ use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface; use HWI\Bundle\OAuthBundle\OAuth\State\State; use HWI\Bundle\OAuthBundle\Security\Http\ResourceOwnerMapInterface; +use RuntimeException; use Symfony\Bundle\SecurityBundle\Security\FirewallMap; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; @@ -40,7 +41,7 @@ public function __construct( private readonly AuthorizationCheckerInterface $authorizationChecker, private readonly FirewallMap $firewallMap, private readonly bool $connect, - private readonly string $grantRule + private readonly string $grantRule, ) { } @@ -126,7 +127,7 @@ public function getLoginUrl(Request $request, string $name): string * @param string $tokenSecret Optional token secret to use with signing * @param string $signatureMethod Optional signature method used to sign token * - * @throws \RuntimeException + * @throws RuntimeException */ public static function signRequest( string $method, @@ -134,12 +135,12 @@ public static function signRequest( array $parameters, string $clientSecret, string $tokenSecret = '', - string $signatureMethod = self::SIGNATURE_METHOD_HMAC + string $signatureMethod = self::SIGNATURE_METHOD_HMAC, ): string { // Validate required parameters foreach (['oauth_consumer_key', 'oauth_timestamp', 'oauth_nonce', 'oauth_version', 'oauth_signature_method'] as $parameter) { if (!isset($parameters[$parameter])) { - throw new \RuntimeException(sprintf('Parameter "%s" must be set.', $parameter)); + throw new RuntimeException(\sprintf('Parameter "%s" must be set.', $parameter)); } } @@ -165,7 +166,7 @@ public static function signRequest( // Remove query params from URL // Ref: Spec: 9.1.2 - $url = sprintf('%s://%s%s%s', $url['scheme'], $url['host'], $explicitPort ? ':'.$explicitPort : '', $url['path'] ?? ''); + $url = \sprintf('%s://%s%s%s', $url['scheme'], $url['host'], $explicitPort ? ':'.$explicitPort : '', $url['path'] ?? ''); // Parameters are sorted by name, using lexicographical byte value ordering. // Ref: Spec: 9.1.1 (1) @@ -194,7 +195,7 @@ public static function signRequest( case self::SIGNATURE_METHOD_RSA: if (!\function_exists('openssl_pkey_get_private')) { - throw new \RuntimeException('RSA-SHA1 signature method requires the OpenSSL extension.'); + throw new RuntimeException('RSA-SHA1 signature method requires the OpenSSL extension.'); } if (str_starts_with($clientSecret, '-----BEGIN')) { @@ -214,7 +215,7 @@ public static function signRequest( break; default: - throw new \RuntimeException(sprintf('Unknown signature method selected %s.', $signatureMethod)); + throw new RuntimeException(\sprintf('Unknown signature method selected %s.', $signatureMethod)); } return base64_encode($signature); @@ -229,7 +230,7 @@ private function getResourceOwner(string $name): ResourceOwnerInterface } } - throw new \RuntimeException(sprintf("No resource owner with name '%s'.", $name)); + throw new RuntimeException(\sprintf("No resource owner with name '%s'.", $name)); } private function getCurrentFirewallName(Request $request): ?string diff --git a/src/Test/OAuth/ResourceOwner/GenericOAuth1ResourceOwnerTestCase.php b/src/Test/OAuth/ResourceOwner/GenericOAuth1ResourceOwnerTestCase.php index 0768aa525..f1f3bda01 100644 --- a/src/Test/OAuth/ResourceOwner/GenericOAuth1ResourceOwnerTestCase.php +++ b/src/Test/OAuth/ResourceOwner/GenericOAuth1ResourceOwnerTestCase.php @@ -14,6 +14,7 @@ use HWI\Bundle\OAuthBundle\OAuth\RequestDataStorageInterface; use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\GenericOAuth1ResourceOwner; use HWI\Bundle\OAuthBundle\Test\Fixtures\CustomUserResponse; +use InvalidArgumentException; use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\OptionsResolver\Exception\ExceptionInterface; @@ -358,7 +359,7 @@ public function testGetAccessTokenInvalidArgumentException(): void $this->storage->expects($this->once()) ->method('fetch') - ->willThrowException(new \InvalidArgumentException()); + ->willThrowException(new InvalidArgumentException()); $this->storage->expects($this->never()) ->method('save'); diff --git a/src/Test/OAuth/ResourceOwner/GenericOAuth2ResourceOwnerTestCase.php b/src/Test/OAuth/ResourceOwner/GenericOAuth2ResourceOwnerTestCase.php index cae1a4276..7f826c8cf 100644 --- a/src/Test/OAuth/ResourceOwner/GenericOAuth2ResourceOwnerTestCase.php +++ b/src/Test/OAuth/ResourceOwner/GenericOAuth2ResourceOwnerTestCase.php @@ -18,6 +18,8 @@ use HWI\Bundle\OAuthBundle\OAuth\StateInterface; use HWI\Bundle\OAuthBundle\Security\Helper\NonceGenerator; use HWI\Bundle\OAuthBundle\Test\Fixtures\CustomUserResponse; +use InvalidArgumentException; +use ReflectionClass; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\OptionsResolver\Exception\ExceptionInterface; use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; @@ -176,7 +178,7 @@ public function testGetStateWithoutStoredValues(): void $this->storage->expects($this->once()) ->method('fetch') ->with($resourceOwner, State::class, 'state') - ->willThrowException(new \InvalidArgumentException('No data available in storage.')); + ->willThrowException(new InvalidArgumentException('No data available in storage.')); $state = $resourceOwner->getState(); self::assertEmpty($state->getAll()); @@ -436,12 +438,12 @@ protected function createResourceOwner( array $options = [], array $paths = [], array $responses = [], - ?StateInterface $state = null + ?StateInterface $state = null, ): GenericOAuth2ResourceOwner { /** @var GenericOAuth2ResourceOwner $resourceOwner */ $resourceOwner = parent::createResourceOwner($options, $paths, $responses); - $reflection = new \ReflectionClass($resourceOwner::class); + $reflection = new ReflectionClass($resourceOwner::class); $stateProperty = $reflection->getProperty('state'); $stateProperty->setAccessible(true); $stateProperty->setValue($resourceOwner, $state ?: new State($this->state)); diff --git a/src/Test/OAuth/ResourceOwner/ResourceOwnerTestCase.php b/src/Test/OAuth/ResourceOwner/ResourceOwnerTestCase.php index a2b81827c..d87cf8664 100644 --- a/src/Test/OAuth/ResourceOwner/ResourceOwnerTestCase.php +++ b/src/Test/OAuth/ResourceOwner/ResourceOwnerTestCase.php @@ -19,6 +19,7 @@ use HWI\Bundle\OAuthBundle\Test\Fixtures\ResourceOwner\OAuth2ResourceOwnerStub; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use RuntimeException; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; use Symfony\Component\Security\Http\HttpUtils; @@ -88,11 +89,11 @@ protected function createResourceOwner(array $options = [], array $paths = [], a protected function setUpResourceOwner(string $name, HttpUtils $httpUtils, array $options, array $responses): ResourceOwnerInterface { if (!$this->resourceOwnerClass) { - throw new \RuntimeException('Missing resource owner class declaration!'); + throw new RuntimeException('Missing resource owner class declaration!'); } if (!\in_array(ResourceOwnerInterface::class, class_implements($this->resourceOwnerClass), true)) { - throw new \RuntimeException('Class is not implementing "ResourceOwnerInterface"!'); + throw new RuntimeException('Class is not implementing "ResourceOwnerInterface"!'); } $resourceOwnerClass = $this->resourceOwnerClass; diff --git a/tests/App/AppKernel.php b/tests/App/AppKernel.php index 830521209..26d6856bb 100644 --- a/tests/App/AppKernel.php +++ b/tests/App/AppKernel.php @@ -15,6 +15,7 @@ use Doctrine\Bundle\DoctrineBundle\DoctrineBundle; use HWI\Bundle\OAuthBundle\HWIOAuthBundle; +use ReflectionClass; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Bundle\MonologBundle\MonologBundle; use Symfony\Bundle\SecurityBundle\SecurityBundle; @@ -81,6 +82,6 @@ public function getLogDir(): string protected function getBaseDir(): string { - return sys_get_temp_dir().'/hwioauth-bundle/'.(new \ReflectionClass($this))->getShortName().'/var/'; + return sys_get_temp_dir().'/hwioauth-bundle/'.(new ReflectionClass($this))->getShortName().'/var/'; } } diff --git a/tests/Controller/Connect/ConnectControllerTest.php b/tests/Controller/Connect/ConnectControllerTest.php index 1f12e7c73..6c76530d8 100644 --- a/tests/Controller/Connect/ConnectControllerTest.php +++ b/tests/Controller/Connect/ConnectControllerTest.php @@ -210,7 +210,7 @@ public function testResourceOwnerHandle(): void private function createConnectController( bool $connectEnabled = true, - bool $confirmConnect = true + bool $confirmConnect = true, ): ConnectController { return new ConnectController( $this->oAuthUtils, diff --git a/tests/Controller/Connect/RegistrationControllerTest.php b/tests/Controller/Connect/RegistrationControllerTest.php index a37d0496a..39f0895cd 100644 --- a/tests/Controller/Connect/RegistrationControllerTest.php +++ b/tests/Controller/Connect/RegistrationControllerTest.php @@ -11,6 +11,7 @@ namespace HWI\Bundle\OAuthBundle\Tests\Controller\Connect; +use Exception; use HWI\Bundle\OAuthBundle\Controller\Connect\RegisterController; use HWI\Bundle\OAuthBundle\Event\FilterUserResponseEvent; use HWI\Bundle\OAuthBundle\Event\FormEvent; @@ -49,7 +50,7 @@ public function testAlreadyConnected(): void public function testCannotRegisterBadError(): void { - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage('Cannot register an account.'); $key = (string) time(); @@ -59,7 +60,7 @@ public function testCannotRegisterBadError(): void $this->session->expects($this->once()) ->method('get') ->with('_hwi_oauth.registration_error.'.$key) - ->willReturn(new \Exception()) + ->willReturn(new Exception()) ; $this->session->expects($this->once()) @@ -167,7 +168,7 @@ private function makeRegistrationForm(): void } private function createConnectController( - bool $connectEnabled = true + bool $connectEnabled = true, ): RegisterController { return new RegisterController( $this->resourceOwnerMapLocator, diff --git a/tests/DependencyInjection/HWIOAuthExtensionTest.php b/tests/DependencyInjection/HWIOAuthExtensionTest.php index 0744d1613..caf7d2e6b 100644 --- a/tests/DependencyInjection/HWIOAuthExtensionTest.php +++ b/tests/DependencyInjection/HWIOAuthExtensionTest.php @@ -16,6 +16,7 @@ use HWI\Bundle\OAuthBundle\Tests\Fixtures\CustomResourceOwner; use HWI\Bundle\OAuthBundle\Tests\Fixtures\CustomResourceOwnerWithoutType; use PHPUnit\Framework\TestCase; +use stdClass; use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; @@ -208,7 +209,7 @@ public function testConfigurationThrowsExceptionWhenClassNotImplementingResource $this->expectExceptionMessage('Invalid configuration for path "hwi_oauth.resource_owners.new_resourceowner": Resource owner class should implement "ResourceOwnerInterface", or extended class "GenericOAuth1ResourceOwner"/"GenericOAuth2ResourceOwner".'); $config = $this->getEmptyConfig(); - $config['resource_owners']['new_resourceowner']['class'] = \stdClass::class; + $config['resource_owners']['new_resourceowner']['class'] = stdClass::class; $config['resource_owners']['new_resourceowner']['client_id'] = 42; $config['resource_owners']['new_resourceowner']['client_secret'] = 'foo'; @@ -626,11 +627,11 @@ protected function getEmptyConfig(): array private function assertAlias(string $value, string $key): void { - $this->assertEquals($value, (string) $this->containerBuilder->getAlias($key), sprintf('%s alias is correct', $key)); + $this->assertEquals($value, (string) $this->containerBuilder->getAlias($key), \sprintf('%s alias is correct', $key)); } private function assertParameter($value, string $key): void { - $this->assertEquals($value, $this->containerBuilder->getParameter($key), sprintf('%s parameter is correct', $key)); + $this->assertEquals($value, $this->containerBuilder->getParameter($key), \sprintf('%s parameter is correct', $key)); } } diff --git a/tests/Fixtures/OAuthAwareException.php b/tests/Fixtures/OAuthAwareException.php index ef29634a9..17b5b54f8 100644 --- a/tests/Fixtures/OAuthAwareException.php +++ b/tests/Fixtures/OAuthAwareException.php @@ -11,6 +11,7 @@ namespace HWI\Bundle\OAuthBundle\Tests\Fixtures; +use Exception; use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken; use HWI\Bundle\OAuthBundle\Security\Core\Exception\OAuthAwareExceptionInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; @@ -18,7 +19,7 @@ /** * @author Alexander */ -final class OAuthAwareException extends \Exception implements OAuthAwareExceptionInterface +final class OAuthAwareException extends Exception implements OAuthAwareExceptionInterface { private OAuthToken $token; private string $resourceOwnerName; diff --git a/tests/OAuth/RequestDataStorage/SessionStorageTest.php b/tests/OAuth/RequestDataStorage/SessionStorageTest.php index 2b4bd6c7e..88dcb55a8 100644 --- a/tests/OAuth/RequestDataStorage/SessionStorageTest.php +++ b/tests/OAuth/RequestDataStorage/SessionStorageTest.php @@ -13,8 +13,10 @@ use HWI\Bundle\OAuthBundle\OAuth\RequestDataStorage\SessionStorage; use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface; +use InvalidArgumentException; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use stdClass; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\SessionInterface; @@ -59,7 +61,7 @@ protected function setUp(): void public function testSaveTokenWithoutOAuthTokenPassedThrowsException(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid request token.'); $this->storage->save($this->resourceOwner, [], 'token'); } @@ -99,7 +101,7 @@ public function testSaveArrayValue(): void public function testSaveObjectValue(): void { - $class = new \stdClass(); + $class = new stdClass(); $key = '_hwi_oauth.resource_owner_name.client_id.type.stdClass'; $this->session ->expects(self::once()) @@ -111,7 +113,7 @@ public function testSaveObjectValue(): void public function testFetchUnavailableKeyThrowsException(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('No data available in storage.'); $this->storage->fetch($this->resourceOwner, 'not-existing-key', 'token'); } @@ -134,7 +136,7 @@ public function testFetchTokenIsOneTimeUseOnly(): void public function testFetchOtherThenToken(): void { - $class = new \stdClass(); + $class = new stdClass(); $key = '_hwi_oauth.resource_owner_name.client_id.state.stdClass'; $this->session ->expects(self::once()) diff --git a/tests/OAuth/ResourceOwner/AppleResourceOwnerTest.php b/tests/OAuth/ResourceOwner/AppleResourceOwnerTest.php index 687c60ccd..e7edb219e 100644 --- a/tests/OAuth/ResourceOwner/AppleResourceOwnerTest.php +++ b/tests/OAuth/ResourceOwner/AppleResourceOwnerTest.php @@ -15,6 +15,7 @@ use HWI\Bundle\OAuthBundle\OAuth\Response\AbstractUserResponse; use HWI\Bundle\OAuthBundle\Test\Fixtures\CustomUserResponse; use HWI\Bundle\OAuthBundle\Test\OAuth\ResourceOwner\GenericOAuth2ResourceOwnerTestCase; +use InvalidArgumentException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Exception\AuthenticationException; @@ -101,7 +102,7 @@ public function testAutoGeneratedClientSecretMissingOptions(): void $request = new Request(['code' => 'somecode']); - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Options "auth_key", "key_id" and "team_id" must be defined to use automatic "client_secret" generation.'); $resourceOwner->getAccessToken($request, 'http://redirect.to/'); @@ -199,7 +200,7 @@ public function testGetUserInformation(): void public function testGetUserInformationFailure(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Undefined index id_token'); $resourceOwner = $this->createResourceOwner( diff --git a/tests/OAuth/ResourceOwner/TelegramResourceOwnerTest.php b/tests/OAuth/ResourceOwner/TelegramResourceOwnerTest.php index 129c0438a..6e2bc183e 100644 --- a/tests/OAuth/ResourceOwner/TelegramResourceOwnerTest.php +++ b/tests/OAuth/ResourceOwner/TelegramResourceOwnerTest.php @@ -181,7 +181,7 @@ private function getAuthToken(array $authData, string $secret) ksort($authData); $dataStr = ''; foreach ($authData as $k => $v) { - $dataStr .= sprintf("\n%s=%s", $k, $v); + $dataStr .= \sprintf("\n%s=%s", $k, $v); } $dataStr = substr($dataStr, 1); $secretKey = hash('sha256', $secret, true); diff --git a/tests/OAuth/Response/PathUserResponseTest.php b/tests/OAuth/Response/PathUserResponseTest.php index ba4192c9c..be4e92766 100644 --- a/tests/OAuth/Response/PathUserResponseTest.php +++ b/tests/OAuth/Response/PathUserResponseTest.php @@ -13,6 +13,7 @@ use HWI\Bundle\OAuthBundle\OAuth\ResourceOwnerInterface; use HWI\Bundle\OAuthBundle\OAuth\Response\PathUserResponse; +use InvalidArgumentException; use PHPUnit\Framework\TestCase; final class PathUserResponseTest extends TestCase @@ -100,7 +101,7 @@ public function testGetUserIdentifier(): void public function testGetUserIdentifierWithoutResponseThrowsException(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('User identifier was not found in response.'); $this->responseObject->setPaths(['identifier' => 'id']); diff --git a/tests/OAuth/State/StateTest.php b/tests/OAuth/State/StateTest.php index 8cae9cdb1..1e6d28334 100644 --- a/tests/OAuth/State/StateTest.php +++ b/tests/OAuth/State/StateTest.php @@ -14,6 +14,7 @@ use HWI\Bundle\OAuthBundle\OAuth\Exception\StateRetrievalException; use HWI\Bundle\OAuthBundle\OAuth\State\State; use HWI\Bundle\OAuthBundle\Security\Helper\NonceGenerator; +use InvalidArgumentException; use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Exception\DuplicateKeyException; @@ -75,7 +76,7 @@ public function testItCanBeSerializedAndUnserialized(): void public function testFromEncodedParameterWithInvalidFormat(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $values = ['some', 'indexed', 'array']; diff --git a/tests/Security/Core/Authentication/Provider/OAuthProviderTest.php b/tests/Security/Core/Authentication/Provider/OAuthProviderTest.php index 8058a3ad7..5316d4a15 100644 --- a/tests/Security/Core/Authentication/Provider/OAuthProviderTest.php +++ b/tests/Security/Core/Authentication/Provider/OAuthProviderTest.php @@ -277,7 +277,7 @@ protected function getOAuthAwareUserProviderMock() protected function getResourceOwnerMap( array $resources = [], - $serviceLocator = null + $serviceLocator = null, ): ResourceOwnerMap { return new ResourceOwnerMap( $this->createMock(HttpUtils::class), diff --git a/tests/Security/Core/User/EntityUserProviderTest.php b/tests/Security/Core/User/EntityUserProviderTest.php index e39f829c8..6c2b18c86 100644 --- a/tests/Security/Core/User/EntityUserProviderTest.php +++ b/tests/Security/Core/User/EntityUserProviderTest.php @@ -20,6 +20,7 @@ use HWI\Bundle\OAuthBundle\Security\Core\User\EntityUserProvider; use HWI\Bundle\OAuthBundle\Tests\Fixtures\User; use PHPUnit\Framework\TestCase; +use RuntimeException; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Exception\UserNotFoundException; @@ -60,7 +61,7 @@ public function testLoadUserByUsernameThrowsExceptionWhenUserIsNull(): void public function testLoadUserByOAuthUserResponseThrowsExceptionWhenNoPropertyIsConfigured(): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('No property defined for entity for resource owner \'not_configured\'.'); $provider = $this->createEntityUserProvider(); diff --git a/tests/Security/Http/Authenticator/OAuthAuthenticatorTest.php b/tests/Security/Http/Authenticator/OAuthAuthenticatorTest.php index 667174c25..1502067bc 100644 --- a/tests/Security/Http/Authenticator/OAuthAuthenticatorTest.php +++ b/tests/Security/Http/Authenticator/OAuthAuthenticatorTest.php @@ -417,7 +417,7 @@ private function getOAuthTokenMock(): OAuthToken private function getResourceOwnerMap( array $resources = [], $httpUtils = null, - $serviceLocator = null + $serviceLocator = null, ): ResourceOwnerMap { return new ResourceOwnerMap( $httpUtils ?: $this->createMock(HttpUtils::class), diff --git a/tests/Security/OAuthUtilsTest.php b/tests/Security/OAuthUtilsTest.php index d8950e615..0585fc742 100644 --- a/tests/Security/OAuthUtilsTest.php +++ b/tests/Security/OAuthUtilsTest.php @@ -16,6 +16,7 @@ use HWI\Bundle\OAuthBundle\Security\Http\ResourceOwnerMap; use HWI\Bundle\OAuthBundle\Security\OAuthUtils; use PHPUnit\Framework\TestCase; +use RuntimeException; use Symfony\Bundle\SecurityBundle\Security\FirewallConfig; use Symfony\Bundle\SecurityBundle\Security\FirewallMap; use Symfony\Component\DependencyInjection\ServiceLocator; @@ -192,7 +193,7 @@ public function testSignatureIsGeneratedCorrectly(string $signature, string $url */ public function testThrowsExceptionIfRequiredParameterIsMissing(array $parameters): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); OAuthUtils::signRequest('GET', 'http://example.com', $parameters, 'client_secret'); } @@ -267,7 +268,7 @@ public function provideServiceAuthUrlsWithState(): iterable $stateAsArray = []; foreach ($parameters as $key => $value) { - $stateAsArray[] = sprintf('state[%s]=%s', $key, rawurlencode($value)); + $stateAsArray[] = \sprintf('state[%s]=%s', $key, rawurlencode($value)); } yield 'state as an array' => [$url.'?'.implode('&', $stateAsArray), $url]; @@ -285,7 +286,7 @@ public function provideAuthorizationUrlsWithState(): iterable $stateAsArray = []; foreach ($parameters as $key => $value) { - $stateAsArray[] = sprintf('state[%s]=%s', $key, rawurlencode($value)); + $stateAsArray[] = \sprintf('state[%s]=%s', $key, rawurlencode($value)); } yield 'state as an array' => [$url, $url.'?'.implode('&', $stateAsArray), $redirect]; From a0ffe6b50a906594d8fa951bb217ce6c2092ef0e Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Tue, 31 Dec 2024 14:42:03 +0100 Subject: [PATCH 2/2] fix issues reported by PHPStan --- phpstan.neon | 1 + .../CompilerPass/ResourceOwnerCompilerPass.php | 4 ++-- src/Security/Http/Firewall/RefreshAccessTokenListener.php | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/phpstan.neon b/phpstan.neon index 216329555..b88ecced5 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -19,3 +19,4 @@ parameters: - '#Parameter \$event of method HWI\\Bundle\\OAuthBundle\\Controller\\Connect\\AbstractController::dispatch\(\) has invalid type Symfony\\Component\\EventDispatcher\\Event.#' - '#Parameter \#2 \$array of function implode expects array, array given.#' - '#PHPDoc type DOMNode of property HWI\\Bundle\\OAuthBundle\\OAuth\\Response\\SensioConnectUserResponse::\$data is not covariant with PHPDoc type array of overridden property HWI\\Bundle\\OAuthBundle\\OAuth\\Response\\AbstractUserResponse::\$data#' + - '#Call to function method_exists\(\) with Symfony\\Component\\Security\\Http\\Authenticator\\Debug\\TraceableAuthenticator#' diff --git a/src/DependencyInjection/CompilerPass/ResourceOwnerCompilerPass.php b/src/DependencyInjection/CompilerPass/ResourceOwnerCompilerPass.php index bc822b972..eccab1184 100644 --- a/src/DependencyInjection/CompilerPass/ResourceOwnerCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/ResourceOwnerCompilerPass.php @@ -67,11 +67,11 @@ private function registerResourceOwnerTypeClassParameters(ContainerBuilder $cont $resourceOwnerClass = $definition->getClass(); // Check whether a ResourceOwner class exists only if resource owner was set by its "options.type" - if (false === preg_match('~^%(?Phwi_oauth.resource_owner.(?P.+).class)%$~', $resourceOwnerClass, $match)) { + if (false === $result = preg_match('~^%(?Phwi_oauth.resource_owner.(?P.+).class)%$~', $resourceOwnerClass, $match)) { return; } - if (!($match['type'] ?? null)) { + if (0 === $result || !$match['type']) { continue; } diff --git a/src/Security/Http/Firewall/RefreshAccessTokenListener.php b/src/Security/Http/Firewall/RefreshAccessTokenListener.php index 2407f4b73..c9598d8db 100644 --- a/src/Security/Http/Firewall/RefreshAccessTokenListener.php +++ b/src/Security/Http/Firewall/RefreshAccessTokenListener.php @@ -40,7 +40,7 @@ protected function refreshToken(OAuthToken $token): OAuthToken return $this->authenticator->refreshToken($token); } - if ($this->authenticator instanceof TraceableAuthenticator) { + if ($this->authenticator instanceof TraceableAuthenticator && method_exists($this->authenticator, 'getAuthenticator')) { $authenticator = $this->authenticator->getAuthenticator(); if ($authenticator instanceof OAuthAuthenticator) {