*/ public static function decode( string $text ): Result { if ( 1 !== preg_match( '/\A[A-Za-z0-9_-]*\z/', $text ) ) { return Result::err( 'base64url_invalid', 'not unpadded base64url' ); } if ( 1 === strlen( $text ) % 4 ) { return Result::err( 'base64url_invalid', 'impossible unpadded base64url length' ); } $padded = strtr( $text, '-_', '+/' ) . str_repeat( '=', ( 4 - strlen( $text ) % 4 ) % 4 ); $decoded = base64_decode( $padded, true ); if ( false === $decoded ) { return Result::err( 'base64url_invalid', 'not decodable' ); } // A non-canonical encoding — trailing bits that are not zero — decodes to // bytes that re-encode differently. Refuse those too. if ( self::encode( $decoded ) !== $text ) { return Result::err( 'base64url_invalid', 'non-canonical base64url encoding' ); } return Result::ok( $decoded ); } }