Skip to content

Commit

Permalink
[10.x] Add hasAny function to ComponentAttributeBag, Allow multiple k…
Browse files Browse the repository at this point in the history
…eys in has function (#47569)

* Add hasAny function to ComponentAttributeBag, Allow multiple keys in has function

* Update ComponentAttributeBag.php

* Update ComponentAttributeBag.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
indykoning and taylorotwell authored Jun 26, 2023
1 parent 7a03161 commit 3558da8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
37 changes: 34 additions & 3 deletions src/Illuminate/View/ComponentAttributeBag.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,43 @@ public function get($key, $default = null)
/**
* Determine if a given attribute exists in the attribute array.
*
* @param string $key
* @param array|string $key
* @return bool
*/
public function has($key)
{
return array_key_exists($key, $this->attributes);
$keys = is_array($key) ? $key : func_get_args();

foreach ($keys as $value) {
if (! array_key_exists($value, $this->attributes)) {
return false;
}
}

return true;
}

/**
* Determine if any of the keys exist in the attribute array.
*
* @param array|string $key
* @return bool
*/
public function hasAny($key)
{
if (! count($this->attributes)) {
return false;
}

$keys = is_array($key) ? $key : func_get_args();

foreach ($keys as $value) {
if ($this->has($value)) {
return true;
}
}

return false;
}

/**
Expand All @@ -77,7 +108,7 @@ public function has($key)
*/
public function missing($key)
{
return ! $this->has($key, $this->attributes);
return ! $this->has($key);
}

/**
Expand Down
6 changes: 6 additions & 0 deletions tests/View/ViewComponentAttributeBagTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,14 @@ public function testAttibuteExistence()
$bag = new ComponentAttributeBag(['name' => 'test']);

$this->assertTrue((bool) $bag->has('name'));
$this->assertTrue((bool) $bag->has(['name']));
$this->assertTrue((bool) $bag->hasAny(['class', 'name']));
$this->assertTrue((bool) $bag->hasAny('class', 'name'));
$this->assertFalse((bool) $bag->missing('name'));
$this->assertFalse((bool) $bag->has('class'));
$this->assertFalse((bool) $bag->has(['class']));
$this->assertFalse((bool) $bag->has(['name', 'class']));
$this->assertFalse((bool) $bag->has('name', 'class'));
$this->assertTrue((bool) $bag->missing('class'));
}
}

0 comments on commit 3558da8

Please sign in to comment.