diff --git a/src/Filesystem/Folder.php b/src/Filesystem/Folder.php index cdac225453a..c1e0eaf0fc2 100644 --- a/src/Filesystem/Folder.php +++ b/src/Filesystem/Folder.php @@ -165,7 +165,7 @@ public function cd($path) * @param bool $fullPath True returns the full path * @return array Contents of current directory as an array, an empty array on failure */ - public function read($sort = true, $exceptions = false, $fullPath = false) + public function read($sort = 'name', $exceptions = false, $fullPath = false) { $dirs = $files = []; @@ -194,16 +194,32 @@ public function read($sort = true, $exceptions = false, $fullPath = false) if ($fullPath) { $name = $item->getPathname(); } + if ($item->isDir()) { - $dirs[] = $name; + $dirs[$item->getCTime()][] = $name; } else { - $files[] = $name; + $files[$item->getCTime()][] = $name; } } + if ($sort || $this->sort) { - sort($dirs); - sort($files); + if ($sort === 'time') { + ksort($dirs); + ksort($files); + } else { + sort($dirs); + sort($files); + } } + + if (!empty($dirs)) { + $dirs = call_user_func_array('array_merge', $dirs); + } + + if (!empty($files)) { + $files = call_user_func_array('array_merge', $files); + } + return [$dirs, $files]; } diff --git a/tests/TestCase/Filesystem/FolderTest.php b/tests/TestCase/Filesystem/FolderTest.php index a9d7c3cfdcb..27b386695d3 100644 --- a/tests/TestCase/Filesystem/FolderTest.php +++ b/tests/TestCase/Filesystem/FolderTest.php @@ -1247,4 +1247,28 @@ public function testMoveWithoutRecursive() $this->assertFalse(is_dir($folderTwo . '/folderA')); $this->assertFalse(file_exists($folderTwo . '/folderA/fileA.php')); } + + /** + * testSortByTime method + * + * Verify that the order using modified time is correct. + * + * @return void + */ + public function testSortByTime() + { + $Folder = new Folder(TMP . 'tests', true); + + $file2 = new File($Folder->pwd() . DS . 'file_2.tmp'); + $file2->create(); + + sleep(1); + + $file1 = new File($Folder->pwd() . DS . 'file_1.tmp'); + $file1->create(); + + $results = $Folder->find('.*', 'time'); + + $this->assertSame(['file_2.tmp', 'file_1.tmp'], $results); + } }