Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Add session hasAny method #50897

Merged
merged 3 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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