/** mediawiki-extensions-Arrays-REL1_37 ExtArrays.php
* locate the index of the first occurrence of an element starting from the 'index'
* - print "-1" (not found) or index (found) to show the index of the first occurrence of 'value' in the array identified by arrayid
* - if 'yes' and 'no' are set, print value of them when found or not-found
* - index is 0-based , it must be non-negative and less than lenth
* usage:
* {{#arraysearch:arrayid|value|index|yes|no}}
*
* See: http://www.php.net/manual/en/function.array-search.php
* note it is extended to support regular expression match and index
*/
public static function pfObj_arraysearch( Parser &$parser, PPFrame $frame, $args ) {
// Get Parameters
$arrayId = trim( $frame->expand( $args[0] ) );
$index = isset( $args[2] ) ? trim( $frame->expand( $args[2] ) ) : 0;
$store = self::get( $parser );
if ( $store->arrayExists( $arrayId )
&& $store->validate_array_index( $arrayId, $index, false )
) {
$array = $store->getArray( $arrayId );
// validate/build search regex:
if ( isset( $args[1] ) ) {
$needle = trim( $frame->expand( $args[1] ) );
if ( !self::isValidRegEx( $needle ) ) {
$needle = '/^\s*' . preg_quote( trim( $needle ), '/' ) . '\s*$/';
}
} else {
$needle = '/^\s*$/';
}
// search for a match inside the array:
$total = count( $array );
for ( $i = $index; $i < $total; $i++ ) {
$value = $array[ $i ];
if ( preg_match( $needle, $value ) ) {
// found!
if ( isset( $args[3] ) ) {
// Expand only when needed!
return trim( $frame->expand( $args[3] ) );
} else {
// return index of first found item
return $i;
}
}
}
}
// no match! (Expand only when needed!)
if ( isset( $args[4] ) ) {
$no = trim( $frame->expand( $args[4] ) );
} else {
global $egArraysCompatibilityMode;
$no = $egArraysCompatibilityMode
? '-1' // COMPATIBILITY-MODE
: '';
}
return $no;
}