Brought Sort back into the repo

Decided that having a bunch of external dependencies would end up being more
trouble than it's worth
This commit is contained in:
Josh Sherman 2014-10-06 18:27:53 -04:00
parent 6c148c124e
commit c5d39db63b
2 changed files with 131 additions and 0 deletions

70
src/Sort.php Normal file
View file

@ -0,0 +1,70 @@
<?php
/**
* Sorting Utility Collection
*
* Licensed under The MIT License
* Redistribution of these files must retain the above copyright notice.
*
* @copyright Copyright 2007-2014, Josh Sherman
* @license http://www.opensource.org/licenses/mit-license.html
* @link http://picklesphp.com
* @package Pickles
*/
namespace Pickles;
/**
* Sort Class
*
* I got tired of writing separate usort functions to sort by different array
* keys in the array, this class solves that.
*/
class Sort
{
/**
* Ascending
*
* Variable to utilize ascending sort
*
* @var integer
*/
const ASC = 'ASC';
/**
* Descending
*
* Variable to utilize descending sort
*
* @var integer
*/
const DESC = 'DESC';
/**
* Sort By
*
* Sorts an array by the specified column, optionally in either direction.
*
* @param string $field field to sort by
* @param array $array array to sort
* @param string $direction optional direction to sort
* @retun boolean true because sorting is done by reference
*/
public static function by($field, &$array, $direction = Sort::ASC)
{
usort($array, create_function('$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b)
{
return 0;
}
return ($a ' . ($direction == Sort::DESC ? '>' : '<') .' $b) ? -1 : 1;
'));
return true;
}
}

View file

@ -0,0 +1,61 @@
<?php
class SortTest extends PHPUnit_Framework_TestCase
{
public function testByNameASC()
{
$shuffled = [
['name' => 'epsilon'],
['name' => 'gamma'],
['name' => 'alpha'],
['name' => 'delta'],
['name' => 'beta'],
];
$sorted = [
['name' => 'alpha'],
['name' => 'beta'],
['name' => 'delta'],
['name' => 'epsilon'],
['name' => 'gamma'],
];
Pickles\Sort::by('name', $shuffled);
$this->assertEquals($sorted, $shuffled);
}
public function testByNameDESC()
{
$shuffled = [
['name' => 'epsilon'],
['name' => 'gamma'],
['name' => 'alpha'],
['name' => 'delta'],
['name' => 'beta'],
];
$sorted = [
['name' => 'gamma'],
['name' => 'epsilon'],
['name' => 'delta'],
['name' => 'beta'],
['name' => 'alpha'],
];
Pickles\Sort::by('name', $shuffled, Pickles\Sort::DESC);
$this->assertEquals($sorted, $shuffled);
}
public function testMissingField()
{
$shuffled = [['foo' => 'bar', 'bar' => 'foo']];
$sorted = [['foo' => 'bar', 'bar' => 'foo']];
Pickles\Sort::by('name', $shuffled);
$this->assertEquals($sorted, $shuffled);
}
}