phpsymfonysymfony-http-client

How can I make a http client request after another is completed?


In my Symfony function I am creating a folder, and inside this folder another folder:

$client = HttpClient::create();

$createFolder = $client->request('MKCOL', $path.$foldername, [
'auth_basic' => [$user, $authKey],
]);


$createImageFolder = $client->request('MKCOL', $path.$foldername/images', [
'auth_basic' => [$user, $authKey],
]);

It works well, but somtimes the first folder is not created fast enough, and the image folder cannot be created. Is there a way, that the second request can wait, until the first folder is created?


Solution

  • $client->request() is asynchronous. You can use $client->getStatusCode() to wait for the response before going to the next operation. You can also use this to confirm that the first operation was successful.

    $client = HttpClient::create();
    
    $createFolder = $client->request('MKCOL', $path.$foldername, [
        'auth_basic' => [$user, $authKey],
    ]);
    
    $code = $createFolder->getStatusCode();
    if ($code < 300) { // Creation was successful
        $createImageFolder = $client->request('MKCOL', $path.$foldername/images', [
            'auth_basic' => [$user, $authKey],
        ]);
    }