diff --git a/src/Csv.php b/src/Csv.php index 70bbbcf..7a8c2f9 100644 --- a/src/Csv.php +++ b/src/Csv.php @@ -739,7 +739,8 @@ class Csv { $this->titles = $head; if (!empty($this->sort_by)) { - $this->sort_reverse ? krsort($rows, $this->sort_type) : ksort($rows, $this->sort_type); + $sort_type = SortEnum::getSorting($this->sort_type); + $this->sort_reverse ? krsort($rows, $sort_type) : ksort($rows, $sort_type); if ($this->offset !== null || $this->limit !== null) { $rows = array_slice($rows, ($this->offset === null ? 0 : $this->offset), $this->limit, true); diff --git a/src/enums/SortEnum.php b/src/enums/SortEnum.php index 42626ef..54c3040 100644 --- a/src/enums/SortEnum.php +++ b/src/enums/SortEnum.php @@ -5,9 +5,24 @@ namespace ParseCsv\enums; class SortEnum extends AbstractEnum { const __DEFAULT = self::SORT_TYPE_REGULAR; - const SORT_TYPE_REGULAR = SORT_REGULAR; + const SORT_TYPE_REGULAR = 'regular'; - const SORT_TYPE_NUMERIC = SORT_NUMERIC; + const SORT_TYPE_NUMERIC = 'numeric'; + + const SORT_TYPE_STRING = 'string'; + + private static $sorting = array( + self::SORT_TYPE_REGULAR => SORT_REGULAR, + self::SORT_TYPE_STRING => SORT_STRING, + self::SORT_TYPE_NUMERIC => SORT_NUMERIC + ); + + public static function getSorting($type){ + if (array_key_exists($type, self::$sorting)){ + return self::$sorting[$type]; + } + + return self::$sorting[self::__DEFAULT]; + } - const SORT_TYPE_STRING = SORT_STRING; } diff --git a/tests/properties/PublicPropertiesTest.php b/tests/properties/PublicPropertiesTest.php index 0510e73..ed49354 100644 --- a/tests/properties/PublicPropertiesTest.php +++ b/tests/properties/PublicPropertiesTest.php @@ -152,14 +152,20 @@ class PublicPropertiesTest extends TestCase { } public function testSetSortType(){ - $this->csv->sort_type = SortEnum::SORT_TYPE_NUMERIC; + $this->csv->sort_type = 'numeric'; $this->assertEquals(SortEnum::SORT_TYPE_NUMERIC, $this->csv->sort_type); - $this->csv->sort_type = SortEnum::SORT_TYPE_STRING; + $this->csv->sort_type = 'string'; $this->assertEquals(SortEnum::SORT_TYPE_STRING, $this->csv->sort_type); + } - $this->csv->sort_type = SortEnum::SORT_TYPE_UNKNOWN; - // todo: how to handle this exception? - $this->expectException(InvalidArgumentException::class); + public function testGetSorting(){ + $this->csv->sort_type = 'numeric'; + $sorting = SortEnum::getSorting($this->csv->sort_type); + $this->assertEquals(SORT_NUMERIC, $sorting); + + $this->csv->sort_type = 'string'; + $sorting = SortEnum::getSorting($this->csv->sort_type); + $this->assertEquals(SORT_STRING, $sorting); } }