I've reviewed a number of ways to determine that a directory is empty or not, and many indicate that $isDirEmpty = !(new \FilesystemIterator($dir))->valid();
is a good choice, except that the directory path in the $dir parameter must exist or else an UnexpectedValueException
is thrown. Please see How can I use PHP to check if a directory is empty? for more details about using this method.
However, this and other examples first need to use other functions/statements to determine if the directory exists before using FileSystemIterator to retrieve the iterator and test its item, but these often cache information about the directory and that needs to be explicitly released after they are used, which many of these examples do not do.
To get around these extra 'details' and aid in my debugging, I've decided to implement the FileSystemIterator technique in a function that uses a try/catch block and instead of the valid method
that returns true if the file system item is valid (whatever that means) or false, I'm using the getPathname
method so I can see the actual directory/file's path name when I debug the code.
Here is my function, but I need the catch() parameter to finish it:
function isDirectoryEmpty( $dir ) {
//
// Create a file system iterator from the directory path and get the first
// directory content item, if one exists, Note, FilesystemIterator ignores
// the special . and .. entries in a directory that always exist, so I don't
// need to filter them out with code.
try {
$iterator = new \FilesystemIterator( $dir );
foreach( $iterator as $fileinfo ) {
$filePathName = $fileinfo->getPathname();
break;
}
}
catch( WHAT_GOES_HERE ) {
$filePathName = '';
}
return ( $filePathName === '' );
}
Since I only need one existing directory member to prove is the directory isn't empty, I break out of the foreach
block that fetches the file information from the iterator, but it would be cleaner if I knew how to do this without the foreach
loop statement. Would someone also give me the code that does this.
UPDATE
The foreach loop can be replaced as follows:
$filePathName = ''; // Assume that the $dir directory is empty, even if it
// doesn't exist and the FilesystemIterator creation
// method throws an exception.
try {
$filePathName = ( new \FilesystemIterator( $dir ) )->getPathname();
}
catch( UnexpectedValueException $exception ) {} // Other than catching the
// exception, no other action
// is needed.
Thanks.