Recursively clean a subdirectory

@param string $path Subdirectory path
@return int                                        Number of contained resources
349976
private function _cleanDirectory($path = '')
    {
        $resources = scandir($this->_base.$path);
        $resourceCount = count($resources);
        $links =
        $files = array();

        // Run through the directory contents
        foreach ($resources as $resource) {
            $absResource = $this->_base.$path.DIRECTORY_SEPARATOR.$resource;
            $origResource = SQUEEZR_DOCROOT.$path.DIRECTORY_SEPARATOR.$resource;

            // Ignore symbolic links to current and parent directory
            if (@is_dir($absResource) && (($resource == '.') || ($resource == '..'))) {
                --$resourceCount;
                continue;
            }

            // If it's a directory ...
            if (@is_dir($absResource)) {

                // Clean recursively and remove it alltogether in case it remains empty
                if (!@is_dir($origResource) || !$this->_cleanDirectory(ltrim($path.DIRECTORY_SEPARATOR.$resource,
                        DIRECTORY_SEPARATOR))
                ) {
                    @exec('rm -R '.escapeshellarg($absResource));
                    --$resourceCount;
                }

                // Else if it's a symbolic link: register it
            } elseif (@is_link($absResource)) {
                $links[] = $resource;

                // Else if it's a regular file: register it
            } elseif (@is_file($absResource)) {
                $files[] = $resource;

                // Else: No idea ... delete it!
            } else {
                if (@unlink($absResource)) {
                    --$resourceCount;
                }
            }
        }

        // Check & clean regular files
        foreach ($files as $file) {
            $absResource = $this->_base.$path.DIRECTORY_SEPARATOR.$file;

            // Proceed based on file extension
            switch (strtolower(pathinfo($file, PATHINFO_EXTENSION))) {

                // CSS file
                case 'css':

                    // If it's a breakpoint CSS file
                    if (preg_match("%^(.+)\-\d+\.css$%i", $file, $breakpointCssFile)) {
                        $origResource = SQUEEZR_DOCROOT.$path.DIRECTORY_SEPARATOR.$breakpointCssFile[1].'.css';

                        // Else: No idea ... delete it!
                    } else {
                        if (@unlink($absResource)) {
                            --$resourceCount;
                        }
                        continue 2;
                    }
                    break;

                // PHP cache file
                case 'php':

                    // If it's a PHP cache file
                    if (preg_match("%^(.+)\-squeezr\.css\.php$%i", $file, $phpCacheFile)) {
                        $origResource = SQUEEZR_DOCROOT.$path.DIRECTORY_SEPARATOR.$phpCacheFile[1].'.css';

                        // Else: No idea ... delete it!
                    } else {
                        if (@unlink($absResource)) {
                            --$resourceCount;
                        }
                        continue 2;
                    }
                    break;

                // Image files
                case 'png':
                case 'jpg':
                case 'jpeg':
                case 'gif':
                    $origResource = SQUEEZR_DOCROOT.$path.DIRECTORY_SEPARATOR.$file;
                    break;

                // Other extensions: Ignore
                default:
                    continue 2;
                    break;
            }

            // Remove the cache file if the original file doesn't exist anymore or is younger
            if (!@is_file($origResource) || (@filemtime($origResource) > @filemtime($absResource))) {
                if (@unlink($absResource)) {
                    --$resourceCount;
                }
            }
        }

        // Check & clean symbolic links
        foreach ($links as $link) {
            $absResource = $this->_base.$path.DIRECTORY_SEPARATOR.$link;
            $origResource = @readlink($absResource);

            // Delete the symbolic link if the original file doesn't exist anymore
            if ((!$origResource || !@is_file($origResource)) && @unlink($absResource)) {
                --$resourceCount;
            }
        }

        return $resourceCount;
    }
711059
public function deleteRecursive($path)
	{
		if (!$this->tryDelete($path)) {
			foreach ((array) $this->nlist($path) as $file) {
				if ($file !== '.' && $file !== '..') {
					$this->deleteRecursive(strpos($file, '/') === FALSE ? "$path/$file" : $file);
				}
			}
			$this->rmdir($path);
		}
	}
295494
public static function readAndDelete($path)
    {
        $path = self::normalizePath($path);
        $contents = file_get_contents($path);
        if ($contents === false) {
            return false;
        }
        self::removeFile($path);
        return $contents;
    }
448801
public static function remove($path)
    {
        $removed = 0;

        if (file_exists($path)) {
            if (is_dir($path)) {
                if (false === ($handle = @opendir($path))) {
                    throw PathException::createUsingLastError();
                }

                while (false !== ($item = readdir($handle))) {
                    if (('.' === $item) || ('..' === $item)) {
                        continue;
                    }

                    $removed += self::remove($path . DIRECTORY_SEPARATOR . $item);
                }

                closedir($handle);

                if (!@rmdir($path)) {
                    throw PathException::createUsingLastError();
                }
            } elseif (!@unlink($path)) {
                throw PathException::createUsingLastError();
            }

            $removed++;
        }

        return $removed;
    }
389216
protected function cleanPathInternal($path)
    {
        if ($this->isVirtual($path)) {
            return $this->cleanPath($path);
        }

        if ($this->hasCDBack($path)) {
            $realpath = $this->cleanPath(realpath($path));
            return $realpath ?: null;
        }

        return $this->cleanPath($path);
    }
219185
private function rmdir($path)
    {
        if (!@rmdir($path)) {
            // retry after a bit on windows since it tends to be touchy with mass removals
            if (!defined('PHP_WINDOWS_VERSION_BUILD') || (usleep(350000) && !@rmdir($path))) {
                $error = error_get_last();
                $message = 'Could not delete '.$path.': '.@$error['message'];
                if (defined('PHP_WINDOWS_VERSION_BUILD')) {
                    $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed";
                }

                throw new \RuntimeException($message);
            }
        }

        return true;
    }
205537
public function recursiveRemoveDirectory($path)
    {
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach ($files as $file) {
            if ($file->isDir()) {
                self::removeDirectory($file->getRealPath());
            } else {
                self::unlink($file->getRealPath());
            }
        }
        self::removeDirectory($path);
    }
556400
public static function cleanFilePathname($path) {
		if (UString::isNotNull ( $path )) {
			if (\DS === "/")
				$path = \str_replace ( "\\", \DS, $path );
			else
				$path = \str_replace ( "/", \DS, $path );
			$path = \str_replace ( \DS . \DS, \DS, $path );
		}
		return $path;
	}
271172
public static function cleanPath($path)
    {
        $regex = '/(\/)\/+/';
        $path = str_replace(['\\', '/ /'], '/', $path);
        $path = preg_replace($regex,'$1',$path);

        return $path;
    }
170991
public function getDirectory($path)
    {
        $subDirectory = new self($this->getFileSystemId(), $this->getFullPath($path));
        $subDirectory->setServiceLocator($this->getServiceLocator());
        return $subDirectory;
    }
465212
public static function rmdir($path)
    {
        if (true === is_dir($path)) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);

            foreach ($files as $file) {
                if (false === in_array($file->getBasename(), self::getDirSymbols())) {
                    if (true === $file->isDir()) {
                        rmdir($file->getPathName());
                    } else {
                        if ((true === $file->isFile()) || (true === $file->isLink())) {
                            unlink($file->getPathname());
                        }
                    }
                }
            }

            return rmdir($path);
        } else {
            if ((is_file($path) === true) || (is_link($path) === true)) {
                return unlink($path);
            }
        }

        return false;
    }
430331
protected function clearDir($path)
    {
        $items = [];
        $finder = new Finder();
        $finder->in($path)
            ->ignoreVCS(false)
            ->ignoreDotFiles(false);

        foreach ($finder as $item) {
            $items[] = $item->getRealpath();
        }

        if (count($items) > 0) {
            $this->fs->remove($items);
        }
    }
401018
public function delete($path)
    {
        $paths = is_array($path) ? $path : func_get_args();

        $success = true;

        foreach ($paths as $path) {
            try {
                if ($this->isDirectory($path)) {
                    if (!$this->deleteDirectoryRecursive($path)) {
                        $success = false;
                    }
                    continue;
                }
                if (!@unlink($path)) {
                    $success = false;
                }
            } catch (Throwable $e) {
                $success = false;
            }
        }

        return $success;
    }
50328
public static function clean($path, $dirSep = DIRECTORY_SEPARATOR): string
    {
        if (!is_string($path) || empty($path)) {
            return '';
        }

        $path = trim((string)$path);

        if (empty($path)) {
            $path = Vars::get($_SERVER['DOCUMENT_ROOT'], '');
        } elseif (($dirSep === '\\') && ($path[0] === '\\') && ($path[1] === '\\')) {
            $path = "\\" . preg_replace('#[/\\\\]+#', $dirSep, $path);
        } else {
            $path = preg_replace('#[/\\\\]+#', $dirSep, $path);
        }

        return $path;
    }
719397
private function clearDirectory($path)
    {
        $this->debug("Clear directory: {$path}");
        $this->delete($path);
        $this->makeDirectory($path);
    }
452152
public static function delDir($path)
    {
        $succeed = true;
        if (is_dir($path)){
            $objDir = opendir($path);
            while (false !== ($fileName = readdir($objDir))){
                if (($fileName != '.') && ($fileName != '..')){
                    chmod("$path/$fileName", 0777);
                    if (!is_dir("$path/$fileName")){
                        if (!unlink("$path/$fileName")){
                            $succeed = false;
                            break;
                        }
                    }
                    else{
                        self::delDir("$path/$fileName");
                    }
                }
            }
            if (!readdir($objDir)){
                closedir($objDir);
                if (!rmdir($path)){
                    $succeed = false;
                }
            }
        }
        return $succeed;
    }
1143610
public function dest($path)
    {
        return $this->iterate(function ($distFile) use ($path) {
            $dir = $path;

            /** @var DistFile $distFile */
            $filename = $distFile->getDistpathname();
            $dsPos = strrpos($filename, DIRECTORY_SEPARATOR);

            if ($dsPos) {
                $dir .= DIRECTORY_SEPARATOR . substr($filename, 0, $dsPos);
            }

            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }

            file_put_contents(
                $path . DIRECTORY_SEPARATOR . $filename,
                $distFile->getContent()
            );
        });
    }