Runs the callback for the given request
@param DispatcherInterface|array $dispatcher
@param null|string               $path
@param null|string               $method
@return mixed
@throws \LogicException
@throws \Throwable
1434
public function dispatch($dispatcher = null, $path = null, $method = null)
    {
        if (!$dispatcher) {
            $dispatcher = new Dispatcher;
        } elseif (\is_array($dispatcher)) {
            $dispatcher = new Dispatcher($dispatcher);
        }

        if (!$dispatcher instanceof DispatcherInterface) {
            throw new \InvalidArgumentException(
                'The first argument is must an array OR an object instanceof the DispatcherInterface'
            );
        }

        if (!$dispatcher->hasRouter()) {
            $dispatcher->setRouter($this);
        }

        return $dispatcher->dispatchUri($path, $method);
    }
248695
protected function getResult($method, $path, array $params = null, array $data = null)
    {
        if ($params === null) {
            $params = [];
        }
        $options = [
            'query' => $this->preParseParams($params),
        ];
        if (is_array($data) && count($data) > 0) {
            $options['json'] = $data;
        }

        $response = $this->call($method, [$path, $options]);

        $responseData = $this->parseResult($response->getBody(), $response->getStatusCode());

        if ($response->getStatusCode() !== 200) {
            throw new Exception(
                $responseData['message'],
                $responseData['code'],
                null,
                (($_ =& $responseData['errors']) ?: [])
            );
        }

        return $responseData;
    }
997785
private function send(callable $method, ...$args): \Generator
    {
        while ($this->busy) {
            try {
                yield $this->busy->promise();
            } catch (\Throwable $exception) {
                // Ignore failure from another operation.
            }
        }

        if (!$this->handle) {
            throw new ConnectionException("The connection to the database has been closed");
        }

        try {
            $this->deferred = $this->busy = new Deferred;

            $handle = $method(...$args);

            Loop::enable($this->poll);
            if (!$this->handle->flush()) {
                Loop::enable($this->await);
            }

            $result = yield $this->deferred->promise();
        } catch (pq\Exception $exception) {
            throw new FailureException($this->handle->errorMessage, 0, $exception);
        } finally {
            $this->deferred = $this->busy = null;
        }

        if (!$result instanceof pq\Result) {
            throw new FailureException("Unknown query result");
        }

        switch ($result->status) {
            case pq\Result::EMPTY_QUERY:
                throw new QueryError("Empty query string");

            case pq\Result::COMMAND_OK:
                if ($handle instanceof pq\Statement) {
                    return $handle; // Will be wrapped into a PqStatement object.
                }

                return new PqCommandResult($result);

            case pq\Result::TUPLES_OK:
                return new PqBufferedResultSet($result);

            case pq\Result::SINGLE_TUPLE:
                $this->busy = new Deferred;
                $result = new PqUnbufferedResultSet($this->fetch, $result, $this->release);
                return $result;

            case pq\Result::NONFATAL_ERROR:
            case pq\Result::FATAL_ERROR:
                throw new QueryExecutionError($result->errorMessage, $result->diag);

            case pq\Result::BAD_RESPONSE:
                throw new FailureException($result->errorMessage);

            default:
                throw new FailureException("Unknown result status");
        }
    }
1276730
public static function getResponse(
    $method,
    $path,
    RequestOptions $options = null
  )
  {
    $instance = static::getInstance();

    if ($options)
    {
      // Get via HTTP
      if (isset($instance->url) && $options->isHttp())
      {
        return $instance->getHTTPResponse($method, $path, $options);
      }
    }

    // Get from the internal call if available
    if (isset($instance->app))
    {
      return $instance->getRawResponse($method, $path, $options);
    }

    // todo better exception message with link
    throw new Exception(
      'No app configured for internal calls,
          and no URL supplied for HTTP based calls'
    );
  }
1206248
public function route(
		$path, $callback, $method='GET', $is_raw=null
	) {
		$this->core->route($path, function($args) use($callback){
			# set token if available
			if (isset($args['cookie'][$this->token_name])) {
				# via cookie
				$this->adm_set_user_token(
					$args['cookie'][$this->token_name]);
			} elseif (isset($args['header']['authorization'])) {
				# via request header
				$auth = explode(' ', $args['header']['authorization']);
				if (count($auth) == 2 && $auth[0] == $this->token_name) {
					$this->adm_set_user_token($auth[1]);
				}
			}
			# execute calback
			$callback($args);
		}, $method, $is_raw);
	}
766487
public function dispatch($method, $params)
    {
        // find() and all() are aliases
        if (($method == 'find' && empty($params)) || $method == 'all') {
            return $this->find();
        }

        // handle find or one with sql params
        else if (($method == 'find' || $method == 'one') && is_string($params[0])) {
            $rs = $this->find(new Criteria(array_shift($params), $params));

            return $method == 'one' ? $rs->one() : $rs;
        }

        // handle magical finders
        else if (preg_match('/^(findBy|oneBy)/', $method)) {
            $rs = $this->find(new Criteria($this->_sqlFromMethod($method), $params));

            return preg_match('/^(oneBy)/', $method) ? $rs->one() : $rs;
        }

        // handle byId
        else if ($method == 'byId') {
            return $this->_findById($params);
        }

        // Criteria search
        else if (isset($params[0]) && $params[0] instanceof Criteria) {
            return $this->find($params[0]);
        }

        // failed to wizard :(
        else {
            throw new \BadMethodCallException("Unable to dispatch '$method' to finder");
        }
    }
1160144
public function send($method, $callback)
    {
        $payload = $method->toPayloadString();

        if (!$this->isBatch) {
            $proxy = function ($err, $res) use ($method, $callback) {
                if ($err !== null) {
                    return call_user_func($callback, $err, null);
                }
                if (!is_array($res)) {
                    $res = $method->transform([$res], $method->outputFormatters);
                    return call_user_func($callback, null, $res[0]);
                }
                $res = $method->transform($res, $method->outputFormatters);

                return call_user_func($callback, null, $res);
            };
            $this->requestManager->sendPayload($payload, $proxy);
        } else {
            $this->methods[] = $method;
            $this->batch[] = $payload;
        }
    }
1217946
public function method($method, $path = null)
	{
		if($path !== null)
			$this->setPath($path);

		return $this->setMethod($method);
	}
816501
public function request($path, $method = Request::GET, $data = [], array $query = [])
    {
        return $this->_client->request('_snapshot/'.$path, $method, $data, $query);
    }
1286540
private static function _callDispatcher($dispatcherCallback) {
        $dispatcherCallback = $dispatcherCallback[0] !== '\\' ? __NAMESPACE__ . '\\' . $dispatcherCallback : $dispatcherCallback;

        if (!is_callable($dispatcherCallback)) {
            throw new \Exception('Routing dispacher [' . $dispatcherCallback . '] cannot be called.', 500);
        }

        return call_user_func_array($dispatcherCallback, [
            self::$_uri, self::$_config
        ]);
    }
213054
public function runResolver($resolver, $parameters = [], $method = null)
	{
		if (is_callable($resolver))
		{
            return call_user_func_array($resolver, $parameters);
        }

        if(class_exists($resolver))
        {
        	$instance = $this->container->make($resolver, $parameters);
		    if($instance instanceof Command)
		    {
		    	return Bus::dispatch($instance, $parameters);
		    }

		    if(is_callable([$instance, $method]))
		    {
		    	 return call_user_func_array([$instance, $method], $parameters);
		    }
        }

        if(strpos($resolver, '@') !== false)
        {
        	list($class, $method) = explode('@', $this->action['uses']);

        	if (!method_exists($instance = $this->container->make($class), $method)) {
		        throw new Exception('Invalid method mapped on object: ' . $class . '.');
		    }

        	return call_user_func_array([$instance, $method], $parameters);
        }

        throw new Exception('Invalid resolver: ' . $resolver . '.');
	}
564331
private function collectRoute(String $method, String $path, Callable $callback) : Route {

		if(in_array([$path, $method], $this->getRoutes()))
			throw new RouterException('Route already defined.');

		$route = new Route($method, $path, $callback);
		array_push($this->routes, $route);
		return $route;

	}
730250
protected function dispatchRouter($method, $path)
    {
        $router = $this->container['router'];
        $logger = $this->container['logger'];

        $logger->debug('Router dispatch.', ['method' => $method, 'path' => $path]);

        $router->init();
        $route_info = $router->dispatch($method, $path);

        $handler = null;
        $vars = [];

        switch ($route_info[0]) {
        case RouteDispatcher::NOT_FOUND:
            $logger->debug('Routing failed. Not Found.');
            throw new HttpNotFoundException('404 Not Found');
            break;
        case RouteDispatcher::METHOD_NOT_ALLOWED:
            $logger->debug('Routing failed. Method Not Allowd.');
            throw new HttpMethodNotAllowedException('405 Method Not Allowed');
            break;
        case RouteDispatcher::FOUND:
            $handler = $route_info[1];
            $vars = $route_info[2];
            $logger->debug('Route found.', ['handler' => $handler]);
            break;
        }

        return [$handler, $vars];
    }
509012
public function on($method, $path, $handler, $name = '') {
		if (!$this->result->hasHandler()
			&& $this->prefixMatched
			&& $this->request->isMethod($method)
		) {
			if ($this->matchPartial($path, true)) {
				$handlers = (array)$handler;

				if ($this->namespace) {
					foreach ($handlers as &$handler) {
						$handler = $this->namespace . $handler;
					}
				}

				if ($this->middlewares) {
					$handlers = array_merge($this->middlewares, $handlers);
				}

				$this->result->setHandler($handlers);
				$this->result->setStatus(200);
				$this->result->setParams($this->params);
			}
		}

		if ($name) {
			$this->urlGenerator->add($name, $this->prefix . $path);
		}

		return $this;
	}
117200
private function send($path, $method, array $parameters = [], array $headers = [], $body = null)
    {
        $request = $this->createRequest($path, $method, $parameters, $headers, $body);

        $event = new RequestEvent($request);
        $this->eventDispatcher->dispatch(GoogleMoviesClientEvents::REQUEST, $event);

        $this->lastResponse = $event->getResponse();

        if ($this->lastResponse instanceof Response) {
            return (string) $this->lastResponse->getBody();
        }

        return [];
    }
416683
public static function set($method, $path, $action)
    {
        if (is_array($method)) {
            foreach ($method as $value) {
                self::set($value, $path, $action);
            }
        } else {
            if (is_string($action)) {
                $action = parent::$prefixNS . $action;
            } elseif ($action !== null && !$action instanceof \Closure) {
                return null;
            }

            $method = strtoupper(trim($method));

            $path = parent::$prefixPath . $path;

            if (!isset(parent::$httpRoutes[$path])) {
                parent::$httpRoutes[$path] = array();
            }

            parent::$httpRoutes[$path][$method] = $action;
        }
    }
1260926
public function dispatch(int $status, string $path, string $method, $route)
    {
        // not found
        if ($status === RouterInterface::NOT_FOUND) {
            return $this->handleNotFound($path, $method);
        }

        // method not allowed
        if ($status === RouterInterface::METHOD_NOT_ALLOWED) {
            return $this->handleNotAllowed($path, $method, $route);
        }

        // trigger route found event
        $this->fire(self::ON_FOUND, [$path, $route]);

        $result = null;
        $options = $route->getOptions();

        // fire enter event
        // schema,domains ... metadata validate
        if (isset($options['enter']) && false === RouteHelper::call($options['enter'], [$options, $path])) {
            return $result;
        }

        $handler = $route->getHandler();
        $args = $route->getParams();

        try {
            // trigger route exec_start event
            $this->fire(self::ON_EXEC_START, [$path, $route]);

            $globChains = $this->getRouter()->getChains();
            $chains = $route->getChains();

            $result = $this->callHandler($path, $method, $handler, $args);

            // fire leave event
            if (isset($options['leave'])) {
                RouteHelper::call($options['leave'], [$options, $path]);
            }

            // trigger route exec_end event
            $this->fire(self::ON_EXEC_END, [$path, $route, $result]);
        } catch (\Throwable $e) {
            // trigger route exec_error event
            if ($cb = $this->getOption(self::ON_EXEC_ERROR)) {
                return RouteHelper::call($cb, [$e, $path, $route]);
            }

            throw $e;
        }

        return $result;
    }