theiconic / php-ga-measurement-protocol

Send data to Google Analytics from the server using PHP. Implements GA measurement protocol.
MIT License
655 stars 136 forks source link

Batch Requests #90

Closed jorgeborges closed 3 years ago

jorgeborges commented 3 years ago

Continues the work from #83 by @alberto-bottarini.

This PR allows you to batching multiple hits in a single request using /batch endpoint.

It adds some new methods:

Here's an example that sends two hits.

$analytics = new Analytics(false, false);

$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-xxxxxx-x')
    ->setClientId('xxxxxx.xxxxxx');    

foreach(range(0, 19) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->sendEnqueuedHits(); //push 20 pageviews in a single request and empty queue

The queue is emptied when the hits are sent, but it can also be empty manually with emptyQueue method.

$analytics = new Analytics(false, false);

$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-xxxxxx-x')
    ->setClientId('xxxxxx.xxxxxx');    

foreach(range(0, 5) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->emptyQueue(); // empty queue, allows to enqueue 20 hits again

foreach(range(1, 20) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->sendEnqueuedHits(); //push 20 pageviews in a single request
coveralls commented 3 years ago

Coverage Status

Coverage remained the same at 100.0% when pulling af8bdc5631abaefa90de6c8c05b8eb0c520ebfae on feature/batch-requests into 0797dcc1cf2cfee9cd0353e5615c1186cc8a721e on master.

jorgeborges commented 3 years ago

hey @alberto-bottarini, I'm done with the changes required for this to be merged.

Take notice that your commits are also in this PR. Changes that I made:

Besides that, I also did the following:

Everything else is working as in your PR.

If you are OK with these changes, I can merge right away and make a new release. Is this OK with you?

alberto-bottarini commented 3 years ago

It's ok for me! Thanks a lot