Skip to content

Commit 95215e4

Browse files
authored
Merge pull request #766 from cakephp/identity-get
Allow using dot separated field names for Identity::get()
2 parents 1c8bd69 + 19df42a commit 95215e4

3 files changed

Lines changed: 32 additions & 8 deletions

File tree

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: 13 additions & 8 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
@@ -90,23 +91,27 @@ public function __isset(string $field): bool
9091
}
9192

9293
/**
93-
* Get data from the identity
94+
* Get data from the identity.
9495
*
95-
* @param string $field Field in the user data.
96+
* You can use dot notation to fetch nested data.
97+
* Calling the method without any argument will return
98+
* the entire data array/object (same as `getOriginalData()`).
99+
*
100+
* @param string|null $field Field in the user data.
96101
* @return mixed
97102
*/
98-
public function get(string $field): mixed
103+
public function get(?string $field = null): mixed
99104
{
105+
if ($field === null) {
106+
return $this->data;
107+
}
108+
100109
$map = $this->_config['fieldMap'];
101110
if (isset($map[$field])) {
102111
$field = $map[$field];
103112
}
104113

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

112117
/**

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)