Skip to content

Shorthand for type modifiers #617

Closed
Closed
@stevelacey

Description

@stevelacey

Argument types with modifiers can get a bit verbose e.g. if you want a non null list of non nulls:

Type::nonNull(Type::listOf(Type::nonNull(GraphQL::type('MyInput'))))

I've written a macro that adds support for variable type syntax GraphQL::parse('[MyInput!]!'):

GraphQL::macro('parse', function (string $string) {
    $modifiers = [];

    while (true) {
        if (Str::endsWith($string, '!')) {
            $string = Str::replaceLast('!', '', $string);
            array_unshift($modifiers, 'nonNull');
        } elseif (preg_match('/^\[.+\]$/', $string)) {
            $string = substr($string, 1, -1);
            array_unshift($modifiers, 'listOf');
        } else {
            $name = $string;
            break;
        }
    }

    if (in_array($name, Type::getStandardTypes())) {
        $type = Type::getStandardTypes()[$name];
    } else {
        $type = GraphQL::type($name);
    }

    foreach ($modifiers as $modifier) {
        $type = Type::$modifier($type);
    }

    return $type;
});

Also adds support for the standard types e.g. GraphQL::parse('[String!]').

The GraphQL::type() method already accepts a string, I'd consider adding in there.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions