Skip to content

Commit

Permalink
Merge pull request #5449 from cakephp/3.0-session-consume
Browse files Browse the repository at this point in the history
Add consume() to session.
  • Loading branch information
markstory committed Dec 20, 2014
2 parents e413acc + bdb9bb1 commit b9af093
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
20 changes: 19 additions & 1 deletion src/Network/Session.php
Expand Up @@ -361,7 +361,7 @@ public function check($name = null) {
/**
* Returns given session variable, or all of them, if no parameters given.
*
* @param string|array|null $name The name of the session variable (or a path as sent to Set.extract)
* @param string|null $name The name of the session variable (or a path as sent to Hash.extract)
* @return mixed The value of the session variable, null if session not available,
* session not started, or provided name not found in the session.
*/
Expand All @@ -385,6 +385,24 @@ public function read($name = null) {
return Hash::get($_SESSION, $name);
}

/**
* Reads and deletes a variable from session.
*
* @param string $name The key to read and remove (or a path as sent to Hash.extract).
* @return mixed The value of the session variable, null if session not available,
* session not started, or provided name not found in the session.
*/
public function consume($name) {
if (empty($name)) {
return null;
}
$value = $this->read($name);
if ($value !== null) {
$this->_overwrite($_SESSION, Hash::remove($_SESSION, $name));
}
return $value;
}

/**
* Writes value to given session variable name.
*
Expand Down
28 changes: 28 additions & 0 deletions tests/TestCase/Network/SessionTest.php
Expand Up @@ -225,6 +225,34 @@ public function testWriteOverwriteStringValue() {
$this->assertEquals(['values'], $session->read('Some.string.array'));
}

/**
* Test consuming session data.
*
* @return void
*/
public function testConsume() {
$session = new Session();
$session->write('Some.string', 'value');
$session->write('Some.array', ['key1' => 'value1', 'key2' => 'value2']);

$this->assertEquals('value', $session->read('Some.string'));

$value = $session->consume('Some.string');
$this->assertEquals('value', $value);
$this->assertFalse($session->check('Some.string'));

$value = $session->consume('');
$this->assertNull($value);

$value = $session->consume(null);
$this->assertNull($value);

$value = $session->consume('Some.array');
$expected = ['key1' => 'value1', 'key2' => 'value2'];
$this->assertEquals($expected, $value);
$this->assertFalse($session->check('Some.array'));
}

/**
* testId method
*
Expand Down

0 comments on commit b9af093

Please sign in to comment.