Go to the documentation of this file.00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00015 final class SortHelper extends Singleton implements Instantiatable
00016 {
00017 const ASC = 0x1;
00018 const DESC = 0x2;
00019
00020 private $vector = null;
00021 private $keys = null;
00022
00023 private $defaultCmpFunction = 'strnatcmp';
00024
00025 public static function me()
00026 {
00027 return Singleton::getInstance('SortHelper');
00028 }
00029
00030 public function setVector(&$vector)
00031 {
00032 $this->vector = &$vector;
00033
00034 return $this;
00035 }
00036
00037 public function setKeys($keys)
00038 {
00039 $this->keys = $keys;
00040
00041 foreach ($this->keys as &$keyData)
00042 if (!isset($keyData[2]))
00043 $keyData[2] = $this->defaultCmpFunction;
00044
00045 return $this;
00046 }
00047
00048 public function sort()
00049 {
00050 Assert::isGreater(count($this->keys), 0);
00051 Assert::isNotEmptyArray($this->vector);
00052
00053 usort($this->vector, array($this, "compare"));
00054 }
00055
00056 private function compare($one, $two, $keyIndex = 0)
00057 {
00058 Assert::isTrue(
00059 isset($one[$this->keys[$keyIndex][0]])
00060 || array_key_exists($this->keys[$keyIndex][0], $one),
00061 'Key must be exist in vector!'
00062 );
00063
00064 $result =
00065 $this->keys[$keyIndex][2](
00066 $one[$this->keys[$keyIndex][0]],
00067 $two[$this->keys[$keyIndex][0]]
00068 );
00069
00070 if ($this->keys[$keyIndex][1] == self::DESC)
00071 $result *= -1;
00072
00073 if ($result == 0) {
00074 $keyIndex++;
00075
00076 if (isset($this->keys[$keyIndex]))
00077 $result = $this->compare($one, $two, $keyIndex);
00078 }
00079
00080 return $result;
00081 }
00082 }
00083 ?>