Skip to content

Commit

Permalink
[11.x] Add Session hasAny method (#50897)
Browse files Browse the repository at this point in the history
* Add `hasAny` method

* Add the test method

* Update Store.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
mahmoudmohamedramadan and taylorotwell authored Apr 3, 2024
1 parent 94bfff1 commit 1bf10e6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Illuminate/Session/Store.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ public function missing($key)
}

/**
* Checks if a key is present and not null.
* Determine if a key is present and not null.
*
* @param string|array $key
* @return bool
Expand All @@ -295,6 +295,19 @@ public function has($key)
});
}

/**
* Determine if any of the given keys are present and not null.
*
* @param string|array $key
* @return bool
*/
public function hasAny($key)
{
return collect(is_array($key) ? $key : func_get_args())->filter(function ($key) {
return ! is_null($this->get($key));
})->count() >= 1;
}

/**
* Get an item from the session.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/Session/SessionStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,22 @@ public function testKeyHas()
$this->assertFalse($session->has('foo', 'bar'));
}

public function testKeyHasAny()
{
$session = $this->getSession();
$session->put('first_name', 'Mahmoud');
$session->put('last_name', 'Ramadan');

$this->assertTrue($session->hasAny('first_name'));
$this->assertTrue($session->hasAny('first_name', 'last_name'));
$this->assertTrue($session->hasAny(['first_name', 'last_name']));
$this->assertTrue($session->hasAny(['first_name', 'middle_name']));

$this->assertFalse($session->hasAny('middle_name'));
$this->assertFalse($session->hasAny('foo', 'bar'));
$this->assertFalse($session->hasAny(['foo', 'bar']));
}

public function testKeyExists()
{
$session = $this->getSession();
Expand Down

0 comments on commit 1bf10e6

Please sign in to comment.