MD_STD/src/MD_STD_SORT.php

79 lines
2.8 KiB
PHP
Raw Normal View History

<?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;
2021-09-26 19:23:42 +02:00
$containsSearchA = stripos($a[$nameIndex], $searchValue);
$containsSearchB = stripos($b[$nameIndex], $searchValue);
if ($containsSearchA !== false and $containsSearchB !== false) {
return $extSortBy[$a[$sortIndex]] > $extSortBy[$b[$sortIndex]] ? -1 : 1;
}
if ($containsSearchA !== false) return -1;
if ($containsSearchB !== false) return 1;
return $extSortBy[$a[$sortIndex]] > $extSortBy[$b[$sortIndex]] ? -1 : 1;
};
}
}