<?php

namespace Miladmodaresi\Taamito\Base;

use WP_REST_Request;

/**
 * The Singleton class defines the `GetInstance` method that serves as an
 * alternative to constructor and lets clients access the same instance of this
 * class over and over.
 */
class Routes
{
    protected $middlewares = [];
    protected $callback = null;

    public function handleMiddlewares(WP_REST_Request $request)
    {
        foreach ($this->middlewares as $middleware) {
            (new $middleware())->handle($request);
        }
        return call_user_func_array($request->get_attributes()[0]['callback2'], [$request]);
    }
    public function setMiddlewares($middlewares = [])
    {
        $this->middlewares = array_merge($middlewares, $this->middlewares);
        return $this;
    }
    public function get($route, $callback)
    {
        register_rest_route('taamito/v1', $route, array(
            'methods' => 'GET',
            'callback' => [$this, 'handleMiddlewares'],
            ['callback2' => $callback]
        ));
    }
    public function post($route, $callback)
    {
        register_rest_route('taamito/v1', $route, array(
            'methods' => 'POST',
            'callback' => [$this, 'handleMiddlewares'],
            ['callback2' => $callback]
        ));
    }
}
