Skip to content

Commit ac4efb8

Browse files
authored
feat(analyticsdata): adds sample for run_report with cohorts (GoogleCloudPlatform#1713)
1 parent a9beb04 commit ac4efb8

File tree

3 files changed

+134
-4
lines changed

3 files changed

+134
-4
lines changed

analyticsdata/src/run_report_with_aggregations.php

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,8 @@
4343
*/
4444
function run_report_with_aggregations(string $propertyId)
4545
{
46-
// [START analyticsdata_initialize]
4746
// Create an instance of the Google Analytics Data API client library.
4847
$client = new BetaAnalyticsDataClient();
49-
// [END analyticsdata_initialize]
5048

5149
// Make an API call.
5250
$response = $client->runReport([
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
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+
* cohort specification in a report.
21+
* See https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.cohort_spec
22+
* for more information.
23+
* Usage:
24+
* composer update
25+
* php run_report_with_cohorts.php YOUR-GA4-PROPERTY-ID
26+
*/
27+
28+
namespace Google\Cloud\Samples\Analytics\Data;
29+
30+
// [START analyticsdata_run_report_with_cohorts]
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\CohortSpec;
37+
use Google\Analytics\Data\V1beta\CohortsRange;
38+
use Google\Analytics\Data\V1beta\Cohort;
39+
use Google\Analytics\Data\V1beta\RunReportResponse;
40+
41+
/**
42+
* @param string $propertyID Your GA-4 Property ID
43+
* Runs a report on a cohort of users whose first session happened on the
44+
* same week. The number of active users and user retention rate is calculated
45+
* for the cohort using WEEKLY granularity.
46+
*/
47+
function run_report_with_cohorts(string $propertyId)
48+
{
49+
// Creates an instance of the Google Analytics Data API client library.
50+
$client = new BetaAnalyticsDataClient();
51+
52+
// Make an API call.
53+
$response = $client->runReport([
54+
'property' => 'properties/' . $propertyId,
55+
'dimensions' => [
56+
new Dimension(['name' => 'cohort']),
57+
new Dimension(['name' => 'cohortNthWeek']),
58+
],
59+
'metrics' => [
60+
new Metric(['name' => 'cohortActiveUsers']),
61+
new Metric([
62+
'name' => 'cohortRetentionRate',
63+
'expression' => 'cohortActiveUsers/cohortTotalUsers'
64+
])
65+
],
66+
'cohortSpec' => new CohortSpec([
67+
'cohorts' => [
68+
new Cohort([
69+
'dimension' => 'firstSessionDate',
70+
'name' => 'cohort',
71+
'date_range' => new DateRange([
72+
'start_date' => '2021-01-03',
73+
'end_date' => '2021-01-09',
74+
]),
75+
])
76+
],
77+
'cohorts_range' => new CohortsRange([
78+
'start_offset' => '0',
79+
'end_offset' => '4',
80+
'granularity' => '2',
81+
]),
82+
]),
83+
]);
84+
85+
printRunReportResponseWithCohorts($response);
86+
}
87+
88+
/**
89+
* Print results of a runReport call.
90+
* @param RunReportResponse $response
91+
*/
92+
function printRunReportResponseWithCohorts($response)
93+
{
94+
// [START analyticsdata_print_run_report_response_header]
95+
printf('%s rows received%s', $response->getRowCount(), PHP_EOL);
96+
foreach ($response->getDimensionHeaders() as $dimensionHeader) {
97+
printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL);
98+
}
99+
foreach ($response->getMetricHeaders() as $metricHeader) {
100+
printf(
101+
'Metric header name: %s (%s)' . PHP_EOL,
102+
$metricHeader->getName(),
103+
MetricType::name($metricHeader->getType())
104+
);
105+
}
106+
// [END analyticsdata_print_run_report_response_header]
107+
108+
// [START analyticsdata_print_run_report_response_rows]
109+
print 'Report result: ' . PHP_EOL;
110+
111+
foreach ($response->getRows() as $row) {
112+
printf(
113+
'%s %s' . PHP_EOL,
114+
$row->getDimensionValues()[0]->getValue(),
115+
$row->getMetricValues()[0]->getValue()
116+
);
117+
}
118+
// [END analyticsdata_print_run_report_response_rows]
119+
}
120+
// [END analyticsdata_run_report_with_cohorts]
121+
122+
// The following 2 lines are only needed to run the samples
123+
require_once __DIR__ . '/../../testing/sample_helpers.php';
124+
return \Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

analyticsdata/test/analyticsDataTest.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public function testRunReport()
3131
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
3232
$output = $this->runFunctionSnippet('run_report', [$propertyId]);
3333

34-
$this->assertRegExp('/Report result/', $output);
34+
$this->assertStringContainsString('Report result', $output);
3535
}
3636

3737
public function testClientFromJsonCredentials()
@@ -51,11 +51,19 @@ public function testClientFromJsonCredentials()
5151
}
5252
}
5353

54+
public function testRunReportWithCohorts()
55+
{
56+
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
57+
$output = $this->runFunctionSnippet('run_report_with_cohorts', [$propertyId]);
58+
59+
$this->assertStringContainsString('Report result', $output);
60+
}
61+
5462
public function testRunReportWithAggregations()
5563
{
5664
$propertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
5765
$output = $this->runFunctionSnippet('run_report_with_aggregations', [$propertyId]);
5866

59-
$this->assertRegExp('/Report result/', $output);
67+
$this->assertStringContainsString('Report result', $output);
6068
}
6169
}

0 commit comments

Comments
 (0)