Skip to content

Instantly share code, notes, and snippets.

@kyrrr
Created January 30, 2018 14:44
Show Gist options
  • Save kyrrr/b208693a59f184fe607660e0dfa8631d to your computer and use it in GitHub Desktop.
Save kyrrr/b208693a59f184fe607660e0dfa8631d to your computer and use it in GitHub Desktop.
Order them properties
<?php
/**
* Pass an array containing objects which share a ->property
* choose asc or desc
* you can cast a string property sort to sort by the int value of the string, for some reason
*
* note: this class has cancer
*/
namespace App\Component\Sorting;
class PropertyOrderHelper
{
function __construct()
{
}
public function orderBy($array, $property, string $dir="asc", string $castAs=null)
{
$dirs = ["asc", "desc"];
$casts = ['int',];
if(!isset($array[0]) || !$array){
//throw new \Exception("No entries!");
}
if(!in_array(strtolower($dir), $dirs)){
throw new \Exception("Unknown order dir!");
}
if($castAs && !in_array(strtolower($castAs), $casts)){
throw new \Exception("Unknown cast $castAs! Allowed value(s): 'int'");
}
$type = gettype($array[0]->{$property});
switch ($type){
case 'integer':
case 'int':
case 'double':
case 'float':
$this->intSort($array, $property, $dir);
break;
case 'string':
if($castAs=="int"){
$this->intSort($array, $property, $dir, true);
} else {
$this->stringSort($array, $property, $dir);
}
break;
default:
break;
}
return $array;
}
protected function intSort(&$array, $property, $dir, $cast=false){
if($dir == "desc"){
usort($array, function ($a, $b) use ($property, $cast){
if($cast){
return intval($a->{$property}) < intval($b->{$property});
} else {
return $a->{$property} < $b->{$property};
}
});
} else {
usort($array, function ($a, $b) use ($property, $cast){
if($cast){
return intval($a->{$property}) > intval($b->{$property});
} else {
return $a->{$property} > $b->{$property};
}
});
}
}
protected function stringSort(&$array, $property, $dir){
if($dir == "desc"){
usort($array, function ($a, $b) use ($property){
return strcmp($b->{$property}, $a->{$property});
});
} else {
usort($array, function ($a, $b) use ($property){
return strcmp($a->{$property}, $b->{$property});
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment