Skip to content

Commit

Permalink
Implements __serialize() and __unserialize() PHP 8.1 magic method…
Browse files Browse the repository at this point in the history
…s on Credentials object (#2316)

Sorry for the delay in merging- thank you for the contribution :)
  • Loading branch information
nunomaduro authored Oct 8, 2021
1 parent ddc203c commit da1f6ae
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Credentials/Credentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,23 @@ public function toArray()

public function serialize()
{
return json_encode($this->toArray());
return json_encode($this->__serialize());
}

public function unserialize($serialized)
{
$data = json_decode($serialized, true);

$this->__unserialize($data);
}

public function __serialize()
{
return $this->toArray();
}

public function __unserialize($data)
{
$this->key = $data['key'];
$this->secret = $data['secret'];
$this->token = $data['token'];
Expand Down
22 changes: 22 additions & 0 deletions tests/Credentials/CredentialsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,26 @@ public function testDeterminesIfExpired()
(new Credentials('foo', 'baz', 'tok', time() - 1000))->isExpired()
);
}

public function testSerialization()
{
$credentials = new Credentials('key-value', 'secret-value');
$actual = unserialize(serialize($credentials))->toArray();
$this->assertEquals([
'key' => 'key-value',
'secret' => 'secret-value',
'token' => null,
'expires' => null,
], $actual);

$credentials = new Credentials('key-value', 'secret-value', 'token-value', 10);
$actual = unserialize(serialize($credentials))->toArray();

$this->assertEquals([
'key' => 'key-value',
'secret' => 'secret-value',
'token' => 'token-value',
'expires' => 10,
], $actual);
}
}

0 comments on commit da1f6ae

Please sign in to comment.