Backport Session consume()

This commit is contained in:
euromark 2014-12-23 03:39:05 +01:00
parent 839ef73d43
commit 813925abee
2 changed files with 40 additions and 0 deletions

View file

@ -432,6 +432,24 @@ class CakeSession {
return true; 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. * Helper method to destroy invalid sessions.
* *

View file

@ -328,6 +328,28 @@ class CakeSessionTest extends CakeTestCase {
); );
} }
/**
* 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 * testId method
* *