diff --git a/src/UrlHelper.php b/src/UrlHelper.php index 625132c..c34d376 100644 --- a/src/UrlHelper.php +++ b/src/UrlHelper.php @@ -27,10 +27,14 @@ public static function parseQueryTokenFromUrl(string $url, string $queryKey = 't return self::parseTokenFromQueryString($queryString, $queryKey); } - public static function parseTokenFromQueryString(string $queryString, string $queryKey = 'token'): string|array + public static function parseTokenFromQueryString(string $queryString, string $queryKey = 'token'): null|string|array { parse_str($queryString, $output); - return $output[$queryKey]; + if (! isset($output[$queryKey])) { + return null; + } + + return $output[$queryKey] ?? null; } } diff --git a/tests/Unit/UrlHelperTest.php b/tests/Unit/UrlHelperTest.php new file mode 100644 index 0000000..b1a1335 --- /dev/null +++ b/tests/Unit/UrlHelperTest.php @@ -0,0 +1,41 @@ +toEqual($result); +})->with([ + 'normal' => [[['https://example.com/oauth/token?token=this_is_my_access_token_from_url', []], 'token'], 'this_is_my_access_token_from_url'], + 'empty' => [[['https://example.com/oauth/token?token=', []], 'token'], null], + 'custom' => [[['https://example.com/oauth/token?custom=this_is_my_access_token_from_url', []], 'custom'], 'this_is_my_access_token_from_url'], + 'wrong' => [[['https://example.com/oauth/token?token=this_is_my_access_token_from_url', []], 'wrong'], null], +]); + +test('UrLHelper parseQueryTokenFromUrl', function (array $params, ?string $result) { + $token = UrlHelper::parseQueryTokenFromUrl(...$params); + + expect($token)->toEqual($result); +})->with([ + 'normal' => [['https://example.com/oauth/token?token=this_is_my_access_token_from_url'], 'this_is_my_access_token_from_url'], + 'empty' => [['https://example.com/oauth/token'], null], + 'custom' => [['https://example.com/oauth/token?custom=this_is_my_access_token_from_url', 'custom'], 'this_is_my_access_token_from_url'], + 'wrong' => [['https://example.com/oauth/token?token=this_is_my_access_token_from_url', 'wrong'], null], +]); + +test('UrLHelper parseTokenFromQueryString', function ($params, $result) { + + $token = UrlHelper::parseTokenFromQueryString(...$params); + + expect($token)->toEqual($result); +})->with([ + 'normal' => [['token=this_is_my_access_token_from_url'], 'this_is_my_access_token_from_url'], + 'invalid query string' => [['something_random'], null], + 'custom key' => [['key=this_is_another_token_from_url', 'key'], 'this_is_another_token_from_url'], + 'wrong key specified' => [['key=this_is_another_token_from_url', 'other_key'], null], +]);