Skip to content

Commit

Permalink
SessionSection: added methods set(), get(), remove()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Sep 5, 2021
1 parent 7af759a commit c4e55fd
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 13 deletions.
51 changes: 40 additions & 11 deletions src/Http/SessionSection.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,46 @@ public function getIterator(): \Iterator
}


/**
* Sets a variable in this session section.
* @param ?string $time
*/
public function set(string $name, $value, $expiration = null): void
{
$this->start();
$this->data[$name] = $value;
$this->setExpiration($expiration, $name);
}


/**
* Gets a variable from this session section.
* @return mixed
*/
public function get(string $name)
{
$this->start();
return $this->data[$name];
}


/**
* Removes a variable or whole section.
* @param string|array|null $name
*/
public function remove($name = null): void
{
$this->start();
if ($name === null) {
$this->data = $this->meta = null;
} else {
foreach ((array) $name as $name) {
unset($this->data[$name], $this->meta[$name]);
}
}
}


/**
* Sets a variable in this session section.
*/
Expand Down Expand Up @@ -187,15 +227,4 @@ public function removeExpiration($variables = null): void
unset($this->meta[$variable]['T']);
}
}


/**
* Cancels the current session section.
*/
public function remove(): void
{
$this->start();
$this->data = null;
$this->meta = null;
}
}
10 changes: 8 additions & 2 deletions tests/Http/SessionSection.basic.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@ $session = new Session(new Nette\Http\Request(new Nette\Http\UrlScript), new Net

$namespace = $session->getSection('one');
$namespace->a = 'apple';
$namespace->p = 'pear';
$namespace->set('p', 'pear');
$namespace['o'] = 'orange';

Assert::same('apple', $namespace->a);
Assert::same('pear', $namespace->get('p'));
Assert::same('orange', $namespace['o']);

foreach ($namespace as $key => $val) {
$tmp[] = "$key=$val";
}
Expand All @@ -34,7 +38,9 @@ Assert::true(isset($namespace['p']));
Assert::true(isset($namespace->o));
Assert::false(isset($namespace->undefined));

unset($namespace['a'], $namespace->p, $namespace->o, $namespace->undef);
unset($namespace['a'], $namespace->o, $namespace->undef);
$namespace->remove('p');
$namespace->remove(['x']);



Expand Down
1 change: 1 addition & 0 deletions tests/Http/SessionSection.setExpiration().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ test('try to expire only 1 of the keys', function () use ($session) {
$namespace->setExpiration(1, 'g');
$namespace->g = 'guava';
$namespace->p = 'plum';
$namespace->set('a', 'apple', '1 second');

$session->close();
sleep(2);
Expand Down

0 comments on commit c4e55fd

Please sign in to comment.