Skip to content

Commit

Permalink
Merge pull request #5 from generationtux/json-serialize
Browse files Browse the repository at this point in the history
serialize tokens for json_encode
  • Loading branch information
kyleferguson committed Feb 13, 2016
2 parents 159f40b + dc840fc commit 4438aff
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/.idea
/vendor
18 changes: 17 additions & 1 deletion spec/JwtTokenSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

namespace spec\GenTux\Jwt;

use GenTux\Jwt\JwtPayloadInterface;
use Prophecy\Argument;
use GenTux\Jwt\JwtToken;
use PhpSpec\ObjectBehavior;
use GenTux\Jwt\JwtPayloadInterface;
use GenTux\Jwt\Drivers\FirebaseDriver;
use GenTux\Jwt\Drivers\JwtDriverInterface;
use GenTux\Jwt\Exceptions\NoTokenException;
use PhpSpec\Exception\Example\FailureException;
use GenTux\Jwt\Exceptions\InvalidTokenException;

class JwtTokenSpec extends ObjectBehavior
Expand Down Expand Up @@ -107,4 +109,18 @@ public function it_gets_the_payload_data_from_the_provided_dot_path(JwtDriverInt
$this->payload('context')->shouldReturn(['some' => 'data']);
$this->payload('context.some')->shouldReturn('data');
}

public function it_encodes_to_json_as_a_string_representation_of_the_token(JwtDriverInterface $jwt)
{
$driver = new FirebaseDriver();
$jwt = new JwtToken($driver);
$token = $jwt->createToken(['exp' => time() + 100], 'secret');

$serialized = json_encode(['token' => $token]);
$decoded = json_decode($serialized);

if( ! is_string($decoded->token) || strlen($decoded->token) < 1) {
throw new FailureException('Token was not json encoded.');
}
}
}
17 changes: 16 additions & 1 deletion src/JwtToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

namespace GenTux\Jwt;

use JsonSerializable;
use Illuminate\Support\Arr;
use GenTux\Jwt\Drivers\JwtDriverInterface;
use GenTux\Jwt\Exceptions\NoTokenException;
use GenTux\Jwt\Exceptions\NoSecretException;
use GenTux\Jwt\Exceptions\InvalidTokenException;

class JwtToken
class JwtToken implements JsonSerializable
{

/** @var JwtDriverInterface */
Expand Down Expand Up @@ -236,6 +237,20 @@ public function createToken($payload, $secret = null, $algo = null)
return $token;
}

/**
* Specify data which should be serialized to JSON
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
*
* @return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
*/
public function jsonSerialize()
{
return $this->token();
}


/**
* Convert into string
*
Expand Down

0 comments on commit 4438aff

Please sign in to comment.