Files
myep/src/BusProNet/Traits/SortByPriceTrait.php
T

47 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\BusProNet\Traits;
/**
* Provides generic price-based sorting functionality for services and insurances.
*
* This trait implements consistent ascending price sorting across the application
* for any objects that have a price property. Null prices are treated as zero,
* ensuring items without pricing information appear first in sorted results.
*
* Usage:
* - Services (skipasses, courses, rentals, board options, etc.)
* - Insurances (individual and package insurances)
*
* Excluded from price sorting:
* - Transportation services (sorted by subType)
* - Pickup locations (no specific sorting)
*/
trait SortByPriceTrait
{
/**
* Sorts an array of objects by their price property in ascending order.
*
* This method provides a consistent sorting strategy across all price-based
* collections in the application. Items are sorted from lowest to highest price,
* with null prices being treated as zero (appearing first).
*
* @param array $items Array of objects with a price property to sort
*
* @return array The sorted array of objects (ascending by price)
*/
protected function sortByPrice(array $items): array
{
usort($items, function (object $a, object $b) {
$priceA = $a->price ?? 0;
$priceB = $b->price ?? 0;
return $priceA <=> $priceB;
});
return $items;
}
}