Skip to content

Commit

Permalink
Backport Session consume()
Browse files Browse the repository at this point in the history
  • Loading branch information
euromark committed Dec 23, 2014
1 parent 839ef73 commit 813925a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
18 changes: 18 additions & 0 deletions lib/Cake/Model/Datasource/CakeSession.php
Expand Up @@ -432,6 +432,24 @@ public static function write($name, $value = null) {
return true;
}

/**
* 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 static function consume($name) {
if (empty($name)) {
return null;
}
$value = self::read($name);
if ($value !== null) {
self::_overwrite($_SESSION, Hash::remove($_SESSION, $name));
}
return $value;
}

/**
* Helper method to destroy invalid sessions.
*
Expand Down
22 changes: 22 additions & 0 deletions lib/Cake/Test/Case/Model/Datasource/CakeSessionTest.php
Expand Up @@ -328,6 +328,28 @@ public function testWriteOverwriteStringValue() {
);
}

/**
* Test consuming session data.
*
* @return void
*/
public function testConsume() {
TestCakeSession::write('Some.string', 'value');
TestCakeSession::write('Some.array', array('key1' => 'value1', 'key2' => 'value2'));
$this->assertEquals('value', TestCakeSession::read('Some.string'));
$value = TestCakeSession::consume('Some.string');
$this->assertEquals('value', $value);
$this->assertFalse(TestCakeSession::check('Some.string'));
$value = TestCakeSession::consume('');
$this->assertNull($value);
$value = TestCakeSession::consume(null);
$this->assertNull($value);
$value = TestCakeSession::consume('Some.array');
$expected = array('key1' => 'value1', 'key2' => 'value2');
$this->assertEquals($expected, $value);
$this->assertFalse(TestCakeSession::check('Some.array'));
}

/**
* testId method
*
Expand Down

0 comments on commit 813925a

Please sign in to comment.