Skip to content

Commit 3558da8

Browse files
[10.x] Add hasAny function to ComponentAttributeBag, Allow multiple keys 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 <[email protected]>
1 parent 7a03161 commit 3558da8

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/Illuminate/View/ComponentAttributeBag.php

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,43 @@ public function get($key, $default = null)
6161
/**
6262
* Determine if a given attribute exists in the attribute array.
6363
*
64-
* @param string $key
64+
* @param array|string $key
6565
* @return bool
6666
*/
6767
public function has($key)
6868
{
69-
return array_key_exists($key, $this->attributes);
69+
$keys = is_array($key) ? $key : func_get_args();
70+
71+
foreach ($keys as $value) {
72+
if (! array_key_exists($value, $this->attributes)) {
73+
return false;
74+
}
75+
}
76+
77+
return true;
78+
}
79+
80+
/**
81+
* Determine if any of the keys exist in the attribute array.
82+
*
83+
* @param array|string $key
84+
* @return bool
85+
*/
86+
public function hasAny($key)
87+
{
88+
if (! count($this->attributes)) {
89+
return false;
90+
}
91+
92+
$keys = is_array($key) ? $key : func_get_args();
93+
94+
foreach ($keys as $value) {
95+
if ($this->has($value)) {
96+
return true;
97+
}
98+
}
99+
100+
return false;
70101
}
71102

72103
/**
@@ -77,7 +108,7 @@ public function has($key)
77108
*/
78109
public function missing($key)
79110
{
80-
return ! $this->has($key, $this->attributes);
111+
return ! $this->has($key);
81112
}
82113

83114
/**

tests/View/ViewComponentAttributeBagTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,14 @@ public function testAttibuteExistence()
118118
$bag = new ComponentAttributeBag(['name' => 'test']);
119119

120120
$this->assertTrue((bool) $bag->has('name'));
121+
$this->assertTrue((bool) $bag->has(['name']));
122+
$this->assertTrue((bool) $bag->hasAny(['class', 'name']));
123+
$this->assertTrue((bool) $bag->hasAny('class', 'name'));
121124
$this->assertFalse((bool) $bag->missing('name'));
122125
$this->assertFalse((bool) $bag->has('class'));
126+
$this->assertFalse((bool) $bag->has(['class']));
127+
$this->assertFalse((bool) $bag->has(['name', 'class']));
128+
$this->assertFalse((bool) $bag->has('name', 'class'));
123129
$this->assertTrue((bool) $bag->missing('class'));
124130
}
125131
}

0 commit comments

Comments
 (0)