From c6d5305450b164287216367eecd10c3952c41ac5 Mon Sep 17 00:00:00 2001 From: Oinkling <> Date: Wed, 7 Aug 2024 12:01:16 +0200 Subject: [PATCH] feat: Allow object as payload Changed JWT::encode and JWT::jsonEncode so that they now accepts an object as well as an array as their first argument --- src/JWT.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/JWT.php b/src/JWT.php index e9d75639..5d14a2f7 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -184,7 +184,7 @@ public static function decode( /** * Converts and signs a PHP array into a JWT string. * - * @param array $payload PHP array + * @param array|object $payload PHP array or object * @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key. * @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256', * 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512' @@ -197,7 +197,7 @@ public static function decode( * @uses urlsafeB64Encode */ public static function encode( - array $payload, + array|object $payload, $key, string $alg, string $keyId = null, @@ -379,13 +379,13 @@ public static function jsonDecode(string $input) /** * Encode a PHP array into a JSON string. * - * @param array $input A PHP array + * @param array|object $input A PHP array or object * - * @return string JSON representation of the PHP array + * @return string JSON representation of the PHP array or object * * @throws DomainException Provided object could not be encoded to valid JSON */ - public static function jsonEncode(array $input): string + public static function jsonEncode(array|object $input): string { if (PHP_VERSION_ID >= 50400) { $json = \json_encode($input, \JSON_UNESCAPED_SLASHES); @@ -399,7 +399,8 @@ public static function jsonEncode(array $input): string throw new DomainException('Null result with non-null input'); } if ($json === false) { - throw new DomainException('Provided object could not be encoded to valid JSON'); + $type = is_array($input) ? 'array' : 'object'; + throw new DomainException('Provided ' . $type . ' could not be encoded to valid JSON'); } return $json; }