Untitled

 avatar
unknown
plain_text
2 years ago
4.9 kB
1
Indexable
<?php


namespace App\Core;


use App\Config;
use App\Core\Request\Get;
use App\Core\Request\Post;
use Closure;

class Route
{
    private $file_dir;

    private static array $routes_list = [];

    public function __construct($dir = null)
    {
        $this->file_dir = Config::BASE_DIR;

        if ($dir)
            $this->file_dir = $dir;

    }

    /**
     * @return bool
     */
    private function getFile()
    {
        $request        = $_SERVER['REQUEST_URI'];
        $composedDir    = $this->file_dir . $request . '.php';
        $composedDirIdx = $this->file_dir . $request . '/index.php';

        if (file_exists($composedDir)) {
            include $composedDir;
        } elseif (file_exists($composedDirIdx)) {
            include $composedDirIdx;
        } else {
            return false;
        }
    }

    /**
     * @param string $resource
     * @return string
     */
    public static function route($resource = '')
    {
        $resource = str_replace(FileSystem::dir(), '', $resource);
        return htmlspecialchars_decode(Config::BASE_URL . $resource);
    }

    /**
     * @param string $resource
     * @return string
     */
    public static function assets($resource = '')
    {
        return Config::ASSETS_URL . $resource;
    }

    /**
     * @return string
     */
    public static function requestMethod()
    {
        return strtolower($_SERVER['REQUEST_METHOD']);
    }

    /**
     * @return string|string[]
     */
    public static function requestUri()
    {
        //$fullUrl = "{$_SERVER['REQUEST_SCHEME']}://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']}";
        //return str_replace(Config::BASE_URL, '', $fullUrl);

        $scheme = $_SERVER['REQUEST_SCHEME'] ? $_SERVER['REQUEST_SCHEME'] : 'http';
        $server_port = $_SERVER['SERVER_PORT'] && !in_array($_SERVER['SERVER_PORT'], [80, 443]) ? ':' . $_SERVER['SERVER_PORT'] : '';
        $fullUrl = "{$scheme}://{$_SERVER['SERVER_NAME']}{$server_port}{$_SERVER['REQUEST_URI']}";
        return str_replace(Config::BASE_URL, '', $fullUrl);
    }

    public static function isAjax()
    {

        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

    }


    /**
     * @param null|string $dir
     * @return Route
     */
    public static function init($dir = null)
    {
        return new Route($dir);
    }


    /**
     * @param $routes_list
     */
    public static function processRoutes(): void
    {
        global $eloquent;
        header('Content-Type: application/json');

        $eloquent::beginTransaction();
        try {

            $request_method = self::requestMethod();
            if (!isset(self::$routes_list[$request_method])) {
                throw new \Exception("Method '{$request_method}' not allowed");
            }

            $group = self::$routes_list[$request_method];

            $request = $group['request'];
            $options = $group['options'];

            $opt = $request['option'];

            if (!isset($options[$opt])) {
                if (!isset($options['default'])) {
                    throw new \Exception("Operation for option '{$opt}' not defined");
                } else {
                    $opt = 'default';
                }
            }

            $response = $options[$opt]($request);

            $eloquent::commit();
        } catch (\Exception $e) {

            $data     = [
                'error'   => $e->getMessage(),
                'line'    => $e->getLine(),
                'code'    => $e->getCode(),
                'file'    => $e->getFile(),
                'trace'   => $e->getTrace(),
                'request' => $_REQUEST, // para obtener la data
            ];
            $title    = 'Operation error';
            $status   = false;
            $response = compact('data', 'title', 'status');

            $eloquent::rollback();
        }

        echo collect($response)->toJson();
    }

    /**
     * @param string $option
     * @param Closure $callback
     */
    public static function post(string $option, Closure $callback): void
    {
        if (!isset(self::$routes_list['post'])) {
            self::$routes_list['post'] = [
                'request' => Post::get(),
                'options' => []
            ];
        }

        self::$routes_list['post']['options'][$option] = $callback;
    }

    /**
     * @param string $option
     * @param Closure $callback
     */
    public static function get(string $option, Closure $callback): void
    {
        if (!isset(self::$routes_list['get'])) {
            self::$routes_list['get'] = [
                'request' => Get::get(),
                'options' => []
            ];
        }

        self::$routes_list['get']['options'][$option] = $callback;
    }

}