Skip to content

Commit c02b4c7

Browse files
authored
feat(analyticsdata): add samples for batch and pivot reports (GoogleCloudPlatform#1746)
1 parent ca9ee44 commit c02b4c7

File tree

3 files changed

+249
-0
lines changed

3 files changed

+249
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
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 batch creation
20+
* of multiple reports.
21+
* See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/batchRunReports
22+
* for more information.
23+
* Usage:
24+
* composer update
25+
* php run_batch_report.php YOUR-GA4-PROPERTY-ID
26+
*/
27+
28+
namespace Google\Cloud\Samples\Analytics\Data;
29+
30+
// [START analyticsdata_run_batch_report]
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\RunReportRequest;
37+
use Google\Analytics\Data\V1beta\RunReportResponse;
38+
39+
/**
40+
* Runs a batch report on a Google Analytics 4 property.
41+
* @param string $propertyId Your GA-4 Property ID
42+
*/
43+
function run_batch_report(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->batchRunReports([
50+
'property' => 'properties/' . $propertyId,
51+
'requests' => [
52+
new RunReportRequest([
53+
'dimensions' => [
54+
new Dimension(['name' => 'country']),
55+
new Dimension(['name' => 'region']),
56+
new Dimension(['name' => 'city']),
57+
],
58+
'metrics' => [new Metric(['name' => 'activeUsers'])],
59+
'date_ranges' => [new DateRange([
60+
'start_date' => '2021-01-03',
61+
'end_date' => '2021-01-09',
62+
]),
63+
],
64+
]),
65+
new RunReportRequest([
66+
'dimensions' => [new Dimension(['name' => 'browser'])],
67+
'metrics' => [new Metric(['name' => 'activeUsers'])],
68+
'date_ranges' => [new DateRange([
69+
'start_date' => '2021-01-01',
70+
'end_date' => '2021-01-31',
71+
]),
72+
],
73+
]),
74+
],
75+
]);
76+
77+
print 'Batch report results' . PHP_EOL;
78+
foreach ($response->getReports() as $report) {
79+
printBatchRunReportsResponse($report);
80+
}
81+
}
82+
83+
/**
84+
* Print results of a runReport call.
85+
* @param RunReportResponse $response
86+
*/
87+
function printBatchRunReportsResponse(RunReportResponse $response)
88+
{
89+
// [START analyticsdata_print_run_report_response_header]
90+
printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
91+
foreach ($response->getDimensionHeaders() as $dimensionHeader) {
92+
printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
93+
}
94+
foreach ($response->getMetricHeaders() as $metricHeader) {
95+
printf(
96+
'Metric header name: %s (%s)' . PHP_EOL,
97+
$metricHeader->getName(),
98+
MetricType::name($metricHeader->getType())
99+
);
100+
}
101+
// [END analyticsdata_print_run_report_response_header]
102+
103+
// [START analyticsdata_print_run_report_response_rows]
104+
print 'Report result: ' . PHP_EOL;
105+
106+
foreach ($response->getRows() as $row) {
107+
printf(
108+
'%s %s' . PHP_EOL,
109+
$row->getDimensionValues()[0]->getValue(),
110+
$row->getMetricValues()[0]->getValue()
111+
);
112+
}
113+
// [END analyticsdata_print_run_report_response_rows]
114+
}
115+
// [END analyticsdata_run_batch_report]
116+
117+
// The following 2 lines are only needed to run the samples
118+
require_once __DIR__ . '/../../testing/sample_helpers.php';
119+
return \Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
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 creation of
20+
* a pivot report.
21+
* See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runPivotReport
22+
* for more information.
23+
* Usage:
24+
* composer update
25+
* php run_pivot_report.php YOUR-GA4-PROPERTY-ID
26+
*/
27+
28+
namespace Google\Cloud\Samples\Analytics\Data;
29+
30+
// [START analyticsdata_run_pivot_report]
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\Pivot;
36+
use Google\Analytics\Data\V1beta\OrderBy;
37+
use Google\Analytics\Data\V1beta\OrderBy\DimensionOrderBy;
38+
use Google\Analytics\Data\V1beta\OrderBy\MetricOrderBy;
39+
use Google\Analytics\Data\V1beta\RunPivotReportResponse;
40+
41+
/**
42+
* Runs a pivot query to build a report of session counts by country,
43+
* pivoted by the browser dimension.
44+
* @param string $propertyId Your GA-4 Property ID
45+
*/
46+
function run_pivot_report(string $propertyId)
47+
{
48+
// Create an instance of the Google Analytics Data API client library.
49+
$client = new BetaAnalyticsDataClient();
50+
51+
// Make an API call.
52+
$response = $client->runPivotReport([
53+
'property' => 'properties/' . $propertyId,
54+
'dateRanges' => [new DateRange([
55+
'start_date' => '2021-01-01',
56+
'end_date' => '2021-01-30',
57+
]),
58+
],
59+
'pivots' => [
60+
new Pivot([
61+
'field_names' => ['country'],
62+
'limit' => 250,
63+
'order_bys' => [new OrderBy([
64+
'dimension' => new DimensionOrderBy([
65+
'dimension_name' => 'country',
66+
]),
67+
])],
68+
]),
69+
new Pivot([
70+
'field_names' => ['browser'],
71+
'offset' => 3,
72+
'limit' => 3,
73+
'order_bys' => [new OrderBy([
74+
'metric' => new MetricOrderBy([
75+
'metric_name' => 'sessions',
76+
]),
77+
'desc' => true,
78+
])],
79+
]),
80+
],
81+
'metrics' => [new Metric(['name' => 'sessions'])],
82+
'dimensions' => [
83+
new Dimension(['name' => 'country']),
84+
new Dimension(['name' => 'browser']),
85+
],
86+
]);
87+
88+
printPivotReportResponse($response);
89+
}
90+
91+
/**
92+
* Print results of a runPivotReport call.
93+
* @param RunPivotReportResponse $response
94+
*/
95+
function printPivotReportResponse(RunPivotReportResponse $response)
96+
{
97+
// [START analyticsdata_print_run_pivot_report_response]
98+
print 'Report result: ' . PHP_EOL;
99+
100+
foreach ($response->getRows() as $row) {
101+
printf(
102+
'%s %s' . PHP_EOL,
103+
$row->getDimensionValues()[0]->getValue(),
104+
$row->getMetricValues()[0]->getValue()
105+
);
106+
}
107+
// [END analyticsdata_print_run_pivot_report_response]
108+
}
109+
// [END analyticsdata_run_pivot_report]
110+
111+
// The following 2 lines are only needed to run the samples
112+
require_once __DIR__ . '/../../testing/sample_helpers.php';
113+
return \Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

analyticsdata/test/analyticsDataTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,23 @@ public function testClientFromJsonCredentials()
5151
}
5252
}
5353

54+
public function testRunBatchReport()
55+
{
56+
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
57+
$output = $this->runFunctionSnippet('run_batch_report', [$propertyId]);
58+
59+
$this->assertStringContainsString('Batch report result', $output);
60+
$this->assertStringContainsString('Report result', $output);
61+
}
62+
63+
public function testRunPivotReport()
64+
{
65+
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
66+
$output = $this->runFunctionSnippet('run_pivot_report', [$propertyId]);
67+
68+
$this->assertStringContainsString('Report result', $output);
69+
}
70+
5471
public function testRunReportWithDimensionExcludeFilter()
5572
{
5673
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');

0 commit comments

Comments
 (0)