Problem/Motivation
Eight backed enums under src/Enum/ share an identical toArray() implementation: iterate self::cases(), map each case through toGraphQlEnumValue(), and return an associative array keyed by the GraphQL enum name with the backing value. The duplication is copy-pasted across WebformElementDescriptionDisplay, WebformElementDisplayOn, WebformElementHelpDisplay, WebformElementTitleDisplay, WebformFormUnavailableReason, WebformMessageType, WebformSubmissionConfirmationType, and WebformWeekday. PHP 8.2+ allows traits on enums, so this can be consolidated without changing the public API.
Proposed resolution
Add a trait, e.g. GraphQlEnumValuesTrait, in src/Enum/ containing the shared static toArray():
public static function toArray(): array { $cases = []; foreach (self::cases() as $case) { $cases[$case->toGraphQlEnumValue()] = $case->value; } return $cases; }
Each affected enum adds use GraphQlEnumValuesTrait; and removes its local toArray() method. Each enum keeps its own toGraphQlEnumValue() implementation — naming is not uniform enough to share (explicit match expressions vs. CaseConverter on backing values in enums like WebformElementTrigger, which does not use toArray() today).
Optionally add a small interface, e.g. GraphQlBackedEnumInterface, declaring toGraphQlEnumValue(): string, implemented by enums that use the trait. This documents the contract the trait relies on but is not strictly required.
No changes to callers (WebformSchemaBuilder, etc.) — SomeEnum::toArray() remains the entry point.
Remaining tasks
- Add
GraphQlEnumValuesTrait(and optionallyGraphQlBackedEnumInterface). - Update the eight enums listed above to
usethe trait and drop duplicatedtoArray()bodies. - Confirm existing coverage still passes (e.g.
WebformElementDisplayOnTest::testToArray()). - Optionally add a focused unit test on one enum or the trait to guard against regressions.
Introduced terminology
GraphQlEnumValuesTrait — shared trait providing toArray() for backed enums that expose GraphQL enum values via toGraphQlEnumValue().
Issue fork graphql_webform-3600642
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #4
kieran.cottI've added a shared
GraphQlEnumValuesTraitandGraphQlBackedEnumInterface, and updated the eight affected backed enums to use the trait instead of carrying duplicatetoArray()implementations as described above.There's also a unit test for the trait using a test-only backed enum, so the shared mapping behaviour is covered directly.
Comment #5
pfrenssenWow, thanks for the lightning fast implementation @kieran.cott! Looks perfect, thanks very much!
Comment #7
kieran.cottComment #9
kieran.cottNo worries! Will leave it to maintainers to update the status.
Comment #10
pfrenssen