From 6a1b643270603ffee073729876e440234e4aa519 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Thu, 9 Aug 2018 05:03:34 +0700 Subject: [PATCH] implements session->push() --- system/Session/Session.php | 18 ++++++++++++++++++ tests/system/Session/SessionTest.php | 17 +++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/system/Session/Session.php b/system/Session/Session.php index e266dea35482..7086baaad580 100644 --- a/system/Session/Session.php +++ b/system/Session/Session.php @@ -516,6 +516,24 @@ public function has(string $key) return isset($_SESSION[$key]); } + //-------------------------------------------------------------------- + + /** + * Push new value onto session value that is array. + * + * @param string $key Identifier of the session property we are interested in. + * @param array $data value to be pushed to existing session key. + * + * @return void + */ + public function push(string $key, array $data) + { + if ($this->has($key) && is_array($value = $this->get($key))) + { + $this->set($key, array_merge($value, $data)); + } + } + //-------------------------------------------------------------------- /** diff --git a/tests/system/Session/SessionTest.php b/tests/system/Session/SessionTest.php index bba8db126928..4a5cfc441038 100644 --- a/tests/system/Session/SessionTest.php +++ b/tests/system/Session/SessionTest.php @@ -170,6 +170,23 @@ public function testHasReturnsFalseOnNotFound() $this->assertFalse($session->has('bar')); } + public function testPushNewValueIntoArraySessionValue() + { + $session = $this->getInstance(); + $session->start(); + + $session->set('hobbies', ['cooking' => 'baking']); + $session->push('hobbies', ['sport'=>'tennis']); + + $this->assertEquals( + [ + 'cooking' => 'baking', + 'sport' => 'tennis', + ], + $session->get('hobbies') + ); + } + public function testRemoveActuallyRemoves() { $session = $this->getInstance();