master

laravel/framework

Last updated at: 29/12/2023 09:23

PrecognitionControllerDispatcher.php

TLDR

The provided file is PrecognitionControllerDispatcher.php which is part of the Illuminate\Foundation\Routing namespace. It extends the ControllerDispatcher class and contains two methods: dispatch and ensureMethodExists. The dispatch method is responsible for dispatching a request to a controller method, while the ensureMethodExists method ensures that a specific method exists on the controller class.

Methods

dispatch

Dispatches a request to a given controller and method.

  • Parameters:
    • $route (Route): The route object for the request.
    • $controller (mixed): The controller to dispatch the request to.
    • $method (string): The method to be called on the controller.
  • Returns: void
  • Description: This method ensures that the specified method exists on the controller, resolves the method's parameters using the route, controller, and method, and then aborts the request with a 204 status code and the Precognition-Success header set to true.

ensureMethodExists

Ensures that the given method exists on the controller.

  • Parameters:
    • $controller (object): The controller object.
    • $method (string): The method to be checked.
  • Returns: $this
  • Description: This method checks if the specified method exists on the controller. If the method exists, it returns the current object. If the method does not exist, it throws a RuntimeException with an error message indicating that the method is not defined.
<?php

namespace Illuminate\Foundation\Routing;

use Illuminate\Routing\ControllerDispatcher;
use Illuminate\Routing\Route;
use RuntimeException;

class PrecognitionControllerDispatcher extends ControllerDispatcher
{
    /**
     * Dispatch a request to a given controller and method.
     *
     * @param  \Illuminate\Routing\Route  $route
     * @param  mixed  $controller
     * @param  string  $method
     * @return void
     */
    public function dispatch(Route $route, $controller, $method)
    {
        $this->ensureMethodExists($controller, $method);

        $this->resolveParameters($route, $controller, $method);

        abort(204, headers: ['Precognition-Success' => 'true']);
    }

    /**
     * Ensure that the given method exists on the controller.
     *
     * @param  object  $controller
     * @param  string  $method
     * @return $this
     */
    protected function ensureMethodExists($controller, $method)
    {
        if (method_exists($controller, $method)) {
            return $this;
        }

        $class = $controller::class;

        throw new RuntimeException("Attempting to predict the outcome of the [{$class}::{$method}()] method but the method is not defined.");
    }
}