From 2581405d9d7f543ecc97c6455bcb0d2e1b2e6d13 Mon Sep 17 00:00:00 2001 From: fadrian06 Date: Thu, 2 Apr 2026 09:46:55 -0400 Subject: [PATCH] allow to use league/oauth2-google without leafs/leaf --- composer.json | 4 ++-- src/Auth.php | 33 +++++++++++++++++++++++---------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/composer.json b/composer.json index 13676ea..65dc9b2 100644 --- a/composer.json +++ b/composer.json @@ -52,9 +52,9 @@ "phpstan/phpstan": "^2.1", "phpstan/extension-installer": "^1.4", "leafs/leaf": "^4.4", - "league/oauth2-google": "^4.0", "leafs/billing": "^0.2.0", - "rector/rector": "^2.2" + "rector/rector": "^2.2", + "league/oauth2-google": "^5.0" }, "scripts": { "alchemy": "./vendor/bin/alchemy setup", diff --git a/src/Auth.php b/src/Auth.php index 2d4b3ee..aceacf5 100644 --- a/src/Auth.php +++ b/src/Auth.php @@ -98,22 +98,35 @@ public function __construct() }); } - if ( - class_exists('League\OAuth2\Client\Provider\Google') && - _env('GOOGLE_AUTH_CLIENT_ID') && - _env('GOOGLE_AUTH_CLIENT_SECRET') - ) { + if ($this->env('GOOGLE_AUTH_CLIENT_ID') && $this->env('GOOGLE_AUTH_CLIENT_SECRET') && class_exists(Google::class)) { $this->withGoogle( - _env('GOOGLE_AUTH_CLIENT_ID'), - _env('GOOGLE_AUTH_CLIENT_SECRET'), + $this->env('GOOGLE_AUTH_CLIENT_ID'), + $this->env('GOOGLE_AUTH_CLIENT_SECRET'), [ 'name' => 'google', - 'redirectUri' => _env('GOOGLE_AUTH_REDIRECT_URI', _env('APP_URL') . '/auth/register/google'), + 'redirectUri' => $this->env( + 'GOOGLE_AUTH_REDIRECT_URI', + $this->env('APP_URL') . '/auth/register/google' + ) ?: '', ] ); } } + /** @return mixed Returns the value of the environment variable by using Leaf's `_env` primarily */ + private function env(string $name, $default = false) + { + // If `_env` function of Leaf is defined, use it. + if (function_exists('_env')) { + return _env($name, $default); + } + + // Return the value if found, otherwise false like getenv(). + return $_ENV[$name] ?? $default; + } + + /** + /** * Connect leaf auth to the database * @param array{ @@ -171,7 +184,7 @@ public function dbConnection(PDO $connection) * @param array{ * name?: string, * redirectUri?: string, - * } $options + * } $options If `$options['redirectUri']` is not set, it will default to `$_ENV['APP_URL']/auth/google/callback` * @return static */ public function withGoogle( @@ -184,7 +197,7 @@ public function withGoogle( unset($options['name']); if (!isset($options['redirectUri'])) { - $options['redirectUri'] = _env('APP_URL') . '/auth/google/callback'; + $options['redirectUri'] = $this->env('APP_URL') . '/auth/google/callback'; } $this->withProvider($clientName, new Google(array_merge([