Fix Undefined Array Key Warning in generateFromRequest Method of FileNameGenerator Class

Created on 2 September 2024, 4 months ago

Problem/Motivation

The generateFromRequest method in the FileNameGenerator class of the ckeditor5_premium_features module throws a warning: Undefined array key 1. This issue occurs when the route name does not contain a dot (.), causing the explode('.', $route_name) function to return an array with fewer than two elements. Consequently, attempting to access $route_param[1] results in a PHP warning. This warning can cause unexpected behavior and errors when generating file names based on route and entity parameters.

Steps to Reproduce

  1. Use a route name that does not include a dot, such as protected_pages_login_page.
  2. Call the generateFromRequest method in the context where this route name is active.
  3. Observe the PHP warning: Undefined array key 1 in FileNameGenerator->generateFromRequest().

Proposed Resolution

  • Update the generateFromRequest method to check if the $route_param array has more than one element before attempting to access $route_param[1].
  • Implement fallback logic to handle cases where the route name format does not include a dot, defaulting to a common entity name or another logical fallback.
  • Example modification:
public function generateFromRequest(): string {
    $route_name = $this->routeMatch->getRouteName();
    $route_param = explode('.', $route_name);

    // Safely check if $route_param has enough elements
    if (count($route_param) > 1) {
        $entity = $this->routeMatch->getParameter($route_param[1]);
    } else {
        // Fallback if the route name doesn't contain a dot
        $entity = $this->routeMatch->getParameter('node'); // or use another default parameter
    }

    try {
        if ($entity) {
            $alias = $entity->toUrl()->toString();
            return $this->convertUrlToFileName($alias);
        }
    } catch (\Exception $e) {
        // Handle exceptions if necessary
    }

    return self::DEFAULT_FILENAME;
}
  • This change will ensure that the function can handle route names without dots and avoid PHP warnings related to undefined array keys.
🐛 Bug report
Status

Active

Version

1.3

Component

Code

Created by

🇬🇧United Kingdom meladawy

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024