vendor/auth0/auth0-php/src/Configuration/SdkConfiguration.php line 221

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Auth0\SDK\Configuration;
  4. use Auth0\SDK\Contract\ConfigurableContract;
  5. use Auth0\SDK\Contract\StoreInterface;
  6. use Auth0\SDK\Exception\ConfigurationException;
  7. use Auth0\SDK\Mixins\ConfigurableMixin;
  8. use Auth0\SDK\Store\CookieStore;
  9. use Auth0\SDK\Utility\EventDispatcher;
  10. use Http\Discovery\Exception\NotFoundException;
  11. use Http\Discovery\Psr17FactoryDiscovery;
  12. use Http\Discovery\Psr18ClientDiscovery;
  13. use Psr\Cache\CacheItemPoolInterface;
  14. use Psr\EventDispatcher\ListenerProviderInterface;
  15. use Psr\Http\Client\ClientInterface;
  16. use Psr\Http\Message\RequestFactoryInterface;
  17. use Psr\Http\Message\ResponseFactoryInterface;
  18. use Psr\Http\Message\StreamFactoryInterface;
  19. /**
  20.  * Configuration container for use with Auth0\SDK
  21.  *
  22.  * @method SdkConfiguration setAudience(?array $audience = null)
  23.  * @method SdkConfiguration setCookieDomain(?string $cookieDomain = null)
  24.  * @method SdkConfiguration setCookieExpires(int $cookieExpires = 0)
  25.  * @method SdkConfiguration setCookiePath(string $cookiePath = '/')
  26.  * @method SdkConfiguration setCookieSameSite(?string $cookieSameSite)
  27.  * @method SdkConfiguration setCookieSecret(?string $cookieSecret)
  28.  * @method SdkConfiguration setCookieSecure(bool $cookieSecure = false)
  29.  * @method SdkConfiguration setClientId(?string $clientId = null)
  30.  * @method SdkConfiguration setClientSecret(?string $clientSecret = null)
  31.  * @method SdkConfiguration setDomain(?string $domain = null)
  32.  * @method SdkConfiguration setCustomDomain(?string $customDomain = null)
  33.  * @method SdkConfiguration setEventListenerProvider(?ListenerProviderInterface $eventListenerProvider = null)
  34.  * @method SdkConfiguration setHttpClient(?ClientInterface $httpClient = null)
  35.  * @method SdkConfiguration setHttpMaxRetries(int $httpMaxRetires = 3)
  36.  * @method SdkConfiguration setHttpRequestFactory(?RequestFactoryInterface $httpRequestFactory = null)
  37.  * @method SdkConfiguration setHttpResponseFactory(?ResponseFactoryInterface $httpResponseFactory = null)
  38.  * @method SdkConfiguration setHttpStreamFactory(?StreamFactoryInterface $httpStreamFactory = null)
  39.  * @method SdkConfiguration setHttpTelemetry(bool $httpTelemetry = true)
  40.  * @method SdkConfiguration setManagementToken(?string $managementToken = null)
  41.  * @method SdkConfiguration setManagementTokenCache(?CacheItemPoolInterface $cache = null)
  42.  * @method SdkConfiguration setOrganization(?array $organization = null)
  43.  * @method SdkConfiguration setPersistAccessToken(bool $persistAccessToken = true)
  44.  * @method SdkConfiguration setPersistIdToken(bool $persistIdToken = true)
  45.  * @method SdkConfiguration setPersistRefreshToken(bool $persistRefreshToken = true)
  46.  * @method SdkConfiguration setPersistUser(bool $persistUser = true)
  47.  * @method SdkConfiguration setQueryUserInfo(bool $queryUserInfo = false)
  48.  * @method SdkConfiguration setRedirectUri(?string $redirectUri = null)
  49.  * @method SdkConfiguration setResponseMode(string $responseMode = 'query')
  50.  * @method SdkConfiguration setResponseType(string $responseType = 'code')
  51.  * @method SdkConfiguration setScope(?array $scope = null)
  52.  * @method SdkConfiguration setSessionStorage(?StoreInterface $sessionStorage = null)
  53.  * @method SdkConfiguration setSessionStorageId(string $sessionStorageId = 'auth0_session')
  54.  * @method SdkConfiguration setStrategy(string $strategy = 'webapp')
  55.  * @method SdkConfiguration setTokenAlgorithm(string $tokenAlgorithm = 'RS256')
  56.  * @method SdkConfiguration setTokenCache(?CacheItemPoolInterface $cache = null)
  57.  * @method SdkConfiguration setTokenCacheTtl(int $tokenCacheTtl = 60)
  58.  * @method SdkConfiguration setTokenJwksUri(?string $tokenJwksUri = null)
  59.  * @method SdkConfiguration setTokenLeeway(int $tokenLeeway = 60)
  60.  * @method SdkConfiguration setTokenMaxAge(?int $tokenMaxAge = null)
  61.  * @method SdkConfiguration setTransientStorage(?StoreInterface $transientStorage = null)
  62.  * @method SdkConfiguration setTransientStorageId(string $transientStorageId = 'auth0_transient')
  63.  * @method SdkConfiguration setUsePkce(bool $usePkce)
  64.  *
  65.  * @method array<string>|null getAudience(?\Throwable $exceptionIfNull = null)
  66.  * @method string|null getCookieDomain(?\Throwable $exceptionIfNull = null)
  67.  * @method int getCookieExpires()
  68.  * @method string getCookiePath()
  69.  * @method string|null getCookieSameSite(?\Throwable $exceptionIfNull = null)
  70.  * @method string|null getCookieSecret(?\Throwable $exceptionIfNull = null)
  71.  * @method bool getCookieSecure()
  72.  * @method string|null getClientId(?\Throwable $exceptionIfNull = null)
  73.  * @method string|null getClientSecret(?\Throwable $exceptionIfNull = null)
  74.  * @method string|string getDomain(?\Throwable $exceptionIfNull = null)
  75.  * @method string|string getCustomDomain(?\Throwable $exceptionIfNull = null)
  76.  * @method ListenerProviderInterface|null getEventListenerProvider(?\Throwable $exceptionIfNull = null)
  77.  * @method ClientInterface|null getHttpClient(?\Throwable $exceptionIfNull = null)
  78.  * @method int getHttpMaxRetries()
  79.  * @method RequestFactoryInterface|null getHttpRequestFactory(?\Throwable $exceptionIfNull = null)
  80.  * @method ResponseFactoryInterface|null getHttpResponseFactory(?\Throwable $exceptionIfNull = null)
  81.  * @method StreamFactoryInterface|null getHttpStreamFactory(?\Throwable $exceptionIfNull = null)
  82.  * @method bool getHttpTelemetry()
  83.  * @method string|null getManagementToken(?\Throwable $exceptionIfNull = null)
  84.  * @method CacheItemPoolInterface|null getManagementTokenCache(?\Throwable $exceptionIfNull = null)
  85.  * @method array<string>|null getOrganization(?\Throwable $exceptionIfNull = null)
  86.  * @method bool getPersistAccessToken()
  87.  * @method bool getPersistIdToken()
  88.  * @method bool getPersistRefreshToken()
  89.  * @method bool getPersistUser()
  90.  * @method bool getQueryUserInfo()
  91.  * @method string|null getRedirectUri(?\Throwable $exceptionIfNull = null)
  92.  * @method string getResponseMode()
  93.  * @method string getResponseType()
  94.  * @method array<string> getScope()
  95.  * @method StoreInterface|null getSessionStorage(?\Throwable $exceptionIfNull = null)
  96.  * @method string getSessionStorageId()
  97.  * @method string getStrategy()
  98.  * @method string getTokenAlgorithm()
  99.  * @method CacheItemPoolInterface|null getTokenCache(?\Throwable $exceptionIfNull = null)
  100.  * @method int getTokenCacheTtl()
  101.  * @method string|null getTokenJwksUri(?\Throwable $exceptionIfNull = null)
  102.  * @method int|null getTokenLeeway(?\Throwable $exceptionIfNull = null)
  103.  * @method int|null getTokenMaxAge(?\Throwable $exceptionIfNull = null)
  104.  * @method StoreInterface|null getTransientStorage(?\Throwable $exceptionIfNull = null)
  105.  * @method string getTransientStorageId()
  106.  * @method bool getUsePkce()
  107.  *
  108.  * @method bool hasAudience()
  109.  * @method bool hasCookieDomain()
  110.  * @method bool hasCookieExpires()
  111.  * @method bool hasCookiePath()
  112.  * @method bool hasCookieSameSite()
  113.  * @method bool hasCookieSecret()
  114.  * @method bool hasCookieSecure()
  115.  * @method bool hasClientId()
  116.  * @method bool hasClientSecret()
  117.  * @method bool hasDomain()
  118.  * @method bool hasCustomDomain()
  119.  * @method bool hasEventListenerProvider()
  120.  * @method bool hasHttpClient()
  121.  * @method bool hasHttpMaxRetries()
  122.  * @method bool hasHttpRequestFactory()
  123.  * @method bool hasHttpResponseFactory()
  124.  * @method bool hasHttpStreamFactory()
  125.  * @method bool hasHttpTelemetry()
  126.  * @method bool hasManagementToken()
  127.  * @method bool hasManagementTokenCache()
  128.  * @method bool hasOrganization()
  129.  * @method bool hasPersistAccessToken()
  130.  * @method bool hasPersistIdToken()
  131.  * @method bool hasPersistRefreshToken()
  132.  * @method bool hasPersistUser()
  133.  * @method bool hasQueryUserInfo()
  134.  * @method bool hasRedirectUri()
  135.  * @method bool hasResponseMode()
  136.  * @method bool hasResponseType()
  137.  * @method bool hasScope()
  138.  * @method bool hasSessionStorage()
  139.  * @method bool hasSessionStorageId()
  140.  * @method bool hasStrategy()
  141.  * @method bool hasTokenAlgorithm()
  142.  * @method bool hasTokenCache()
  143.  * @method bool hasTokenCacheTtl()
  144.  * @method bool hasTokenLeeway()
  145.  * @method bool hasTokenMaxAge()
  146.  * @method bool hasTransientStorage()
  147.  * @method bool hasTransientStorageId()
  148.  * @method bool hasUsePkce()
  149.  *
  150.  * @method bool pushScope($scope)
  151.  * @method bool pushAudience($audience)
  152.  * @method bool pushOrganization($organization)
  153.  */
  154. final class SdkConfiguration implements ConfigurableContract
  155. {
  156.     use ConfigurableMixin;
  157.     public const STRATEGY_REGULAR 'webapp';
  158.     public const STRATEGY_API 'api';
  159.     public const STRATEGY_MANAGEMENT_API 'management';
  160.     public const STRATEGY_NONE 'none';
  161.     /**
  162.      * An instance of the EventDispatcher utility.
  163.      */
  164.     private ?EventDispatcher $eventDispatcher null;
  165.     /**
  166.      * SdkConfiguration Constructor
  167.      *
  168.      * @param array<mixed>|null              $configuration         An key-value array matching this constructor's arguments. Overrides any other passed arguments with the same key name.
  169.      * @param string|null                    $strategy              Defaults to 'webapp'. Should be assigned either 'api', 'management', or 'webapp' to specify the type of application the SDK is being applied to. Determines what configuration options will be required at initialization.
  170.      * @param string|null                    $domain                Auth0 domain for your tenant, found in your Auth0 Application settings.
  171.      * @param string|null                    $customDomain          If you have configured Auth0 to use a custom domain, configure it here.
  172.      * @param string|null                    $clientId              Client ID, found in the Auth0 Application settings.
  173.      * @param string|null                    $redirectUri           Authentication callback URI, as defined in your Auth0 Application settings.
  174.      * @param string|null                    $clientSecret          Client Secret, found in the Auth0 Application settings.
  175.      * @param array<string>|null             $audience              One or more API identifiers, found in your Auth0 API settings. The SDK uses the first value for building links. If provided, at least one of these values must match the 'aud' claim to validate an ID Token successfully.
  176.      * @param array<string>|null             $organization          One or more Organization IDs, found in your Auth0 Organization settings. The SDK uses the first value for building links. If provided, at least one of these values must match the 'org_id' claim to validate an ID Token successfully.
  177.      * @param bool                           $usePkce               Defaults to true. Use PKCE (Proof Key of Code Exchange) with Authorization Code Flow requests. See https://auth0.com/docs/flows/call-your-api-using-the-authorization-code-flow-with-pkce
  178.      * @param array<string>                  $scope                 One or more scopes to request for Tokens. See https://auth0.com/docs/scopes
  179.      * @param string                         $responseMode          Defaults to 'query.' Where to extract request parameters from, either 'query' for GET or 'form_post' for POST requests.
  180.      * @param string                         $responseType          Defaults to 'code.' Use 'code' for server-side flows and 'token' for application side flow.
  181.      * @param string                         $tokenAlgorithm        Defaults to 'RS256'. Algorithm to use for Token verification. Expects either 'RS256' or 'HS256'.
  182.      * @param string|null                    $tokenJwksUri          URI to the JWKS when verifying RS256 tokens.
  183.      * @param int|null                       $tokenMaxAge           The maximum window of time (in seconds) since the 'auth_time' to accept during Token validation.
  184.      * @param int                            $tokenLeeway           Defaults to 60. Leeway (in seconds) to allow during time calculations with Token validation.
  185.      * @param CacheItemPoolInterface|null    $tokenCache            A PSR-6 compatible cache adapter for storing JSON Web Key Sets (JWKS).
  186.      * @param int                            $tokenCacheTtl         How long (in seconds) to keep a JWKS cached.
  187.      * @param ClientInterface|null           $httpClient            A PSR-18 compatible HTTP client to use for API requests.
  188.      * @param int                            $httpMaxRetries        When a rate-limit (429 status code) response is returned from the Auth0 API, automatically retry the request up to this many times.
  189.      * @param RequestFactoryInterface|null   $httpRequestFactory    A PSR-17 compatible request factory to generate HTTP requests.
  190.      * @param ResponseFactoryInterface|null  $httpResponseFactory   A PSR-17 compatible response factory to generate HTTP responses.
  191.      * @param StreamFactoryInterface|null    $httpStreamFactory     A PSR-17 compatible stream factory to create request body streams.
  192.      * @param bool                           $httpTelemetry         Defaults to true. If true, API requests will include telemetry about the SDK and PHP runtime version to help us improve our services.
  193.      * @param StoreInterface|null            $sessionStorage        Defaults to use cookies. A StoreInterface-compatible class for storing Token state.
  194.      * @param string                         $sessionStorageId      Defaults to 'auth0_session'. The namespace to prefix session items under.
  195.      * @param string|null                    $cookieSecret          The secret used to derive an encryption key for the user identity in a session cookie and to sign the transient cookies used by the login callback.
  196.      * @param string|null                    $cookieDomain          Defaults to value of HTTP_HOST server environment information. Cookie domain, for example 'www.example.com', for use with PHP sessions and SDK cookies. To make cookies visible on all subdomains then the domain must be prefixed with a dot like '.example.com'.
  197.      * @param int                            $cookieExpires         Defaults to 0. How long, in seconds, before cookies expire. If set to 0 the cookie will expire at the end of the session (when the browser closes).
  198.      * @param string                         $cookiePath            Defaults to '/'. Specifies path on the domain where the cookies will work. Use a single slash ('/') for all paths on the domain.
  199.      * @param string|null                    $cookieSameSite        Defaults to 'lax'. Specifies whether cookies should be restricted to first-party or same-site context.
  200.      * @param bool                           $cookieSecure          Defaults to false. Specifies whether cookies should ONLY be sent over secure connections.
  201.      * @param bool                           $persistUser           Defaults to true. If true, the user data will persist in session storage.
  202.      * @param bool                           $persistIdToken        Defaults to true. If true, the Id Token will persist in session storage.
  203.      * @param bool                           $persistAccessToken    Defaults to true. If true, the Access Token will persist in session storage.
  204.      * @param bool                           $persistRefreshToken   Defaults to true. If true, the Refresh Token will persist in session storage.
  205.      * @param StoreInterface|null            $transientStorage      Defaults to use cookies. A StoreInterface-compatible class for storing ephemeral state data, such as nonces.
  206.      * @param string                         $transientStorageId    Defaults to 'auth0_transient'. The namespace to prefix transient items under.
  207.      * @param bool                           $queryUserInfo         Defaults to false. If true, query the /userinfo endpoint during an authorization code exchange.
  208.      * @param string|null                    $managementToken       An Access Token to use for Management API calls. If there isn't one specified, the SDK will attempt to get one for you using your $clientSecret.
  209.      * @param CacheItemPoolInterface|null    $managementTokenCache  A PSR-6 compatible cache adapter for storing generated management access tokens.
  210.      * @param ListenerProviderInterface|null $eventListenerProvider A PSR-14 compatible event listener provider, for interfacing with events triggered by the SDK.
  211.      *
  212.      * @throws \Auth0\SDK\Exception\ConfigurationException When a valid `$strategy` is not specified.
  213.      */
  214.     public function __construct(
  215.         ?array $configuration null,
  216.         ?string $strategy 'webapp',
  217.         ?string $domain null,
  218.         ?string $customDomain null,
  219.         ?string $clientId null,
  220.         ?string $redirectUri null,
  221.         ?string $clientSecret null,
  222.         ?array $audience null,
  223.         ?array $organization null,
  224.         bool $usePkce true,
  225.         array $scope = ['openid''profile''email'],
  226.         string $responseMode 'query',
  227.         string $responseType 'code',
  228.         string $tokenAlgorithm 'RS256',
  229.         ?string $tokenJwksUri null,
  230.         ?int $tokenMaxAge null,
  231.         int $tokenLeeway 60,
  232.         ?CacheItemPoolInterface $tokenCache null,
  233.         int $tokenCacheTtl 60,
  234.         ?ClientInterface $httpClient null,
  235.         int $httpMaxRetries 3,
  236.         ?RequestFactoryInterface $httpRequestFactory null,
  237.         ?ResponseFactoryInterface $httpResponseFactory null,
  238.         ?StreamFactoryInterface $httpStreamFactory null,
  239.         bool $httpTelemetry true,
  240.         ?StoreInterface $sessionStorage null,
  241.         string $sessionStorageId 'auth0_session',
  242.         ?string $cookieSecret null,
  243.         ?string $cookieDomain null,
  244.         int $cookieExpires 0,
  245.         string $cookiePath '/',
  246.         bool $cookieSecure false,
  247.         ?string $cookieSameSite null,
  248.         bool $persistUser true,
  249.         bool $persistIdToken true,
  250.         bool $persistAccessToken true,
  251.         bool $persistRefreshToken true,
  252.         ?StoreInterface $transientStorage null,
  253.         string $transientStorageId 'auth0_transient',
  254.         bool $queryUserInfo false,
  255.         ?string $managementToken null,
  256.         ?CacheItemPoolInterface $managementTokenCache null,
  257.         ?ListenerProviderInterface $eventListenerProvider null
  258.     ) {
  259.         $this->setState(func_get_args());
  260.         $this->setupStateCookies();
  261.         $this->setupStateFactories();
  262.         $this->setupStateStorage();
  263.         $this->validateState();
  264.     }
  265.     /**
  266.      * Return the configured custom or tenant domain, formatted with protocol.
  267.      *
  268.      * @param bool $forceTenantDomain Force the return of the tenant domain even if a custom domain is configured.
  269.      */
  270.     public function formatDomain(
  271.         bool $forceTenantDomain false
  272.     ): string {
  273.         if ($this->hasCustomDomain() && ! $forceTenantDomain) {
  274.             return 'https://' $this->getCustomDomain();
  275.         }
  276.         return 'https://' $this->getDomain();
  277.     }
  278.     /**
  279.      * Return the configured domain with protocol.
  280.      */
  281.     public function formatCustomDomain(): ?string
  282.     {
  283.         if ($this->hasCustomDomain()) {
  284.             return 'https://' $this->getCustomDomain();
  285.         }
  286.         return null;
  287.     }
  288.     /**
  289.      * Return the configured scopes as a space-delimited string.
  290.      */
  291.     public function formatScope(): ?string
  292.     {
  293.         if ($this->hasScope()) {
  294.             $scope $this->getScope();
  295.             if ($scope !== []) {
  296.                 return implode(' '$scope);
  297.             }
  298.         }
  299.         return null;
  300.     }
  301.     /**
  302.      * Get the first configured organization.
  303.      */
  304.     public function defaultOrganization(): ?string
  305.     {
  306.         // Return the default organization.
  307.         if ($this->hasOrganization()) {
  308.             $organization $this->getOrganization();
  309.             if ($organization !== null && $organization !== []) {
  310.                 return $organization[0];
  311.             }
  312.         }
  313.         return null;
  314.     }
  315.     /**
  316.      * Get the first configured audience.
  317.      */
  318.     public function defaultAudience(): ?string
  319.     {
  320.         // Return the default audience.
  321.         if ($this->hasAudience()) {
  322.             $audience $this->getAudience();
  323.             if ($audience !== null && $audience !== []) {
  324.                 return $audience[0] ?? '';
  325.             }
  326.         }
  327.         return null;
  328.     }
  329.     /**
  330.      * Get an instance of the EventDispatcher.
  331.      */
  332.     public function eventDispatcher(): EventDispatcher
  333.     {
  334.         if ($this->eventDispatcher === null) {
  335.             $this->eventDispatcher = new EventDispatcher($this);
  336.         }
  337.         return $this->eventDispatcher;
  338.     }
  339.     /**
  340.      * Setup SDK cookie state.
  341.      */
  342.     private function setupStateCookies(): void
  343.     {
  344.         if (! $this->hasCookieDomain()) {
  345.             $domain $_SERVER['HTTP_HOST'] ?? $this->getRedirectUri();
  346.             if ($domain !== null) {
  347.                 $parsed parse_url($domainPHP_URL_HOST);
  348.                 if (is_string($parsed)) {
  349.                     $domain $parsed;
  350.                 }
  351.                 if ($domain) {
  352.                     $this->setCookieDomain($domain);
  353.                 }
  354.             }
  355.         }
  356.     }
  357.     /**
  358.      * Setup SDK factories.
  359.      *
  360.      * @throws NotFoundException When a PSR-18 or PSR-17 are not configured, and cannot be discovered.
  361.      *
  362.      * @codeCoverageIgnore
  363.      */
  364.     private function setupStateFactories(): void
  365.     {
  366.         // If a PSR-18 compatible client wasn't provided, try to discover one.
  367.         if (! $this->getHttpClient() instanceof ClientInterface) {
  368.             try {
  369.                 $this->setHttpClient(Psr18ClientDiscovery::find());
  370.             } catch (\Throwable $th) {
  371.                 throw \Auth0\SDK\Exception\ConfigurationException::missingPsr18Library();
  372.             }
  373.         }
  374.         // If a PSR-17 compatible request factory wasn't provided, try to discover one.
  375.         if (! $this->getHttpRequestFactory() instanceof RequestFactoryInterface) {
  376.             try {
  377.                 $this->setHttpRequestFactory(Psr17FactoryDiscovery::findRequestFactory());
  378.             } catch (NotFoundException $exception) {
  379.                 throw \Auth0\SDK\Exception\ConfigurationException::missingPsr17Library();
  380.             }
  381.         }
  382.         // If a PSR-17 compatible response factory wasn't provided, try to discover one.
  383.         if (! $this->getHttpResponseFactory() instanceof ResponseFactoryInterface) {
  384.             try {
  385.                 $this->setHttpResponseFactory(Psr17FactoryDiscovery::findResponseFactory());
  386.             } catch (NotFoundException $exception) {
  387.                 throw \Auth0\SDK\Exception\ConfigurationException::missingPsr17Library();
  388.             }
  389.         }
  390.         // If a PSR-17 compatible stream factory wasn't provided, try to discover one.
  391.         if (! $this->getHttpStreamFactory() instanceof StreamFactoryInterface) {
  392.             try {
  393.                 $this->setHttpStreamFactory(Psr17FactoryDiscovery::findStreamFactory());
  394.             } catch (NotFoundException $exception) {
  395.                 throw \Auth0\SDK\Exception\ConfigurationException::missingPsr17Library();
  396.             }
  397.         }
  398.     }
  399.     /**
  400.      * Setup SDK storage state.
  401.      */
  402.     private function setupStateStorage(): void
  403.     {
  404.         if (! $this->getSessionStorage() instanceof StoreInterface) {
  405.             $this->setSessionStorage(new CookieStore($this$this->getSessionStorageId()));
  406.         }
  407.         if (! $this->getTransientStorage() instanceof StoreInterface) {
  408.             $this->setTransientStorage(new CookieStore($this$this->getTransientStorageId()));
  409.         }
  410.     }
  411.     /**
  412.      * Fires when the configuration state changes, to ensure changes are formatted correctly.
  413.      *
  414.      * @param string $propertyName The property being mutated.
  415.      * @param mixed  $propertyValue The new value of the property.
  416.      *
  417.      * @return mixed
  418.      *
  419.      * @throws ConfigurationException When a validation check for the mutation fails to pass, such as a incompatible type being used.
  420.      */
  421.     private function onStateChange(
  422.         string $propertyName,
  423.         $propertyValue
  424.     ) {
  425.         if ($propertyValue === null) {
  426.             return $propertyValue;
  427.         }
  428.         if ($propertyName === 'strategy') {
  429.             if (is_string($propertyValue) && mb_strlen($propertyValue) !== 0) {
  430.                 $propertyValue mb_strtolower($propertyValue);
  431.                 if (in_array($propertyValue, [self::STRATEGY_REGULARself::STRATEGY_APIself::STRATEGY_MANAGEMENT_APIself::STRATEGY_NONE], true)) {
  432.                     return $propertyValue;
  433.                 }
  434.             }
  435.             throw \Auth0\SDK\Exception\ConfigurationException::validationFailed($propertyName);
  436.         }
  437.         if ($propertyName === 'domain' || $propertyName === 'customDomain') {
  438.             if (is_string($propertyValue)) {
  439.                 $propertyValue trim($propertyValue);
  440.                 if (strlen($propertyValue) !== 0) {
  441.                     $host preg_replace('#^[^:/.]*[:/]+#i'''$propertyValue);
  442.                     $host parse_url('https://' $hostPHP_URL_HOST);
  443.                     $host filter_var($hostFILTER_SANITIZE_URLFILTER_NULL_ON_FAILURE);
  444.                     if (is_string($host) && strlen($host) !== && filter_var($hostFILTER_VALIDATE_DOMAINFILTER_FLAG_HOSTNAME) !== false) {
  445.                         return $host;
  446.                     }
  447.                 }
  448.             }
  449.             throw \Auth0\SDK\Exception\ConfigurationException::validationFailed($propertyName);
  450.         }
  451.         if ($propertyName === 'tokenAlgorithm' && ! in_array($propertyValue, ['HS256''RS256'], true)) {
  452.             throw \Auth0\SDK\Exception\ConfigurationException::invalidAlgorithm();
  453.         }
  454.         if (in_array($propertyName, ['organization''audience'], true)) {
  455.             if (is_array($propertyValue) && $propertyValue !== []) {
  456.                 return $propertyValue;
  457.             }
  458.             return null;
  459.         }
  460.         return $propertyValue;
  461.     }
  462.     /**
  463.      * Setup SDK validators based on strategy type.
  464.      */
  465.     private function validateState(
  466.         ?string $strategy null
  467.     ): void {
  468.         $strategy $strategy ?? $this->getStrategy();
  469.         if ($strategy === self::STRATEGY_REGULAR) {
  470.             $this->validateStateWebApp();
  471.         }
  472.         if ($strategy === self::STRATEGY_API) {
  473.             $this->validateStateApi();
  474.         }
  475.         if ($strategy === self::STRATEGY_MANAGEMENT_API) {
  476.             $this->validateStateManagement();
  477.         }
  478.     }
  479.     /**
  480.      * Run validations for an API-only usage configuration.
  481.      */
  482.     private function validateStateApi(): void
  483.     {
  484.         if (! $this->hasDomain()) {
  485.             throw \Auth0\SDK\Exception\ConfigurationException::requiresDomain();
  486.         }
  487.         if (! $this->hasAudience()) {
  488.             throw \Auth0\SDK\Exception\ConfigurationException::requiresAudience();
  489.         }
  490.     }
  491.     /**
  492.      * Run validations for a Management-only usage configuration.
  493.      */
  494.     private function validateStateManagement(): void
  495.     {
  496.         if (! $this->hasDomain()) {
  497.             throw \Auth0\SDK\Exception\ConfigurationException::requiresDomain();
  498.         }
  499.         if (! $this->hasManagementToken()) {
  500.             if (! $this->hasClientId()) {
  501.                 throw \Auth0\SDK\Exception\ConfigurationException::requiresClientId();
  502.             }
  503.             if (! $this->hasClientSecret()) {
  504.                 throw \Auth0\SDK\Exception\ConfigurationException::requiresClientSecret();
  505.             }
  506.         }
  507.     }
  508.     /**
  509.      * Run validations for a general webapp usage configuration.
  510.      */
  511.     private function validateStateWebApp(): void
  512.     {
  513.         if (! $this->hasDomain()) {
  514.             throw \Auth0\SDK\Exception\ConfigurationException::requiresDomain();
  515.         }
  516.         if (! $this->hasClientId()) {
  517.             throw \Auth0\SDK\Exception\ConfigurationException::requiresClientId();
  518.         }
  519.         if ($this->getTokenAlgorithm() === 'HS256' && ! $this->hasClientSecret()) {
  520.             throw \Auth0\SDK\Exception\ConfigurationException::requiresClientSecret();
  521.         }
  522.         if (! $this->hasCookieSecret()) {
  523.             throw \Auth0\SDK\Exception\ConfigurationException::requiresCookieSecret();
  524.         }
  525.     }
  526. }