Skip to content

Commit f160d71

Browse files
committed
Optimize single element find
1 parent 19e5890 commit f160d71

File tree

1 file changed

+33
-14
lines changed

1 file changed

+33
-14
lines changed

src/Element/Element.php

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -139,24 +139,17 @@ public function waitFor($timeout, $callback)
139139
}
140140

141141
/**
142-
* {@inheritdoc}
143-
*/
144-
public function find($selector, $locator)
145-
{
146-
$items = $this->findAll($selector, $locator);
147-
148-
return count($items) ? current($items) : null;
149-
}
150-
151-
/**
152-
* {@inheritdoc}
142+
* @param string $selector selector engine name
143+
* @param string|array $locator selector locator
144+
*
145+
* @return NodeElement[]
153146
*/
154-
public function findAll($selector, $locator)
147+
private function findAllWithLimit($selector, $locator, ?int $limit): array
155148
{
156149
if ('named' === $selector) {
157-
$items = $this->findAll('named_exact', $locator);
150+
$items = $this->findAllWithLimit('named_exact', $locator);
158151
if (empty($items)) {
159-
$items = $this->findAll('named_partial', $locator);
152+
$items = $this->findAllWithLimit('named_partial', $locator);
160153
}
161154

162155
return $items;
@@ -165,9 +158,35 @@ public function findAll($selector, $locator)
165158
$xpath = $this->selectorsHandler->selectorToXpath($selector, $locator);
166159
$xpath = $this->xpathManipulator->prepend($xpath, $this->getXpath());
167160

161+
if ($limit !== null) {
162+
if ($limit === 1) {
163+
$xpath = '(' . $xpath . ')[1]';
164+
} else {
165+
$xpath = '(' . $xpath . ')[position() <= ' . $limit . ']';
166+
}
167+
}
168+
168169
return $this->getDriver()->find($xpath);
169170
}
170171

172+
/**
173+
* {@inheritdoc}
174+
*/
175+
public function find($selector, $locator)
176+
{
177+
$items = $this->findAllWithLimit($selector, $locator, 1);
178+
179+
return count($items) > 0 ? current($items) : null;
180+
}
181+
182+
/**
183+
* {@inheritdoc}
184+
*/
185+
public function findAll($selector, $locator)
186+
{
187+
return $this->findAllWithLimit($selector, $locator, null);
188+
}
189+
171190
/**
172191
* {@inheritdoc}
173192
*/

0 commit comments

Comments
 (0)