Skip to content

Commit

Permalink
PSession :: dot notation support
Browse files Browse the repository at this point in the history
  • Loading branch information
atakde committed Nov 6, 2022
1 parent 799ca10 commit fb20539
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/PSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,20 @@ public function __set(string $key, $value): void
*/
public function get(string $key, $defaultValue = null)
{
return $_SESSION[$key] ?? $defaultValue;
$keys = explode('.', $key);
$session = $_SESSION;
foreach ($keys as $key) {
// allow both object and array access
if (is_array($session) && isset($session[$key])) {
$session = $session[$key];
} elseif (is_object($session) && isset($session->$key)) {
$session = $session->$key;
} else {
return $defaultValue;
}
}

return $session ?? $defaultValue;
}

/**
Expand All @@ -201,7 +214,24 @@ public function get(string $key, $defaultValue = null)
*/
public function set(string $key, $value = null): void
{
$_SESSION[$key] = $value;
// both object and array access
$keys = explode('.', $key);
$session = &$_SESSION;
foreach ($keys as $key) {
if (is_array($session) && !isset($session[$key])) {
$session[$key] = [];
} elseif (is_object($session) && !isset($session->$key)) {
$session->$key = [];
}

if (is_array($session)) {
$session = &$session[$key];
} elseif (is_object($session)) {
$session = &$session->$key;
}
}

$session = $value;
}

/**
Expand Down

0 comments on commit fb20539

Please sign in to comment.