1
0
mirror of https://github.com/processwire/processwire.git synced 2025-08-11 17:24:46 +02:00

Optimizations to WireArray::get(), plus add support for get('a|b|c') where it returns value for first matching key, consistently with WireData. This also provides a solution for PR #109 @bernhardbaumrock

This commit is contained in:
Ryan Cramer
2021-05-19 08:57:13 -04:00
parent 335ad1cefe
commit ff0a66821d

View File

@@ -539,6 +539,7 @@ class WireArray extends Wire implements \IteratorAggregate, \ArrayAccess, \Count
*
*/
public function get($key) {
$match = null;
// if an object was provided, get its key
if(is_object($key)) {
@@ -568,6 +569,9 @@ class WireArray extends Wire implements \IteratorAggregate, \ArrayAccess, \Count
// check if the index is set and return it if so
if(isset($this->data[$key])) return $this->data[$key];
// check if key contains something other than numbers, letters, underscores, hyphens
if(!ctype_alnum("$key") && !ctype_alnum(strtr("$key", '-_', 'ab'))) {
// check if key contains a selector
if(Selectors::stringHasSelector($key)) {
$item = $this->findOne($key);
@@ -585,9 +589,23 @@ class WireArray extends Wire implements \IteratorAggregate, \ArrayAccess, \Count
return $this->explode(substr($key, 0, -2));
}
// check if key is asking for first match in "a|b|c"
if(strpos($key, '|') !== false) {
$numericKeys = $this->usesNumericKeys();
foreach(explode('|', $key) as $k) {
if(isset($this->data[$k])) {
$match = $this->data[$k];
} else if($numericKeys) {
$match = $this->getItemThatMatches('name', $k);
}
if($match) break;
}
return $match;
}
}
// if the WireArray uses numeric keys, then it's okay to
// match a 'name' field if the provided key is a string
$match = null;
if(is_string($key) && $this->usesNumericKeys()) {
$match = $this->getItemThatMatches('name', $key);
}