<commit_before><?php

namespace LizardsAndPumpkins\Utils;

use LizardsAndPumpkins\Utils\Exception\DirectoryDoesNotExistException;
use LizardsAndPumpkins\Utils\Exception\DirectoryNotWritableException;

class LocalFilesystem
{
    /**
     * @param string $directoryPath
     */
    public function removeDirectoryAndItsContent($directoryPath)
    {
        if (!is_dir($directoryPath)) {
            throw new DirectoryDoesNotExistException(sprintf('The directory "%s" does not exist', $directoryPath));
        }

        if (!is_writable($directoryPath)) {
            throw new DirectoryNotWritableException(sprintf('The directory "%s" is not writable', $directoryPath));
        }

        $directoryIterator = new \RecursiveDirectoryIterator($directoryPath, \FilesystemIterator::SKIP_DOTS);

        foreach (new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::CHILD_FIRST) as $path) {
            $path->isDir() && !$path->isLink() ? rmdir($path->getPathname()) : unlink($path->getPathname());
        }

        rmdir($directoryPath);
    }

    /**
     * @param string $directoryPath
     */
    public function removeDirectoryContents($directoryPath)
    {
        if (!file_exists($directoryPath)) {
            return;
        }
        if (!is_dir($directoryPath)) {
            $message = sprintf('The given path is not a directory: "%s"', $directoryPath);
            throw new Exception\NotADirectoryException($message);
        }
        $directoryIterator = new \RecursiveDirectoryIterator($directoryPath, \FilesystemIterator::SKIP_DOTS);
        foreach ($directoryIterator as $path) {
            is_dir($path->getPathname()) ?
                $this->removeDirectoryAndItsContent($path->getPathname()) :
                unlink($path->getPathname());
        }
    }

    /**
     * @param string $basePath
     * @param string $path
     * @return string
     */
    public function getRelativePath($basePath, $path)
    {
        if (0 === strpos($path, $basePath) || $basePath === $path . '/') {
            return ltrim(substr($path, strlen($basePath)), '/');
        }

        if ($this->isRelativePath($path)) {
            return $path;
        }

        return $this->buildRelativePath($basePath, $path);
    }

    /**
     * @param string $basePath
     * @param string $path
     * @return string
     */
    private function buildRelativePath($basePath, $path)
    {
        $pathParts = explode('/', rtrim($path, '/'));
        $basePathParts = explode('/', rtrim($basePath, '/'));
        $commonDirCount = $this->getCountOfSharedDirectories($basePathParts, $pathParts);
        $downPath = $this->buildDownPortionOfRelativePath($commonDirCount, $basePathParts);
        $upPath = $this->buildUpPortionOfRelativePath($commonDirCount, $pathParts);

        return $downPath . $upPath . (substr($path, - 1) === '/' ? '/' : '');
    }

    /**
     * @param string[] $basePathParts
     * @param string[] $pathParts
     * @return int
     */
    private function getCountOfSharedDirectories(array $basePathParts, array $pathParts)
    {
        $commonPartCount = 0;
        for ($max = min(count($pathParts), count($basePathParts)); $commonPartCount < $max; $commonPartCount ++) {
            if ($pathParts[$commonPartCount] !== $basePathParts[$commonPartCount]) {
                return $commonPartCount;
            }
        }

        return $commonPartCount;
    }

    /**
     * @param int $commonDirCount
     * @param string[] $basePathParts
     * @return string
     */
    private function buildDownPortionOfRelativePath($commonDirCount, array $basePathParts)
    {<commit_msg>Issue #393: Refactor LocalFilesystem::getCountOfSharedDirectories<commit_after><?php

namespace LizardsAndPumpkins\Utils;

use LizardsAndPumpkins\Utils\Exception\DirectoryDoesNotExistException;
use LizardsAndPumpkins\Utils\Exception\DirectoryNotWritableException;

class LocalFilesystem
{
    /**
     * @param string $directoryPath
     */
    public function removeDirectoryAndItsContent($directoryPath)
    {
        if (!is_dir($directoryPath)) {
            throw new DirectoryDoesNotExistException(sprintf('The directory "%s" does not exist', $directoryPath));
        }

        if (!is_writable($directoryPath)) {
            throw new DirectoryNotWritableException(sprintf('The directory "%s" is not writable', $directoryPath));
        }

        $directoryIterator = new \RecursiveDirectoryIterator($directoryPath, \FilesystemIterator::SKIP_DOTS);

        foreach (new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::CHILD_FIRST) as $path) {
            $path->isDir() && !$path->isLink() ? rmdir($path->getPathname()) : unlink($path->getPathname());
        }

        rmdir($directoryPath);
    }

    /**
     * @param string $directoryPath
     */
    public function removeDirectoryContents($directoryPath)
    {
        if (!file_exists($directoryPath)) {
            return;
        }
        if (!is_dir($directoryPath)) {
            $message = sprintf('The given path is not a directory: "%s"', $directoryPath);
            throw new Exception\NotADirectoryException($message);
        }
        $directoryIterator = new \RecursiveDirectoryIterator($directoryPath, \FilesystemIterator::SKIP_DOTS);
        foreach ($directoryIterator as $path) {
            is_dir($path->getPathname()) ?
                $this->removeDirectoryAndItsContent($path->getPathname()) :
                unlink($path->getPathname());
        }
    }

    /**
     * @param string $basePath
     * @param string $path
     * @return string
     */
    public function getRelativePath($basePath, $path)
    {
        if (0 === strpos($path, $basePath) || $basePath === $path . '/') {
            return ltrim(substr($path, strlen($basePath)), '/');
        }

        if ($this->isRelativePath($path)) {
            return $path;
        }

        return $this->buildRelativePath($basePath, $path);
    }

    /**
     * @param string $basePath
     * @param string $path
     * @return string
     */
    private function buildRelativePath($basePath, $path)
    {
        $pathParts = explode('/', rtrim($path, '/'));
        $basePathParts = explode('/', rtrim($basePath, '/'));
        $commonDirCount = $this->getCountOfSharedDirectories($basePathParts, $pathParts);
        $downPath = $this->buildDownPortionOfRelativePath($commonDirCount, $basePathParts);
        $upPath = $this->buildUpPortionOfRelativePath($commonDirCount, $pathParts);

        return $downPath . $upPath . (substr($path, - 1) === '/' ? '/' : '');
    }

    /**
     * @param string[] $basePathParts
     * @param string[] $pathParts
     * @return int
     */
    private function getCountOfSharedDirectories(array $basePathParts, array $pathParts)
    {
        $commonPartCount = 0;
        for ($max = min(count($pathParts), count($basePathParts)); $commonPartCount < $max; $commonPartCount ++) {
            if ($pathParts[$commonPartCount] !== $basePathParts[$commonPartCount]) {
                break;
            }
        }

        return $commonPartCount;
    }

    /**
     * @param int $commonDirCount
     * @param string[] $basePathParts
     * @return string
     */
    private function buildDownPortionOfRelativePath($commonDirCount, array $basePathParts)
    {
{'fraction_non_alphanumeric': 0.13594218707390238, 'fraction_numerical': 0.0012271611671666213, 'mean_word_length': 2.81038961038961, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5603858', 'n_tokens_mistral': 2077, 'n_tokens_neox': 2035, 'n_words': 382}