Skip to content

Commit cd7d066

Browse files
committed
Add "in" and "orIn" filters to XPath builder
1 parent 2e5539c commit cd7d066

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

src/XPath/Builder.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,35 @@ public function get()
165165
return $this->find();
166166
}
167167

168+
/**
169+
* Add an "in" filter.
170+
*
171+
* @param string $xpath
172+
* @param array $values
173+
* @param string $boolean
174+
* @return self
175+
*/
176+
public function in($xpath, array $values, $boolean = 'and')
177+
{
178+
return $this->filter(function ($builder) use ($xpath, $values) {
179+
foreach ($values as $value) {
180+
$builder->filter($xpath, '=', $value, 'or');
181+
}
182+
}, null, null, $boolean);
183+
}
184+
185+
/**
186+
* Add an "or in" filter.
187+
*
188+
* @param string $xpath
189+
* @param array $values
190+
* @return self
191+
*/
192+
public function orIn($xpath, array $values)
193+
{
194+
return $this->in($xpath, $values, 'or');
195+
}
196+
168197
/**
169198
* Add a nested filter using a callback.
170199
*

tests/XPath/BuilderTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,20 @@ public function testOrContains()
7575
$this->assertEquals((new Builder)->filter('@id', 99)->orContains('@name', 'Smith')->toXPath(), '@id = 99 or contains(@name, "Smith")');
7676
}
7777

78+
public function testInFilter()
79+
{
80+
$builder = new Builder;
81+
$builder->in('@id', [1, 2, 5, 10]);
82+
$this->assertEquals($builder->toXPath(), '(@id = 1 or @id = 2 or @id = 5 or @id = 10)');
83+
}
84+
85+
public function testOrInFilter()
86+
{
87+
$builder = new Builder;
88+
$builder->filter('@id', '<', 5)->in('@id', [1, 2, 5, 10]);
89+
$this->assertEquals($builder->toXPath(), '@id < 5 and (@id = 1 or @id = 2 or @id = 5 or @id = 10)');
90+
}
91+
7892
public function testSorting()
7993
{
8094
$builder = new Builder;

0 commit comments

Comments
 (0)