wearerequired / harvest-api-php-client

⏱ PHP client library for the Harvest REST API v2.
https://help.getharvest.com/api-v2/
MIT License
14 stars 13 forks source link

Access data in AutoPagingIterator Object? #48

Open ursbraem opened 2 years ago

ursbraem commented 2 years ago

I get all our active clients with

    $harvest = new \Required\Harvest\Client();
    $harvest->authenticate( config('services.harvest.account_id'), config('services.harvest.token') );
    $clients = $harvest->clients()->allWithAutoPagingIterator(['is_active'=>true]);

When I foreach through the $clients, I can access all data in an array for each client. But how to get the entire data out of the AutoPagingIterator object into an array of all clients (invoices, contacts etc)?

Seems ->data is a protected property, I also tried ->getData(). What do you recommend?


PS huge thanks for this library! Good to see we're not the only swiss company using harvest. We now make our QR-BESR via api...

ocean90 commented 2 years ago

Hey there, to convert the iterator object into an array you can use iterator_to_array(). But it seems like you also want to get invoices for a client? In this case you have to do a follow-up request for the invoices endpoint and set the client_id parameter.

$clients = $harvest->clients()->allWithAutoPagingIterator(['is_active'=>true]);

foreach ( $clients as $client ) {
    $invoices = $harvest->invoices()->allWithAutoPagingIterator(['client_id'=>$client['id']]);
    // Do another foreach loop or use iterator_to_array().
}

Does this help?

ursbraem commented 2 years ago

Hey there, to convert the iterator object into an array you can use iterator_to_array().

oha! Thanks! Works flawlessly.

No, I've got my invoices already (just need drafts). Including the BESRs 🎉 Do you want them? I'm using https://github.com/sprain/php-swiss-qr-bill but probably you have solved that already for yourself :-)

What I now struggled with was that I was looping contacts and requesting clients in each loop similar to your example above. Which is taking quite a while. So I want to avoid that and first get all clients & all contacts and match them in a less expensive way afterwards. That's why I want the array.

But what I wondered: Maybe the looped requests to harvest are just slow, but not (php) timeout-sensitive, as guzzlehttp will manage all those requests in the background?