Add new class MD_STD_SORT to provide useful sorting tools

This commit is contained in:
Joshua Ramon Enslin 2021-09-26 01:02:18 +02:00
parent 143a4680e2
commit 9113cad57e
Signed by: jrenslin
GPG Key ID: 46016F84501B70AE

72
src/MD_STD_SORT.php Normal file
View File

@ -0,0 +1,72 @@
<?PHP
/**
* Provides basic helper functions for sorting.
*/
declare(strict_types = 1);
/**
* Standard class providing basic helper functions for sorting.
*/
final class MD_STD_SORT {
/**
* Provides a function usable by usort that sorts first by string occurence,
* then by a similarity as provided by an outside array.
*
* @param string $nameIndex Index of the name column.
* @param string $searchValue Value to search for.
* @param string $sortIndex Index to sort by in case the name index didn't return a hit.
*
* @return closure
*/
public static function sort_by_string_occurence_and_int(string $nameIndex, string $searchValue, string $sortIndex):closure {
return function (array $a, array $b) use ($nameIndex, $searchValue, $sortIndex) {
if ($a == $b) {
return 0;
}
if ($a[$nameIndex] === $searchValue) return -1;
if ($b[$nameIndex] === $searchValue) return 1;
if (stripos($a[$nameIndex], $searchValue) !== false) return -1;
if (stripos($b[$nameIndex], $searchValue) !== false) return 1;
return $a[$sortIndex] > $b[$sortIndex] ? -1 : 1;
};
}
/**
* Provides a function usable by usort that sorts first by string occurence,
* then by an integer value provided in another part of the array.
*
* @param string $nameIndex Index of the name column.
* @param string $searchValue Value to search for.
* @param array<integer|float> $extSortBy External list to sort by, e.g.
* similarities as per levinsthein.
* @param string $sortIndex Index to sort by in case the name
* index didn't return a hit.
*
*
* @return closure
*/
public static function sort_by_string_occurence_and_ext_sort_index(string $nameIndex, string $searchValue, array $extSortBy, string $sortIndex):closure {
return function (array $a, array $b) use ($nameIndex, $searchValue, $extSortBy, $sortIndex) {
if ($a == $b) {
return 0;
}
if ($a[$nameIndex] === $searchValue) return -1;
if ($b[$nameIndex] === $searchValue) return 1;
if (stripos($a[$nameIndex], $searchValue) !== false) return -1;
if (stripos($b[$nameIndex], $searchValue) !== false) return 1;
return $extSortBy[$a[$sortIndex]] > $extSortBy[$b[$sortIndex]] ? -1 : 1;
};
}
}