Created
January 30, 2018 14:44
-
-
Save kyrrr/b208693a59f184fe607660e0dfa8631d to your computer and use it in GitHub Desktop.
Order them properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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