Skip to content

Commit

Permalink
added ordering by modified time in Folder Util.
Browse files Browse the repository at this point in the history
Now the results returned by Folder::path can be ordered by file/dir
modification time.
  • Loading branch information
tzaoh committed Apr 30, 2016
1 parent 9a8b0ec commit dbd60fc
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/Filesystem/Folder.php
Expand Up @@ -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 = [];

Expand Down Expand Up @@ -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];
}

Expand Down
24 changes: 24 additions & 0 deletions tests/TestCase/Filesystem/FolderTest.php
Expand Up @@ -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);
}
}

0 comments on commit dbd60fc

Please sign in to comment.