From 28e0c828bbbacdc9aca0a46040045df4b350b16d Mon Sep 17 00:00:00 2001 From: Elias Luhr Date: Fri, 13 Jan 2023 14:38:26 +0100 Subject: [PATCH] implement dot notation access for claims --- src/components/BaseTokenManager.php | 41 +++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src/components/BaseTokenManager.php b/src/components/BaseTokenManager.php index 501f0b3..bb2a3cf 100644 --- a/src/components/BaseTokenManager.php +++ b/src/components/BaseTokenManager.php @@ -46,14 +46,51 @@ public function setToken(UnencryptedToken $token): void */ public function getRoles(): array { - return $this->getClaim($this->rolesClaimName, []); + return (array)$this->getClaim($this->rolesClaimName, []); } /** * @inheritdoc + * + * Name can be represented in dot notation like this claim1.subClaim */ public function getClaim(string $name, $default = null): mixed { - return $this->getToken()->claims()->get($name, $default); + // split name into separate parts + $parts = explode('.', $name); + + // check if there is at least one item + $baseName = $parts[0] ?? null; + if ($baseName === null) { + return $default; + } + + // remove first part because it is saved in $baseName + unset($parts[0]); + + // set this as base value + $baseValue = $this->getToken()->claims()->get($baseName, $default); + + // iterate over the rest of the parts + foreach ($parts as $part) { + // check if key exists and value is array to continue. If not return value + if (!isset($baseValue[$part]) && !is_array($baseValue[$part])) { + return $baseValue; + } + $baseValue = $baseValue[$part]; + } + // return the value + return $baseValue; + } + + /** + * split name to array + * @param string $name + * + * @return array + */ + protected function parseName(string $name): array { + $parts = explode('.', $name); + return $parts; } } \ No newline at end of file