Skip to content

Commit 079695b

Browse files
authored
feat: [AnalyticsData] add samples for run_report with ordering, pagination, property quota (GoogleCloudPlatform#1744)
1 parent c2b0655 commit 079695b

File tree

5 files changed

+361
-5
lines changed

5 files changed

+361
-5
lines changed

analyticsdata/src/run_report.php

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,15 +33,13 @@
3333
use Google\Analytics\Data\V1beta\RunReportResponse;
3434

3535
/**
36-
* @param string $propertyID Your GA-4 Property ID
37-
*/
36+
* @param string $propertyId Your GA-4 Property ID
37+
*/
3838
function run_report(string $propertyId)
3939
{
40-
// [START analyticsdata_initialize]
40+
// Create an instance of the Google Analytics Data API client library.
4141
$client = new BetaAnalyticsDataClient();
4242

43-
// [END analyticsdata_initialize]
44-
4543
// Make an API call.
4644
$response = $client->runReport([
4745
'property' => 'properties/' . $propertyId,
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
<?php
2+
/**
3+
* Copyright 2022 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* Google Analytics Data API sample application demonstrating the ordering of
20+
* report rows.
21+
* See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.order_bys
22+
* for more information.
23+
* Usage:
24+
* composer update
25+
* php run_report_with_ordering.php YOUR-GA4-PROPERTY-ID
26+
*/
27+
28+
namespace Google\Cloud\Samples\Analytics\Data;
29+
30+
// [START analyticsdata_run_report_with_ordering]
31+
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
32+
use Google\Analytics\Data\V1beta\DateRange;
33+
use Google\Analytics\Data\V1beta\Dimension;
34+
use Google\Analytics\Data\V1beta\Metric;
35+
use Google\Analytics\Data\V1beta\MetricType;
36+
use Google\Analytics\Data\V1beta\OrderBy;
37+
use Google\Analytics\Data\V1beta\OrderBy\MetricOrderBy;
38+
use Google\Analytics\Data\V1beta\RunReportResponse;
39+
40+
/**
41+
* Runs a report of active users grouped by three dimensions, ordered by
42+
* the total revenue in descending order.
43+
* @param string $propertyId Your GA-4 Property ID
44+
*/
45+
function run_report_with_ordering(string $propertyId)
46+
{
47+
// Create an instance of the Google Analytics Data API client library.'
48+
$client = new BetaAnalyticsDataClient();
49+
50+
// Make an API call.
51+
$response = $client->runReport([
52+
'property' => 'properties/' . $propertyId,
53+
'dimensions' => [new Dimension(['name' => 'date'])],
54+
'metrics' => [
55+
new Metric(['name' => 'activeUsers']),
56+
new Metric(['name' => 'newUsers']),
57+
new Metric(['name' => 'totalRevenue']),
58+
],
59+
'dateRanges' => [
60+
new DateRange([
61+
'start_date' => '7daysAgo',
62+
'end_date' => 'today',
63+
]),
64+
],
65+
'orderBys' => [
66+
new OrderBy([
67+
'metric' => new MetricOrderBy([
68+
'metric_name' => 'totalRevenue',
69+
]),
70+
'desc' => true,
71+
]),
72+
],
73+
]);
74+
75+
printRunReportResponseWithOrdering($response);
76+
}
77+
78+
/**
79+
* Print results of a runReport call.
80+
* @param RunReportResponse $response
81+
*/
82+
function printRunReportResponseWithOrdering(RunReportResponse $response)
83+
{
84+
// [START analyticsdata_print_run_report_response_header]
85+
printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
86+
foreach ($response->getDimensionHeaders() as $dimensionHeader) {
87+
printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
88+
}
89+
foreach ($response->getMetricHeaders() as $metricHeader) {
90+
printf(
91+
'Metric header name: %s (%s)' . PHP_EOL,
92+
$metricHeader->getName(),
93+
MetricType::name($metricHeader->getType())
94+
);
95+
}
96+
// [END analyticsdata_print_run_report_response_header]
97+
98+
// [START analyticsdata_print_run_report_response_rows]
99+
print 'Report result: ' . PHP_EOL;
100+
101+
foreach ($response->getRows() as $row) {
102+
printf(
103+
'%s %s' . PHP_EOL,
104+
$row->getDimensionValues()[0]->getValue(),
105+
$row->getMetricValues()[0]->getValue()
106+
);
107+
}
108+
// [END analyticsdata_print_run_report_response_rows]
109+
}
110+
// [END analyticsdata_run_report_with_ordering]
111+
112+
// The following 2 lines are only needed to run the samples
113+
require_once __DIR__ . '/../../testing/sample_helpers.php';
114+
return \Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
<?php
2+
/**
3+
* Copyright 2022 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* Google Analytics Data API sample application demonstrating the use of
20+
* pagination to retrieve large result sets.
21+
* See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.offset
22+
* for more information.
23+
* Usage:
24+
* composer update
25+
* php run_report_with_pagination.php YOUR-GA4-PROPERTY-ID
26+
*/
27+
28+
namespace Google\Cloud\Samples\Analytics\Data;
29+
30+
// [START analyticsdata_run_report_with_pagination]
31+
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
32+
use Google\Analytics\Data\V1beta\DateRange;
33+
use Google\Analytics\Data\V1beta\Dimension;
34+
use Google\Analytics\Data\V1beta\Metric;
35+
use Google\Analytics\Data\V1beta\MetricType;
36+
use Google\Analytics\Data\V1beta\RunReportResponse;
37+
38+
/**
39+
* Runs a report several times, each time retrieving a portion of result
40+
* using pagination.
41+
* @param string $propertyId Your GA-4 Property ID
42+
*/
43+
function run_report_with_pagination(string $propertyId)
44+
{
45+
// Create an instance of the Google Analytics Data API client library.
46+
$client = new BetaAnalyticsDataClient();
47+
48+
// Make an API call.
49+
$response = $client->runReport([
50+
'property' => 'properties/' . $propertyId,
51+
'dateRanges' => [
52+
new DateRange([
53+
'start_date' => '350daysAgo',
54+
'end_date' => 'yesterday',
55+
])
56+
],
57+
'dimensions' => [
58+
new Dimension(['name' => 'firstUserSource']),
59+
new Dimension(['name' => 'firstUserMedium']),
60+
new Dimension(['name' => 'firstUserCampaignName']),
61+
],
62+
'metrics' => [
63+
new Metric(['name' => 'sessions']),
64+
new Metric(['name' => 'conversions']),
65+
new Metric(['name' => 'totalRevenue']),
66+
],
67+
'limit' => 100000,
68+
'offset' => 0,
69+
]);
70+
71+
printRunReportResponseWithPagination($response);
72+
}
73+
74+
/**
75+
* Print results of a runReport call.
76+
* @param RunReportResponse $response
77+
*/
78+
function printRunReportResponseWithPagination(RunReportResponse $response)
79+
{
80+
// [START analyticsdata_print_run_report_response_header]
81+
printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
82+
foreach ($response->getDimensionHeaders() as $dimensionHeader) {
83+
printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
84+
}
85+
foreach ($response->getMetricHeaders() as $metricHeader) {
86+
printf(
87+
'Metric header name: %s (%s)' . PHP_EOL,
88+
$metricHeader->getName(),
89+
MetricType::name($metricHeader->getType())
90+
);
91+
}
92+
// [END analyticsdata_print_run_report_response_header]
93+
94+
// [START analyticsdata_print_run_report_response_rows]
95+
print 'Report result: ' . PHP_EOL;
96+
97+
foreach ($response->getRows() as $row) {
98+
printf(
99+
'%s %s' . PHP_EOL,
100+
$row->getDimensionValues()[0]->getValue(),
101+
$row->getMetricValues()[0]->getValue()
102+
);
103+
}
104+
// [END analyticsdata_print_run_report_response_rows]
105+
}
106+
// [END analyticsdata_run_report_with_pagination]
107+
108+
// The following 2 lines are only needed to run the samples
109+
require_once __DIR__ . '/../../testing/sample_helpers.php';
110+
return \Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
<?php
2+
/**
3+
* Copyright 2022 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
/**
19+
* Google Analytics Data API sample application demonstrating the usage of
20+
* property quota metadata.
21+
* See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.return_property_quota
22+
* for more information.
23+
* Usage:
24+
* composer update
25+
* php run_report_with_property_quota.php YOUR-GA4-PROPERTY-ID
26+
*/
27+
28+
namespace Google\Cloud\Samples\Analytics\Data;
29+
30+
// [START analyticsdata_run_report_with_property_quota]
31+
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
32+
use Google\Analytics\Data\V1beta\DateRange;
33+
use Google\Analytics\Data\V1beta\Dimension;
34+
use Google\Analytics\Data\V1beta\Metric;
35+
use Google\Analytics\Data\V1beta\RunReportResponse;
36+
37+
/**
38+
* Runs a report and prints property quota information.
39+
* @param string $propertyId Your GA-4 Property ID
40+
*/
41+
function run_report_with_property_quota(string $propertyId)
42+
{
43+
// Create an instance of the Google Analytics Data API client library.
44+
$client = new BetaAnalyticsDataClient();
45+
46+
// Make an API call.
47+
$response = $client->runReport([
48+
'property' => 'properties/' . $propertyId,
49+
'returnPropertyQuota' => true,
50+
'dimensions' => [new Dimension(['name' => 'country'])],
51+
'metrics' => [new Metric(['name' => 'activeUsers'])],
52+
'dateRanges' => [
53+
new DateRange([
54+
'start_date' => '7daysAgo',
55+
'end_date' => 'today',
56+
]),
57+
],
58+
]);
59+
60+
printRunReportResponseWithPropertyQuota($response);
61+
}
62+
63+
/**
64+
* Print results of a runReport call.
65+
* @param RunReportResponse $response
66+
*/
67+
function printRunReportResponseWithPropertyQuota(RunReportResponse $response)
68+
{
69+
// [START analyticsdata_run_report_with_property_quota_print_response]
70+
if ($response->hasPropertyQuota()) {
71+
$propertyQuota = $response->getPropertyQuota();
72+
$tokensPerDay = $propertyQuota->getTokensPerDay();
73+
$tokensPerHour = $propertyQuota->getTokensPerHour();
74+
$concurrentRequests = $propertyQuota->getConcurrentRequests();
75+
$serverErrors = $propertyQuota->getServerErrorsPerProjectPerHour();
76+
$thresholdedRequests = $propertyQuota->getPotentiallyThresholdedRequestsPerHour();
77+
78+
printf(
79+
'Tokens per day quota consumed: %s, remaining: %s' . PHP_EOL,
80+
$tokensPerDay->getConsumed(),
81+
$tokensPerDay->getRemaining(),
82+
);
83+
printf(
84+
'Tokens per hour quota consumed: %s, remaining: %s' . PHP_EOL,
85+
$tokensPerHour->getConsumed(),
86+
$tokensPerHour->getRemaining(),
87+
);
88+
printf(
89+
'Concurrent requests quota consumed: %s, remaining: %s' . PHP_EOL,
90+
$concurrentRequests->getConsumed(),
91+
$concurrentRequests->getRemaining(),
92+
);
93+
printf(
94+
'Server errors per project per hour quota consumed: %s, remaining: %s' . PHP_EOL,
95+
$serverErrors->getConsumed(),
96+
$serverErrors->getRemaining(),
97+
);
98+
printf(
99+
'Potentially thresholded requests per hour quota consumed: %s, remaining: %s' . PHP_EOL,
100+
$thresholdedRequests->getConsumed(),
101+
$thresholdedRequests->getRemaining(),
102+
);
103+
}
104+
// [END analyticsdata_run_report_with_property_quota_print_response]
105+
}
106+
// [END analyticsdata_run_report_with_property_quota]
107+
108+
// The following 2 lines are only needed to run the samples
109+
require_once __DIR__ . '/../../testing/sample_helpers.php';
110+
return \Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

analyticsdata/test/analyticsDataTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,4 +179,28 @@ public function testRunReportWithAggregations()
179179

180180
$this->assertStringContainsString('Report result', $output);
181181
}
182+
183+
public function testRunReportWithOrdering()
184+
{
185+
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
186+
$output = $this->runFunctionSnippet('run_report_with_ordering', [$propertyId]);
187+
188+
$this->assertStringContainsString('Report result', $output);
189+
}
190+
191+
public function testRunReportWithPagination()
192+
{
193+
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
194+
$output = $this->runFunctionSnippet('run_report_with_pagination', [$propertyId]);
195+
196+
$this->assertStringContainsString('Report result', $output);
197+
}
198+
199+
public function testRunReportWithPropertyQuota()
200+
{
201+
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
202+
$output = $this->runFunctionSnippet('run_report_with_property_quota', [$propertyId]);
203+
204+
$this->assertStringContainsString('Tokens per day quota consumed', $output);
205+
}
182206
}

0 commit comments

Comments
 (0)