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; } diff --git a/tests/JWTTest.php b/tests/JWTTest.php index d09d43e3..9e8683dd 100644 --- a/tests/JWTTest.php +++ b/tests/JWTTest.php @@ -82,6 +82,17 @@ public function testValidToken() $this->assertSame($decoded->message, 'abc'); } + public function testValidTokenWithObjectPayload() + { + $payload = (object)[ + 'message' => 'abc', + 'exp' => time() + JWT::$leeway + 20, // time in the future + ]; + $encoded = JWT::encode($payload, 'my_key', 'HS256'); + $decoded = JWT::decode($encoded, new Key('my_key', 'HS256')); + $this->assertSame($decoded->message, 'abc'); + } + /** * @runInSeparateProcess */