Description
Feature Request
Q | A |
---|---|
Flysystem Version | 3.29 |
Adapter Name | LocalFilesystemAdapter |
Adapter version | 3.29 |
Scenario / Use-case
There are plenty of times we want to check if a directory is empty but don't need to know what's actually in it. A common example is before deleting a directory, we may want to throw an exception or ask for confirmation if the directory has some contents.
Currently we have to call listContents()
to check if there are contents, but this fetches the data about all files in the directory, which has performance implications.
Currently we are looking at implementing this in a League\Flysystem\Filesystem
subclass as a workaround:
public function isEmpty(string $location): bool
{
// listContents() uses generators, so we can start the iterator and return false if there's a single item.
// In most cases this will be orders of magnitude faster than checking if $this->listContents($location)->toArray() is empty.
foreach ($this->listContents($location) as $item) {
return false;
}
return true;
}
This works well with league/flysystem-local
- presumably because it only gets data for each file one at a time. But with the s3 adapter for example, I would expect a chunk of data for multiple files to be returned at a time, which means additional time spent collecting the information on the AWS-side, and additional time shipping it over the network.
It's also not part of the official API which means others may not think to implement this (we didn't until we recently discovered checking empty($fs->listContents()->toArray())
was causing performance problems when we have thousands of files in the directory).
Having this method is also useful semantically, as it is clear just from the method name that you only care about if the directory is empty, not what's specifically in it.
Summary
A new method in League\Flysystem\Filesystem
and in the League\Flysystem\FilesystemAdapter
interface to check if the directory is empty or not.
Each adapter should perform only the minimum required processing to check if there is anything in the directory or not.