| 1 |
|
<?php |
| 2 |
|
/** |
| 3 |
|
* Xyster Framework |
| 4 |
|
* |
| 5 |
|
* This source file is subject to the new BSD license that is bundled |
| 6 |
|
* with this package in the file LICENSE.txt. |
| 7 |
|
* It is also available through the world-wide-web at this URL: |
| 8 |
|
* http://www.opensource.org/licenses/bsd-license.php |
| 9 |
|
* |
| 10 |
|
* @category Xyster |
| 11 |
|
* @package Xyster_Data |
| 12 |
|
* @copyright Copyright LibreWorks, LLC (http://libreworks.net) |
| 13 |
|
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License |
| 14 |
|
* @version $Id$ |
| 15 |
|
*/ |
| 16 |
|
namespace Xyster\Data; |
| 17 |
|
/** |
| 18 |
|
* Comparator for objects or associative arrays |
| 19 |
|
* |
| 20 |
|
* @category Xyster |
| 21 |
|
* @package Xyster_Data |
| 22 |
|
* @copyright Copyright LibreWorks, LLC (http://libreworks.net) |
| 23 |
|
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License |
| 24 |
|
*/ |
| 25 |
|
class Comparator implements \Xyster\Collection\IComparator |
| 26 |
|
{ |
| 27 |
|
/** |
| 28 |
|
* The clause of {@link Symbol\Sort} objects |
| 29 |
|
* |
| 30 |
|
* @var Symbol\SortClause |
| 31 |
|
*/ |
| 32 |
|
protected $_sorts; |
| 33 |
|
|
| 34 |
|
/** |
| 35 |
|
* Create a new Data Comparator object |
| 36 |
|
* |
| 37 |
|
* If you pass a clause containing no objects, this comparator will always |
| 38 |
|
* return zero when comparing objects. |
| 39 |
|
* |
| 40 |
|
* @param Symbol\SortClause $sorts A clause of sort objects |
| 41 |
|
*/ |
| 42 |
|
public function __construct(Symbol\SortClause $sorts) |
| 43 |
|
{ |
| 44 |
4 |
$this->_sorts = $sorts; |
| 45 |
|
} |
| 46 |
|
|
| 47 |
|
/** |
| 48 |
|
* Compares two arguments for sorting |
| 49 |
|
* |
| 50 |
|
* Returns a negative integer, zero, or a positive integer as the first |
| 51 |
|
* argument is less than, equal to, or greater than the second. |
| 52 |
|
* |
| 53 |
|
* @param mixed $a |
| 54 |
|
* @param mixed $b |
| 55 |
|
*/ |
| 56 |
|
public function compare($a, $b) |
| 57 |
|
{ |
| 58 |
4 |
foreach ($this->_sorts as $sort) { |
| 59 |
4 |
$getter = new Symbol\Evaluator($sort->getField()); |
| 60 |
4 |
$av = $getter->evaluate($a); |
| 61 |
4 |
$bv = $getter->evaluate($b); |
| 62 |
4 |
if ($av < $bv) { |
| 63 |
4 |
return ( $sort->isAscending() ) ? -1 : 1; |
| 64 |
4 |
} else if ($av > $bv) { |
| 65 |
4 |
return ( $sort->isAscending() ) ? 1 : -1; |
| 66 |
|
} |
| 67 |
2 |
} |
| 68 |
2 |
return 0; |
| 69 |
|
} |
| 70 |
1 |
} |