<?php

namespace Snaju\Inception\Util;

class Loader
{

    private $folder;
    private $regex;
    private $level = 0;
    private $matches = [];
    private $files = [];

    /**
     * Load constructor.
     * @param $folder
     * @param $regex
     * @param bool $autoLoad
     * @internal param bool $recursive
     * @internal param int $levels
     */
    public function __construct($folder, $regex, $autoLoad = true)
    {
        $this->folder = $folder;
        $this->regex = $regex;

        $this->collect($this->folder);
        $this->find();
        if ($autoLoad) {
            $this->load();
        }
    }

    public function collect($dir)
    {
//        if (strpos($dir, BASE . "/") !== false) {
        $baseDir = $dir . "/*";
//        } else {
//            $baseDir = BASE . "/" . $dir . "/*";
//        }

        foreach (glob($baseDir) as $file) {
            if (is_dir($file)) {
                $this->collect($file);
            } else {
                $this->files[] = $file;
            }
        }
    }

    public function find()
    {
        foreach ($this->files as $file) {
            if (preg_match($this->regex, $file)) {
                if (file_exists($file) && is_file($file)) {
                    $this->matches[] = $file;
                }
            }
        }
    }

    public function load()
    {
        if (count($this->matches) > 0) {
            foreach ($this->matches as $file) {
                require $file;
            }
        }
    }

    /**
     * @return mixed
     */
    public function getFolder()
    {
        return $this->folder;
    }

    /**
     * @param mixed $folder
     */
    public function setFolder($folder)
    {
        $this->folder = $folder;
    }

    /**
     * @return mixed
     */
    public function getRegex()
    {
        return $this->regex;
    }

    /**
     * @param mixed $regex
     */
    public function setRegex($regex)
    {
        $this->regex = $regex;
    }

    /**
     * @return mixed
     */
    public function getMatches()
    {
        return $this->matches;
    }

    /**
     * @return mixed
     */
    public function getFiles()
    {
        return $this->files;
    }
}

?>
