Error generating enum for menu ids starting with numbers

Created on 11 September 2023, 10 months ago
Updated 25 January 2024, 5 months ago

Problem/Motivation

1.0.0-beta6 adds enums for menu names for menuByName() query. As per graphql specs, a valid name should not start with a number. So, if there is any menu id/machine name which starts with number(for example, 1menu) this breaks the enum generation with error:
GraphQL\Error\SyntaxError: Syntax Error: Expected Name, found Int "1" in GraphQL\Language\Parser->expect() (line 366 of vendor/webonyx/graphql-php/src/Language/Parser.php).

The enum of menu names is being generated in graphql_core_schema\src\Plugin\GraphQL\SchemaExtension\MenuExtension::buildMenuNameEnum()

Steps to reproduce

1. Create a menu with a name having digit as its first character. e.g. 1main
2. Create a graphql server and enable "Menu" extension.
3. Goto explorer tab to see the error.

Proposed resolution

To handle such cases, we can prefix the enum key with 'MENU_' .

--- a/src/Plugin/GraphQL/SchemaExtension/MenuExtension.php
+++ b/src/Plugin/GraphQL/SchemaExtension/MenuExtension.php
@@ -113,7 +113,7 @@ class MenuExtension extends SdlSchemaExtensionPluginBase implements CoreSchemaEx
       /** @var \Drupal\system\Entity\Menu $menu */
       $menu = $storage->load($id);
       $key = strtoupper(str_replace('-', '_', $id));
-      $values[$key] = [
+      $values['MENU_' . $key] = [
         'value' => $key,
         'description' => $menu->getDescription(),
       ];
@@ -152,8 +152,9 @@ class MenuExtension extends SdlSchemaExtensionPluginBase implements CoreSchemaEx
       $builder->produce('entity_load')
         ->map('type', $builder->fromValue('menu'))
         ->map('id', $builder->callback(function ($value, $args) {
-          // Convert the enum from MY_MENU_NAME to my-menu-name.
-          return str_replace('_', '-', strtolower($args['name']));
+          // Convert the enum from MENU_MY_MENU_NAME to my-menu-name.
+          return str_replace('_', '-', strtolower(preg_replace('/^' . preg_quote('MENU_', '/') . '/', '', $args['name'])));
         }))
     );

Remaining tasks

- May be there is a better fix.

🐛 Bug report
Status

Fixed

Version

1.0

Component

Code

Created by

🇮🇳India sumit_saini

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

Comments & Activities

Production build 0.69.0 2024