Remove a directory, but only if it is empty.

@param string $folder Absolute folder path
@param boolean $recursive Remove contained empty folders before attempting to remove this one
@return boolean True on success, false on failure.
8267
public static function remove_folder_if_empty($folder, $recursive = true)
    {
        if (!is_readable($folder)) {
            return false;
        }
        $handle = opendir($folder);
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                // if an empty folder is detected, remove that one first and move on
                if ($recursive && is_dir($entry) && self::remove_folder_if_empty($entry)) {
                    continue;
                }
                // if a file was encountered, or a subdirectory was not empty, return false.
                return false;
            }
        }
        // if we are still here, the folder is empty.
        rmdir($folder);
        return true;
    }
347088
protected function removeChildDirecotries(string $dir = null)
    {
        if (empty($dir)) {
            $dir = $this->cacheDir;
        }

        $success = true;
        $objects = new GlobIterator($dir);

        foreach ($objects as $object) {
            if (!is_dir("$dir/$object") && is_link("$dir/$object")) {
                $success = $this->recursiveRemove("$dir/$object") && rmdir($dir) && $success;
            }
        }

        return $success;
    }
1200855
final public function deleteContents($folderpath, $filterByExtension = [], $filterByName = [],
                                         $filterExcludeMode = true, $recursive = true)
    {

        //1. Search $name as a folder or as a file
        if (!$this->is($folderpath)) { //if in path is a directory
            return false;
        }

        $dirh = @opendir($folderpath); //directory handler

        if ($dirh) {
            while (false !== ($file = readdir($dirh))) {
                // remove '.' and '..'
                if ($filterExcludeMode) {
                    //Excluding by name as in "file.ext"
                    if ($file == '.' || $file == '..' || in_array($file, $filterByName)) {
                        continue;
                    }
                    //Excluding extension
                    if (!empty($filterByExtension)) {
                        $fhandler = $this->getFile();
                        $extension = $fhandler->getExtension($file);
                        if (in_array($extension, $filterByExtension)) {
                            continue;
                        }
                    }
                }

                //The new path
                $newPath = $folderpath . DS . $file;
                //echo $newPath;

                //If newpath is a folder and we are deleting recursively
                if ($this->isFolder($newPath) && $recursive) {
                    $this->deleteContents($newPath, $filterByExtension, $filterByName, $filterExcludeMode, $recursive);
                }
                //Now unlink the file
                if (!static::delete($newPath)) {
                    static::setError("Could not delete {$newPath}");

                    return false;
                }
            }
            closedir($dirh);
        }

        //@TODO if long, get additional info for each path;

        return true;
    }
182223
public function emptyDir($remove = false, $path = null)
    {
        if (null === $path) {
            $path = $this->path;
        }
        // Get a directory handle.
        if (!$dh = @opendir($path)) {
            return;
        }

        // Recursively dig through the directory, deleting files where applicable.
        while (false !== ($obj = readdir($dh))) {
            if ($obj == '.' || $obj == '..') {
                continue;
            }
            if (!@unlink($path . DIRECTORY_SEPARATOR . $obj)) {
                $this->emptyDir(true, $path . DIRECTORY_SEPARATOR . $obj);
            }
        }

        // Close the directory handle.
        closedir($dh);

        // If the delete flag was passed, remove the top level directory.
        if ($remove) {
            @rmdir($path);
        }
    }
681704
public function addLocalDirectory($directory, $recursive = false)
    {
        if (!file_exists($directory) || !is_dir($directory)) {
            throw new Exception\InvalidArgumentException(sprintf(
                'The directory "%s" does not exists.',
                $directory
            ));
        }

        if ($recursive) {
            $iterator = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($directory)
            );
        } else {
            $iterator = new \DirectoryIterator($directory);
        }

        foreach ($iterator as $fileinfo) {
            if (!$fileinfo->isFile()) {
                continue;
            }
            
            $extension = $fileinfo->getExtension();
            if ($extension != 'js') {
                continue;
            }

            $this->addLocalFile($fileinfo->getPathname());
        }

        return $this;
    }
822278
public function createFolder(String $path, Int $mode = 0777, Bool $recursive = true) : Bool
    {
        if( @ssh2_sftp_mkdir($this->connect, $path, $mode, $recursive) )
        {
            return true;
        }
        else
        {
            throw new FolderAllreadyException(NULL, $path);
        }
    }
504635
public function createDirectory(string $path, int $mode = 0777, bool $recursive = false): bool
	{
		return mkdir($path, $mode, $recursive);
	}
206634
public function deleteFolder($folder)
    {
        if (!$this->isDir($folder)) {
            $path = $this->pathRoot.$folder;
            throw new ExceptionStorage("Directory {$path} Not found or Not Is Diretory", static::E_NOT_IS_DIR);
        }

        $metadata = $this->dropbox->delete($this->pathRoot.$folder);
        return !is_null($metadata);
    }
1295904
protected function doListContents($directory, $recursive)
	{
		$filter = function ($path) use ($directory, $recursive) {
			// Remove the root directory from any listing.
			if ($path === '') {
				return false;
			}

			if (Util::dirname($path) === $directory) {
				return true;
			}

			return $recursive && $this->pathIsInDirectory($path, $directory);
		};

		return \array_filter(\array_keys($this->storage), $filter);
	}
327749
public static function dirs($path, $recursive = false, $toArray = false, $pathType = self::PATH_ABSOLUTE)
	{
		/**
		 * Files callback
		 *
		 * @param \SplFileInfo                $current  Current item's value
		 * @param string                      $key      Current item's key
		 * @param \RecursiveDirectoryIterator $iterator Iterator being filtered
		 *
		 * @return boolean   TRUE to accept the current item, FALSE otherwise
		 */
		$callback = function ($current, $key, $iterator) use ($path, $recursive)
		{
			if ($recursive)
			{
				// Ignore self
				if ($iterator->getRealPath() == static::cleanPath($path))
				{
					return false;
				}

				// If set to recursive, every returned folder name will include a dot (.),
				// so we can't using isDot() to detect folder.
				return $iterator->isDir() && ($iterator->getBasename() != '..');
			}
			else
			{
				return $iterator->isDir() && !$iterator->isDot();
			}
		};

		$files = static::findByCallback($path, $callback, $recursive);
		
		if ($toArray) {
		    $files = static::toArray($files, $pathType);
		}
	    
	    return $files;
	}
1341601
public function delete($recursive = true) {
		$success = 0;
		$count = $this->getCount();
		$comments = $this->getAll()->setIncrementOffset(false);
		foreach ($comments as $comment) {
			if ($comment->delete($recursive)) {
				$success++;
			}
		}
		return ($success == $count);
	}
970583
public function remove($path, $recursive, $force)
    {
        $this->clearAll();

        $path = trim($path);
        if (!$this->validatePath($path)) {
            throw new \InvalidArgumentException('Invalid path');
        }

        $this->addCommandName(self::GIT_REMOVE);

        if ($recursive) {
            $this->addCommandArgument('-r');
        }

        if ($force) {
            $this->addCommandArgument('-f');
        }

        $this->addPath($path);

        return $this->getCommand();
    }
1038826
public function delete(bool $recursive = true): bool
    {
        if (is_writeable($this->path)) {
            if ($recursive) {
                $files = $this->findFiles('{,.}{,..}[!.,!..]*', GLOB_MARK | GLOB_BRACE);
                foreach ($files as $file) {
                    $file->delete();
                }
                $folders = $this->findFolders('{,.}{,..}[!.,!..]*', GLOB_MARK | GLOB_BRACE | GLOB_ONLYDIR);
                foreach ($folders as $folder) {
                    $folder->delete(true);
                }
            }

            return rmdir($this->path);
        }
        throw new FolderException('Cannot delete folder, because ('.$this->path.') is not writable', FolderException::NOT_WRITEABLE);
    }
1276798
public static function removeFolder($folder, $contentsOnly = false)
    {

        // remove a file encountered by a recursive call.
        if (is_file($folder) || is_link($folder)) {
            unlink($folder);
        } else {
            $dir = opendir($folder);
            while ($file = readdir($dir)) {
                if (($file == '.' || $file == '..')) {
                    continue;
                } else {
                    self::removeFolder($folder . '/' . $file);
                }
            }
            closedir($dir);
            if (!$contentsOnly) {
                rmdir($folder);
            }
        }
    }
875502
public static function mkdir($path, $mode = 0755, $recursive = false, $force = false)
    {
        if (!self::exists($path)) {
            if ($force) {
                return @mkdir($path, $mode, $recursive);
            }

            return mkdir($path, $mode, $recursive);
        }

        return true;
    }
464190
public static function removeDirectory($directory)
    {
        $inner = new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS);
        $outer = new \RecursiveIteratorIterator($inner, \RecursiveIteratorIterator::SELF_FIRST);

        // remove the files first
        foreach ($outer as $file) {
            if ($file->isFile()) {
                unlink($file);
            }
        }

        // remove the sub-directories next
        $files = iterator_to_array($outer);
        foreach (array_reverse($files) as $file) {
            /** @var \SplFileInfo $file */
            if ($file->isDir()) {
                rmdir($file);
            }
        }

        // finally the directory itself
        rmdir($directory);
    }
865626
public static function ListAllFiles( string $folder, bool $recursive = false ) : array
   {

      // Init the array that should contain the resulting file paths
      $files = [];

      if ( ! @\is_dir( $folder ) )
      {
         // No folder = we are done here
         return $files;
      }

      if ( ! $recursive )
      {
         // List only files directly contained inside $folder (none from sub folders)

         // Open the directory pointer
         $d = \dir( $folder );
         // Ignore . and ..
         $d->read(); $d->read();
         // loop the rest
         while ( false !== ( $entry = $d->read() ) )
         {
            $tmp = Path::Combine( $folder, $entry );
            if ( ! \is_file( $tmp ) )
            {
               // Ignore sub folders
               continue;
            }
            $files[] = $tmp;
         }
         $d->close();
         return $files;
      }

      // List all files, also from sub folders
      static::_listRecursive( $files, $folder );

      return $files;

   }