Skip to content

Commit f7d8757

Browse files
committed
Add google-analytics-admin quickstart
1 parent c8e5b6b commit f7d8757

File tree

10 files changed

+324
-2
lines changed

10 files changed

+324
-2
lines changed

CONTRIBUTING.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ recommendations. This is enforced using [PHP CS Fixer][php-cs-fixer], using the
8181
Install that by running
8282

8383
```
84-
RUN composer require --dev friendsofphp/php-cs-fixer
84+
composer require --dev friendsofphp/php-cs-fixer
8585
```
8686

8787
Then to fix your directory or file run

google-analytics-admin/README.md

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Google Analytics Admin API Samples
2+
3+
[![Open in Cloud Shell][shell_img]][shell_link]
4+
5+
[shell_img]: http://gstatic.com/cloudssh/images/open-btn.svg
6+
[shell_link]: https://shell.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fgoogleanalytics%2Fphp-docs-samples
7+
8+
## Description
9+
10+
These samples show how to use the [Google Analytics Data API][analyticsdata-api]
11+
from PHP.
12+
13+
[analyticsadmin-api]: https://developers.google.com/analytics/devguides/config/admin/v1
14+
15+
## Build and Run
16+
1. **Enable APIs** - [Enable the Analytics Data API](https://console.cloud.google.com/flows/enableapi?apiid=analyticsadmin.googleapis.com)
17+
and create a new project or select an existing project.
18+
2. **Download The Credentials** - Configure your project using [Application Default Credentials][adc].
19+
Click "Go to credentials" after enabling the APIs. Click "Create Credentials"
20+
and select "Service Account Credentials" and download the credentials file. Then set the path to
21+
this file to the environment variable `GOOGLE_APPLICATION_CREDENTIALS`:
22+
```sh
23+
$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
24+
```
25+
3. **Clone the repo** and cd into this directory
26+
```sh
27+
$ git clone https://github.com/googleanalytics/php-docs-samples
28+
$ cd php-docs-samples/google-analytics-admin
29+
```
30+
4. **Install dependencies** via [Composer](http://getcomposer.org/doc/00-intro.md).
31+
Run `php composer.phar install` (if composer is installed locally) or `composer install`
32+
(if composer is installed globally).
33+
5. **Replace `$property_id` variable** if present in the snippet with the
34+
value of the Google Analytics 4 property id you want to access.
35+
6. **Run** with the command `php SNIPPET_NAME.php`. For example:
36+
```sh
37+
$ php quickstart.php
38+
```
39+
40+
## Contributing changes
41+
42+
* See [CONTRIBUTING.md](CONTRIBUTING.md)
43+
44+
## Licensing
45+
46+
* See [LICENSE](LICENSE)
47+
48+
[adc]: https://cloud.google.com/docs/authentication#adc

google-analytics-admin/composer.json

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"require": {
3+
"google/analytics-admin": "^0.20.0"
4+
},
5+
"require-dev": {
6+
"google/cloud-tools": "dev-main",
7+
"squizlabs/php_codesniffer": "^3.5",
8+
"phpunit/phpunit": "^9.0",
9+
"friendsofphp/php-cs-fixer": "^3.46"
10+
}
11+
}
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Copyright 2022 Google Inc.
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+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="./testing/bootstrap.php" colors="true" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
18+
<coverage>
19+
<include>
20+
<directory suffix=".php">./src</directory>
21+
</include>
22+
<exclude>
23+
<directory>./vendor</directory>
24+
</exclude>
25+
<report>
26+
<clover outputFile="build/logs/clover.xml"/>
27+
</report>
28+
</coverage>
29+
<testsuites>
30+
<testsuite name="Google Analytics Admin API Tests">
31+
<directory>test</directory>
32+
</testsuite>
33+
</testsuites>
34+
<php>
35+
<env name="PHPUNIT_TESTS" value="1"/>
36+
</php>
37+
</phpunit>

google-analytics-admin/quickstart.php

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php
2+
/**
3+
* Copyright 2021 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+
/* Google Analytics Admin API sample quickstart application.
19+
20+
This application demonstrates the usage of the Analytics Admin API to list
21+
all Google Analytics accounts available to the authenticated user, using
22+
service account credentials.
23+
24+
Before you start the application, please review the comments starting with
25+
"TODO(developer)" and update the code to use the correct values.
26+
27+
Usage:
28+
composer update
29+
php quickstart.php
30+
*/
31+
32+
// [START analytics_admin_quickstart]
33+
require 'vendor/autoload.php';
34+
35+
use Google\Analytics\Admin\V1beta\Account;
36+
use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient;
37+
use Google\Analytics\Admin\V1beta\ListAccountsRequest;
38+
39+
/**
40+
* TODO(developer): Replace this variable with your Google Analytics 4
41+
* property ID before running the sample.
42+
*/
43+
$property_id = 'YOUR-GA4-PROPERTY-ID';
44+
45+
// Using a default constructor instructs the client to use the credentials
46+
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
47+
// See https://cloud.google.com/docs/authentication/production for more information
48+
// about managing credentials.
49+
$client = new AnalyticsAdminServiceClient();
50+
51+
// Calls listAccounts() method of the Google Analytics Admin API and prints
52+
// the response for each account.
53+
$request = new ListAccountsRequest();
54+
$response = $client->listAccounts($request);
55+
56+
print 'Result:' . PHP_EOL;
57+
foreach($response->iterateAllElements() as $account) {
58+
print 'Account name: ' . $account->getName() . PHP_EOL;
59+
print 'Display name: ' . $account->getDisplayName() . PHP_EOL;
60+
print 'Country code: ' . $account->getRegionCode() . PHP_EOL;
61+
print 'Create time: ' . $account->getCreateTime()->getSeconds() . PHP_EOL;
62+
print 'Update time: ' . $account->getUpdateTime()->getSeconds() . PHP_EOL;
63+
}
64+
// [END analytics_admin_quickstart]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
/**
4+
* Copyright 2022 Google Inc.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
use Google\Cloud\TestUtils\TestTrait;
20+
use PHPUnit\Framework\TestCase;
21+
22+
class QuickstartTest extends TestCase
23+
{
24+
use TestTrait;
25+
26+
public function testQuickstart()
27+
{
28+
$testPropertyId = self::requireEnv('GA_TEST_PROPERTY_ID');
29+
$file = sys_get_temp_dir() . '/analyticsadmin_quickstart.php';
30+
$contents = file_get_contents(__DIR__ . '/../quickstart.php');
31+
$contents = str_replace(
32+
['YOUR-GA4-PROPERTY-ID', '__DIR__'],
33+
[$testPropertyId, sprintf('"%s/.."', __DIR__)],
34+
$contents
35+
);
36+
file_put_contents($file, $contents);
37+
38+
// Invoke quickstart.php
39+
$output = $this->runSnippet($file);
40+
41+
$this->assertStringContainsString('Result', $output);
42+
}
43+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
$testDir = getcwd();
4+
5+
if (!file_exists($testDir . '/phpunit.xml.dist')) {
6+
throw new Exception('You are not in a sample directory');
7+
}
8+
9+
if (file_exists($testDir . '/composer.json')) {
10+
if (!file_exists($testDir . '/vendor/autoload.php')) {
11+
throw new Exception('You need to run "composer install" in your current directory');
12+
}
13+
require_once $testDir . '/vendor/autoload.php';
14+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
require __DIR__ . '/vendor/autoload.php';
4+
5+
if (count($argv) != 2) {
6+
die('Usage: check_version.php CONSTRAINT' . PHP_EOL);
7+
}
8+
9+
if ('null' === $argv[1]) {
10+
// If there is no php constraint, it satisfies
11+
echo '0';
12+
return;
13+
}
14+
15+
echo Composer\Semver\Semver::satisfies(PHP_VERSION, $argv[1]) ? '0' : '1';
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<?php
2+
3+
namespace Google\Analytics\Admin\Samples;
4+
5+
use ReflectionFunction;
6+
7+
function execute_sample(string $file, string $namespace, ?array $argv)
8+
{
9+
// Return if sample file is not being executed via CLI
10+
if (is_null($argv)) {
11+
return;
12+
}
13+
14+
// Return if sample file is being included via PHPUnit
15+
$argvFile = array_shift($argv);
16+
if ('.php' != substr($argvFile, -4)) {
17+
return;
18+
}
19+
20+
// Determine the name of the function to execute
21+
$functionName = sprintf('%s\\%s', $namespace, basename($file, '.php'));
22+
23+
// Verify the user has supplied the correct number of arguments
24+
$functionReflection = new ReflectionFunction($functionName);
25+
if (
26+
count($argv) < $functionReflection->getNumberOfRequiredParameters()
27+
|| count($argv) > $functionReflection->getNumberOfParameters()
28+
) {
29+
print(get_usage(basename($file), $functionReflection));
30+
return;
31+
}
32+
33+
// Require composer autoload for the user
34+
$autoloadDir = dirname(dirname($functionReflection->getFileName()));
35+
if (!file_exists($autoloadFile = $autoloadDir . '/vendor/autoload.php')) {
36+
printf(
37+
'You must run "composer install" in the sample root (%s/)' . PHP_EOL,
38+
$autoloadDir
39+
);
40+
return;
41+
}
42+
require_once $autoloadFile;
43+
44+
// If any parameters are typehinted as "array", explode user input on ","
45+
$validArrayTypes = ['array', 'array<string>', 'string[]'];
46+
$parameterReflections = $functionReflection->getParameters();
47+
foreach (array_values($argv) as $i => $val) {
48+
$parameterReflection = $parameterReflections[$i];
49+
if ($parameterReflection->hasType()) {
50+
$parameterType = $parameterReflection->getType()->getName();
51+
if (in_array($parameterType, $validArrayTypes) && !is_array($val)) {
52+
$key = array_search($val, $argv);
53+
$argv[$key] = explode(',', $argv[$key]);
54+
}
55+
}
56+
}
57+
58+
// Run the function
59+
return call_user_func_array($functionName, $argv);
60+
}
61+
62+
function get_usage(string $file, ReflectionFunction $functionReflection)
63+
{
64+
// Print basic usage
65+
$paramNames = [];
66+
foreach ($functionReflection->getParameters() as $param) {
67+
$name = '$' . $param->getName();
68+
if ($param->isOptional()) {
69+
$default = var_export($param->getDefaultValue(), true);
70+
$name = "[$name=$default]";
71+
}
72+
$paramNames[] = $name;
73+
}
74+
$usage = sprintf('Usage: %s %s' . PHP_EOL, $file, implode(' ', $paramNames));
75+
76+
// Print @param docs if they exist
77+
preg_match_all(
78+
"#(@param+\s*[a-zA-Z0-9, ()_].*)#",
79+
$functionReflection->getDocComment(),
80+
$matches
81+
);
82+
if (isset($matches[0])) {
83+
$usage .= PHP_EOL . "\t";
84+
$usage .= implode(PHP_EOL . "\t", $matches[0]) . PHP_EOL;
85+
$usage .= PHP_EOL;
86+
}
87+
88+
return $usage;
89+
}

google-analytics-data/composer.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"require-dev": {
66
"google/cloud-tools": "dev-main",
77
"squizlabs/php_codesniffer": "^3.5",
8-
"phpunit/phpunit": "^9.0"
8+
"phpunit/phpunit": "^9.0",
9+
"friendsofphp/php-cs-fixer": "*"
910
}
1011
}

0 commit comments

Comments
 (0)