<?php

/**
 * Class FileSystemReader
 */
class FileSystemReader
{
    /**
     * @param $currentDir
     * @return array
     * @throws Exception
     */
    public function getFiles($currentDir)
    {
        if (!is_readable($currentDir)) {
            $error = 'Requested directory ' . $currentDir . ' is not readable.';
            syslog(LOG_DEBUG, 'Requesting - ' . $currentDir . ' Error: ' . $error);
            throw new Exception($error);
        }

        $currentDir .= '/*';
        // GLOB_ONLYDIR flag returns only directories
        $dirs = glob($currentDir, GLOB_ONLYDIR);

        $result = [];
        if (count($dirs) > 0) {
            foreach ($dirs as $dir) {
                $dir = realpath($dir);
                $directory = [
                    'name' => basename($dir),
                    'path' => ['absolute' => $dir, 'relative' => str_replace(POLICY_PATH, '', $dir)],
                ];
                // scandir always returns . and .. even for empty directory
                if (scandir($dir) > 2) {
                    $directory['children'] = $this->getFiles($dir);
                }
                $result[] = $directory;
            }
        }

        // there is no flag to get only files, so we exclude directories from result
        $files = array_diff(glob($currentDir), $dirs);
        if (count($files) > 0) {
            foreach ($files as $file) {
                $file = realpath($file);
                $result[] = [
                    'name' => basename($file),
                    'path' => ['absolute' => $file, 'relative' => str_replace(POLICY_PATH, '', $file)],
                    'hash' => hash_file('sha256', $file)
                ];
            }
        }

        return $result;
    }

    /**
     * @param $path
     * @return bool|string
     * @throws Exception
     */
    public function getFileContent($path)
    {
        if (!is_readable($path)) {
            $error = 'Requested file ' . $path . ' is not readable.';
            syslog(LOG_DEBUG, 'Requesting - ' . $_SERVER['REQUEST_URI'] . ' Error: ' . $error);
            throw new Exception($error);
        }

        return file_get_contents($path);
    }

}
