Search code examples
phpgoogle-slides-api

Function for repetitive Google Slides API 'requests' via PHP


I am new to Google Slides API using PHP. I am working on a script to produces slides via my script. If I layout all the 'requests' (i.e. createSlide, createTable, insertText) sequentially in the script, .....I am able to produce the slides in Google. However, I want to minimize all the requests by using a function, but keep encountering errors:

{ "error": { "code": 400, "message": "Invalid requests[1]: No request set.", "errors": [ { "message": "Invalid requests[1]: No request set.", "domain": "global", "reason": "badRequest" } ], "status": "INVALID_ARGUMENT" } } %s

my test sample code:

function createNewSlide($requests,$slide_id) {
        $requests[] = new Google_Service_Slides_Request([
                'createSlide' => [
                'objectId' => $slide_id
                ]
        ]);
     return $requests;
   } 

$requests = [];
$slide_id = 'unique_slide_id_'.rand(1,9999999);
$requests[] = createNewSlide($requests,$slide_id);

///////////////////////////////////////////////////////
// Execute the request.
$batchUpdateRequest = new Google_Service_Slides_BatchUpdatePresentationRequest(array(
    'requests' => $requests
));
try {
  $response = $slidesService->presentations->batchUpdate($created_presentation->presentationId, $batchUpdateRequest);
    print("A new slide was added to the presentation<br>");
} catch (\Exception $e) {
    //print($e->getMessageAsString()." \n%s\n");
    print($e->getMessage()." \n%s\n");
}
//////////////////////////////////////////////////////////

Solution

  • Continuing on from the comment,When you write $requests[] =, it means adding the result to an array. Then you return the resulting array. Since you want to return just the google object you don't have to pass $requests to the function and just return the google object from the function.

    function createNewSlide($slide_id) {
        return new Google_Service_Slides_Request([
                'createSlide' => [
                'objectId' => $slide_id
                ]
        ]);
    } 
    

    Then you can just add what returns from the function to $requests array.

    $requests[] = createNewSlide($slide_id);