How can I dynamically construct a GraphQL query in PHP?

How can I dynamically construct a GraphQL query in PHP?


1

I’m using the following query in GraphQL:

$q = "
{ 
    shop { 
        name 
    } 
}
";

But I want to do it dynamically in PHP in the following way:

$fieldName = 'name';

$query = [
    "shop" => [
        $fieldName
    ]
];

And later on when passing the query to GraphQL I wanna convert in GraphQL suitable format.
Well I can do it by using iterative function in PHP but that doesn’t seem very efficient.

function formatGraphQLQuery($queryArray, $indentation = 0) {
    $formattedQuery = '';
    $indent = str_repeat('    ', $indentation);

    foreach ($queryArray as $field => $value) {
        if (is_array($value)) {
            $formattedQuery .= $indent . $field . " {n";
            $formattedQuery .= formatGraphQLQuery($value, $indentation + 1);
            $formattedQuery .= $indent . "}n";
        } else {
            $formattedQuery .= $indent . $value . "n";
        }
    }

    return $formattedQuery;
}

Also using json_encode doesn’t work as it returns in the following format:

{
    "shop":[
            "name"
        ]
}

So what would be an idea solution?

Share
Improve this question

0

1 Answer
1

Reset to default


0

I personnaly use HEREDOC syntax to write GraphQL queries.

HEREDOC syntax behaves like a double quote string so you can add variables in it

$fieldName = 'name';
$query = <<<GRAPHQL
{ 
    shop { 
        $fieldName
    } 
}
GRAPHQL;

Share
Improve this answer



Leave a Reply

Your email address will not be published. Required fields are marked *