Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Re-implementing Session::write()
  • Loading branch information
lorenzo committed May 17, 2014
1 parent 826614b commit fd77006
Showing 1 changed file with 30 additions and 26 deletions.
56 changes: 30 additions & 26 deletions src/Network/Session.php
Expand Up @@ -309,6 +309,35 @@ public function read($name = null) {
return Hash::get($_SESSION, $name);
}

/**
* Writes value to given session variable name.
*
* @param string|array $name Name of variable
* @param string $value Value to write
* @return bool True if the write was successful, false if the write failed
*/
public function write($name, $value = null) {
if (empty($name)) {
return;
}

if (!$this->started()) {
$this->start();
}

$write = $name;
if (!is_array($name)) {
$write = array($name => $value);
}

$data = $_SESSION ?: [];
foreach ($write as $key => $val) {
$data = Hash::insert($data, $key, $val);
}

$this->_overwrite($_SESSION, $data);
}

/**
* Returns the session id.
* Calling this method will not auto start the session. You might have to manually
Expand Down Expand Up @@ -355,7 +384,7 @@ public function delete($name) {
* @param array $new New set of variable => value
* @return void
*/
protected static function _overwrite(&$old, $new) {
protected function _overwrite(&$old, $new) {
if (!empty($old)) {
foreach ($old as $key => $var) {
if (!isset($new[$key])) {
Expand All @@ -368,31 +397,6 @@ protected static function _overwrite(&$old, $new) {
}
}

/**
* Writes value to given session variable name.
*
* @param string|array $name Name of variable
* @param string $value Value to write
* @return bool True if the write was successful, false if the write failed
*/
public static function write($name, $value = null) {
if (empty($name) || !static::start()) {
return false;
}

$write = $name;
if (!is_array($name)) {
$write = array($name => $value);
}
foreach ($write as $key => $val) {
static::_overwrite($_SESSION, Hash::insert($_SESSION, $key, $val));
if (Hash::get($_SESSION, $key) !== $val) {
return false;
}
}
return true;
}

/**
* Helper method to destroy invalid sessions.
*
Expand Down

0 comments on commit fd77006

Please sign in to comment.