Skip to content

Commit f49d9ba

Browse files
committed
Allow using dot separated field names for Identity::get()
1 parent 1c8bd69 commit f49d9ba

File tree

3 files changed

+27
-7
lines changed

3 files changed

+27
-7
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
"require": {
2626
"php": ">=8.1",
2727
"cakephp/http": "^5.0",
28+
"cakephp/utility": "^5.0",
2829
"laminas/laminas-diactoros": "^3.0",
2930
"psr/http-client": "^1.0",
3031
"psr/http-message": "^1.1 || ^2.0",

src/Identity.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use ArrayAccess;
2020
use BadMethodCallException;
2121
use Cake\Core\InstanceConfigTrait;
22+
use Cake\Utility\Hash;
2223

2324
/**
2425
* Identity object
@@ -92,21 +93,21 @@ public function __isset(string $field): bool
9293
/**
9394
* Get data from the identity
9495
*
95-
* @param string $field Field in the user data.
96+
* @param string|null $field Field in the user data.
9697
* @return mixed
9798
*/
98-
public function get(string $field): mixed
99+
public function get(?string $field = null): mixed
99100
{
101+
if ($field === null) {
102+
return $this->data;
103+
}
104+
100105
$map = $this->_config['fieldMap'];
101106
if (isset($map[$field])) {
102107
$field = $map[$field];
103108
}
104109

105-
if (isset($this->data[$field])) {
106-
return $this->data[$field];
107-
}
108-
109-
return null;
110+
return Hash::get($this->data, $field);
110111
}
111112

112113
/**

tests/TestCase/IdentityTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use ArrayObject;
2020
use Authentication\Identity;
2121
use BadMethodCallException;
22+
use Cake\ORM\Entity;
2223
use Cake\TestSuite\TestCase;
2324

2425
class IdentityTest extends TestCase
@@ -43,6 +44,23 @@ public function testGetIdentifier()
4344
$this->assertSame('florian', $identity->username);
4445
}
4546

47+
public function testGet(): void
48+
{
49+
$data = new Entity([
50+
'id' => 1,
51+
'username' => 'florian',
52+
'account' => new Entity(['id' => 2, 'role' => 'admin']),
53+
]);
54+
55+
$identity = new Identity($data);
56+
57+
$this->assertSame(1, $identity->get('id'));
58+
$this->assertSame('florian', $identity->get('username'));
59+
$this->assertSame('admin', $identity->get('account.role'));
60+
$this->assertNull($identity->get('missing'));
61+
$this->assertSame($data, $identity->get());
62+
}
63+
4664
/**
4765
* Test mapping fields
4866
*

0 commit comments

Comments
 (0)