You are here

protected function EntityResolverManager::setParametersFromReflection in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Entity/EntityResolverManager.php \Drupal\Core\Entity\EntityResolverManager::setParametersFromReflection()

Sets the upcasting information using reflection.

Parameters

string|array $controller: A PHP callable representing the controller.

\Symfony\Component\Routing\Route $route: The route object to populate without upcasting information.

Return value

bool Returns TRUE if the upcasting parameters could be set, FALSE otherwise.

1 call to EntityResolverManager::setParametersFromReflection()
EntityResolverManager::setRouteOptions in core/lib/Drupal/Core/Entity/EntityResolverManager.php
Set the upcasting route objects.

File

core/lib/Drupal/Core/Entity/EntityResolverManager.php, line 120

Class

EntityResolverManager
Sets the entity route parameter converter options automatically.

Namespace

Drupal\Core\Entity

Code

protected function setParametersFromReflection($controller, Route $route) {
  $entity_types = $this
    ->getEntityTypes();
  $parameter_definitions = $route
    ->getOption('parameters') ?: [];
  $result = FALSE;
  if (is_array($controller)) {
    list($instance, $method) = $controller;
    $reflection = new \ReflectionMethod($instance, $method);
  }
  else {
    $reflection = new \ReflectionFunction($controller);
  }
  $parameters = $reflection
    ->getParameters();
  foreach ($parameters as $parameter) {
    $parameter_name = $parameter
      ->getName();

    // If the parameter name matches with an entity type try to set the
    // upcasting information automatically. Therefore take into account that
    // the user has specified some interface, so the upcasting is intended.
    if (isset($entity_types[$parameter_name])) {
      $entity_type = $entity_types[$parameter_name];
      $entity_class = $entity_type
        ->getClass();
      $reflection_class = Reflection::getParameterClassName($parameter);
      if ($reflection_class && (is_subclass_of($entity_class, $reflection_class) || $entity_class == $reflection_class)) {
        $parameter_definitions += [
          $parameter_name => [],
        ];
        $parameter_definitions[$parameter_name] += [
          'type' => 'entity:' . $parameter_name,
        ];
        $result = TRUE;
      }
    }
  }
  if (!empty($parameter_definitions)) {
    $route
      ->setOption('parameters', $parameter_definitions);
  }
  return $result;
}