master

laravel/framework

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

RouteSignatureParameters.php

TLDR

This file defines a class RouteSignatureParameters in the Illuminate\Routing namespace. The class contains two methods:

  • fromAction: This method extracts the signature parameters from a route action.
  • fromClassMethodString: This method retrieves the parameters for a given class and method by string.

Methods

fromAction

This method takes an array $action and an optional array $conditions as parameters. It extracts the signature parameters from the route action.

  • If the action contains a serialized closure, it unserializes the closure and gets its parameters.
  • If the action uses a string callback, it calls the fromClassMethodString method to retrieve the parameters.

fromClassMethodString

This method takes a string $uses as a parameter. It parses the class and method from the $uses string using the Str::parseCallback method. If the class method exists and is callable, it returns an empty array. Otherwise, it uses reflection to get the parameters of the class method.

<?php

namespace Illuminate\Routing;

use Illuminate\Support\Reflector;
use Illuminate\Support\Str;
use ReflectionFunction;
use ReflectionMethod;

class RouteSignatureParameters
{
    /**
     * Extract the route action's signature parameters.
     *
     * @param  array  $action
     * @param  array  $conditions
     * @return array
     */
    public static function fromAction(array $action, $conditions = [])
    {
        $callback = RouteAction::containsSerializedClosure($action)
                        ? unserialize($action['uses'])->getClosure()
                        : $action['uses'];

        $parameters = is_string($callback)
                        ? static::fromClassMethodString($callback)
                        : (new ReflectionFunction($callback))->getParameters();

        return match (true) {
            ! empty($conditions['subClass']) => array_filter($parameters, fn ($p) => Reflector::isParameterSubclassOf($p, $conditions['subClass'])),
            ! empty($conditions['backedEnum']) => array_filter($parameters, fn ($p) => Reflector::isParameterBackedEnumWithStringBackingType($p)),
            default => $parameters,
        };
    }

    /**
     * Get the parameters for the given class / method by string.
     *
     * @param  string  $uses
     * @return array
     */
    protected static function fromClassMethodString($uses)
    {
        [$class, $method] = Str::parseCallback($uses);

        if (! method_exists($class, $method) && Reflector::isCallable($class, $method)) {
            return [];
        }

        return (new ReflectionMethod($class, $method))->getParameters();
    }
}