<?php

namespace Velis\Filesystem;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 * @author Damian Kurek <damian.kurek@velis.pl>
 */
trait ListKeysTrait
{
    /**
     * @param string $directory
     * @param string $prefix
     *
     * @return array
     */
    private function listKeysInDirectory($directory, $prefix = '')
    {
        $entries = [];
        $fullDirectoryPath = $this->basePath . $directory;
        if (!file_exists($fullDirectoryPath)) {
            return $entries;
        }

        $handle = opendir($fullDirectoryPath);

        while (false !== ($entry = readdir($handle))) {
            if (in_array($entry, ['.', '..'])) {
                continue;
            }

            $entryKey = ltrim($directory . '/' . $entry, '/');
            $entryFullPath = $this->basePath . $entryKey;

            $keyLength = strlen($entryKey);
            $prefixLength = strlen($prefix);

            $shorter = $keyLength >= $prefixLength ? $prefix : $entryKey;
            $longer = $keyLength >= $prefixLength ? $entryKey : $prefix;

            if (is_dir($entryFullPath) && (empty($prefix) || 0 === strpos($longer, $shorter))) {
                $entries = array_merge($entries, $this->listKeysInDirectory($entryKey, $prefix));
            }

            if (empty($prefix) || 0 === strpos($entryKey, $prefix)) {
                $entries[] = $entryKey;
            }
        }

        return $entries;
    }
}
