├── CODEOWNERS ├── google-analytics-data ├── quickstart_oauth2 │ ├── composer.json │ ├── README.md │ └── index.php ├── composer.json ├── testing │ ├── check_version.php │ ├── bootstrap.php │ └── sample_helpers.php ├── phpunit.xml.dist ├── test │ ├── quickstartTest.php │ └── analyticsDataTest.php ├── src │ ├── client_from_json_credentials.php │ ├── run_realtime_report.php │ ├── run_report.php │ ├── run_realtime_report_with_multiple_metrics.php │ ├── run_realtime_report_with_multiple_dimensions.php │ ├── run_report_with_multiple_metrics.php │ ├── run_report_with_date_ranges.php │ ├── run_report_with_multiple_dimensions.php │ ├── run_realtime_report_with_minute_ranges.php │ ├── run_report_with_named_date_ranges.php │ ├── run_report_with_aggregations.php │ ├── run_pivot_report.php │ ├── get_common_metadata.php │ ├── get_metadata_by_property_id.php │ ├── run_report_with_ordering.php │ ├── run_report_with_property_quota.php │ ├── run_report_with_dimension_filter.php │ ├── run_batch_report.php │ ├── run_report_with_dimension_exclude_filter.php │ ├── run_report_with_dimension_in_list_filter.php │ ├── run_report_with_cohorts.php │ ├── run_report_with_pagination.php │ ├── run_report_with_multiple_dimension_filters.php │ ├── run_report_with_dimension_and_metric_filters.php │ └── run_funnel_report.php ├── README.md └── quickstart.php ├── .gitignore ├── google-analytics-admin ├── composer.json ├── testing │ ├── check_version.php │ ├── bootstrap.php │ └── sample_helpers.php ├── test │ ├── analyticsAdminTest.php │ └── quickstartTest.php ├── phpunit.xml.dist ├── README.md ├── quickstart.php └── src │ └── properties_list.php ├── README.md ├── .github └── renovate.json5 ├── .php-cs-fixer.dist.php ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md └── LICENSE /CODEOWNERS: -------------------------------------------------------------------------------- 1 | @googleanalytics/google-analytics 2 | -------------------------------------------------------------------------------- /google-analytics-data/quickstart_oauth2/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": { 3 | "google/analytics-data": "^0.23.0", 4 | "ext-bcmath": "*" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *~ 3 | *.iml 4 | composer.phar 5 | composer.lock 6 | vendor/ 7 | credentials.* 8 | **/vendor/ 9 | **/build/ 10 | .php_cs.cache 11 | .php-cs-fixer.cache 12 | .vscode/ 13 | .kokoro/secrets.sh 14 | .phpunit.result.cache 15 | .DS_Store 16 | -------------------------------------------------------------------------------- /google-analytics-admin/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": { 3 | "php": ">=8.1", 4 | "google/analytics-admin": "^0.31.0" 5 | }, 6 | "require-dev": { 7 | "google/cloud-tools": "dev-main", 8 | "squizlabs/php_codesniffer": "^4.0", 9 | "phpunit/phpunit": "^10.0", 10 | "friendsofphp/php-cs-fixer": "^3.46" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /google-analytics-data/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": { 3 | "php": ">=8.1", 4 | "google/analytics-data": "^0.23.0" 5 | }, 6 | "require-dev": { 7 | "google/cloud-tools": "dev-main", 8 | "squizlabs/php_codesniffer": "^4.0", 9 | "phpunit/phpunit": "^10.0", 10 | "friendsofphp/php-cs-fixer": "^3.46" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /google-analytics-admin/testing/check_version.php: -------------------------------------------------------------------------------- 1 | runFunctionSnippet('properties_list', [$accountId]); 32 | 33 | $this->assertStringContainsString('Result:', $output); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /google-analytics-data/phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | ./src 21 | 22 | 23 | ./vendor 24 | 25 | 26 | 27 | 28 | test 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /google-analytics-admin/phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | ./src 21 | 22 | 23 | ./vendor 24 | 25 | 26 | 27 | 28 | test 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /google-analytics-admin/test/quickstartTest.php: -------------------------------------------------------------------------------- 1 | runSnippet($file); 40 | 41 | $this->assertStringContainsString('Result', $output); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /google-analytics-data/quickstart_oauth2/README.md: -------------------------------------------------------------------------------- 1 | This application demonstrates the usage of the Analytics Data API using 2 | OAuth2 credentials. 3 | 4 | Please familiarize yourself with the OAuth2 flow guide at 5 | https://developers.google.com/identity/protocols/oauth2 6 | 7 | For more information on authenticating as an end user, see 8 | https://cloud.google.com/docs/authentication/end-user 9 | 10 | In a nutshell, you need to: 11 | 12 | 1. Create your OAuth2 client credentials in Google Cloud Console. 13 | Choose "Web application" when asked for an application type. 14 | https://support.google.com/cloud/answer/6158849 15 | 16 | 2. When configuring the web application credentials, add 17 | "http://localhost:3000/" to "Authorized redirect URIs". 18 | 19 | 3. Download a credentials file using "Download JSON" button in the credentials 20 | configuration dialog and save it as `oauth2.keys.json` in the same 21 | directory with this sample app. 22 | 23 | 4. Replace `$property_id` variable with the value of the Google Analytics 4 24 | property id you want to access. 25 | 26 | 5. Install the PHP bcmath extension (due to https://github.com/protocolbuffers/protobuf/issues/4465): 27 | 28 | ``` 29 | sudo -s apt-get install php-bcmath 30 | ``` 31 | 32 | 6. Run the following commands from the current directory in order to install 33 | dependencies and run the sample app: 34 | 35 | ``` 36 | composer update 37 | php -S localhost:3000 -t . 38 | ``` 39 | 40 | 7. In a browser, open the following url to start the sample: 41 | 42 | http://localhost:3000/ 43 | -------------------------------------------------------------------------------- /google-analytics-data/test/quickstartTest.php: -------------------------------------------------------------------------------- 1 | runSnippet($file); 40 | 41 | $this->assertStringContainsString('Report result', $output); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.php-cs-fixer.dist.php: -------------------------------------------------------------------------------- 1 | setRules([ 8 | '@PSR2' => true, 9 | 'concat_space' => ['spacing' => 'one'], 10 | 'no_unused_imports' => true, 11 | 'whitespace_after_comma_in_array' => true, 12 | 'method_argument_space' => [ 13 | 'keep_multiple_spaces_after_comma' => true, 14 | 'on_multiline' => 'ignore' 15 | ], 16 | 'return_type_declaration' => [ 17 | 'space_before' => 'none' 18 | ], 19 | // only converts simple strings in double quotes to single quotes 20 | // ignores strings using variables, escape characters or single quotes inside 21 | 'single_quote' => true, 22 | // there should be a single space b/w the cast and it's operand 23 | 'cast_spaces' => ['space' => 'single'], 24 | // there shouldn't be any trailing whitespace at the end of a non-blank line 25 | 'no_trailing_whitespace' => true, 26 | // there shouldn't be any trailing whitespace at the end of a blank line 27 | 'no_whitespace_in_blank_line' => true, 28 | // there should be a space around binary operators like (=, => etc) 29 | 'binary_operator_spaces' => ['default' => 'single_space'], 30 | // deals with rogue empty blank lines 31 | 'no_extra_blank_lines' => ['tokens' => ['extra']], 32 | // reduces multi blank lines b/w phpdoc description and @param to a single line 33 | // NOTE: Doesn't add a blank line if none exist 34 | 'phpdoc_trim_consecutive_blank_line_separation' => true, 35 | ]) 36 | ->setFinder( 37 | PhpCsFixer\Finder::create() 38 | ->in(__DIR__) 39 | ) 40 | ; 41 | 42 | return $config; 43 | -------------------------------------------------------------------------------- /google-analytics-data/src/client_from_json_credentials.php: -------------------------------------------------------------------------------- 1 | $credentialsJsonPath 44 | ]); 45 | 46 | return $client; 47 | } 48 | // [END analyticsdata_json_credentials_initialize] 49 | 50 | // The following 2 lines are only needed to run the samples 51 | require_once __DIR__ . '/../testing/sample_helpers.php'; 52 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 53 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, 4 | and in the interest of fostering an open and welcoming community, 5 | we pledge to respect all people who contribute through reporting issues, 6 | posting feature requests, updating documentation, 7 | submitting pull requests or patches, and other activities. 8 | 9 | We are committed to making participation in this project 10 | a harassment-free experience for everyone, 11 | regardless of level of experience, gender, gender identity and expression, 12 | sexual orientation, disability, personal appearance, 13 | body size, race, ethnicity, age, religion, or nationality. 14 | 15 | Examples of unacceptable behavior by participants include: 16 | 17 | * The use of sexualized language or imagery 18 | * Personal attacks 19 | * Trolling or insulting/derogatory comments 20 | * Public or private harassment 21 | * Publishing other's private information, 22 | such as physical or electronic 23 | addresses, without explicit permission 24 | * Other unethical or unprofessional conduct. 25 | 26 | Project maintainers have the right and responsibility to remove, edit, or reject 27 | comments, commits, code, wiki edits, issues, and other contributions 28 | that are not aligned to this Code of Conduct. 29 | By adopting this Code of Conduct, 30 | project maintainers commit themselves to fairly and consistently 31 | applying these principles to every aspect of managing this project. 32 | Project maintainers who do not follow or enforce the Code of Conduct 33 | may be permanently removed from the project team. 34 | 35 | This code of conduct applies both within project spaces and in public spaces 36 | when an individual is representing the project or its community. 37 | 38 | Instances of abusive, harassing, or otherwise unacceptable behavior 39 | may be reported by opening an issue 40 | or contacting one or more of the project maintainers. 41 | 42 | This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, 43 | available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) 44 | -------------------------------------------------------------------------------- /google-analytics-data/README.md: -------------------------------------------------------------------------------- 1 | # Google Analytics Data 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 | [analyticsdata-api]: https://developers.google.com/analytics/devguides/reporting/data/v1 14 | 15 | ## Build and Run 16 | 1. **Enable APIs** - [Enable the Analytics Data API](https://console.cloud.google.com/flows/enableapi?apiid=analyticsdata.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-data 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 49 | -------------------------------------------------------------------------------- /google-analytics-admin/README.md: -------------------------------------------------------------------------------- 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 Admin API][analyticsadmin-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 Admin 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 49 | -------------------------------------------------------------------------------- /google-analytics-admin/quickstart.php: -------------------------------------------------------------------------------- 1 | listAccounts($request); 56 | 57 | print 'Result:' . PHP_EOL; 58 | foreach ($response->iterateAllElements() as $account) { 59 | print 'Account name: ' . $account->getName() . PHP_EOL; 60 | print 'Display name: ' . $account->getDisplayName() . PHP_EOL; 61 | print 'Country code: ' . $account->getRegionCode() . PHP_EOL; 62 | print 'Create time: ' . $account->getCreateTime()->getSeconds() . PHP_EOL; 63 | print 'Update time: ' . $account->getUpdateTime()->getSeconds() . PHP_EOL; 64 | } 65 | // [END analytics_admin_quickstart] 66 | -------------------------------------------------------------------------------- /google-analytics-admin/src/properties_list.php: -------------------------------------------------------------------------------- 1 | setFilter('parent:accounts/' . $accountId) 46 | ->setShowDeleted(true); 47 | $response = $client->listProperties($request); 48 | 49 | print 'Result:' . PHP_EOL; 50 | $i = 0; 51 | foreach ($response->iterateAllElements() as $property) { 52 | printf('Property #%d resource name: %s, parent: %s, display name: "%s", currency: %s, time zone: %s, create time: %s, update time: %s%s', 53 | $i++, 54 | $property->getName(), 55 | $property->getParent(), 56 | $property->getDisplayName(), 57 | $property->getCurrencyCode(), 58 | $property->getTimeZone(), 59 | $property->getCreateTime()->getSeconds(), 60 | $property->getUpdateTime()->getSeconds(), 61 | PHP_EOL, 62 | ); 63 | } 64 | } 65 | // [END analyticsadmin_properties_list] 66 | 67 | // The following 2 lines are only needed to run the samples 68 | require_once __DIR__ . '/../testing/sample_helpers.php'; 69 | return \Google\Analytics\Admin\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 70 | -------------------------------------------------------------------------------- /google-analytics-data/quickstart.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $property_id) 56 | ->setDateRanges([ 57 | new DateRange([ 58 | 'start_date' => '2020-03-31', 59 | 'end_date' => 'today', 60 | ]), 61 | ]) 62 | ->setDimensions([new Dimension([ 63 | 'name' => 'city', 64 | ]), 65 | ]) 66 | ->setMetrics([new Metric([ 67 | 'name' => 'activeUsers', 68 | ]) 69 | ]); 70 | $response = $client->runReport($request); 71 | // [END analyticsdata_run_report] 72 | 73 | // [START analyticsdata_run_report_response] 74 | // Print results of an API call. 75 | print 'Report result: ' . PHP_EOL; 76 | 77 | foreach ($response->getRows() as $row) { 78 | print $row->getDimensionValues()[0]->getValue() 79 | . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL; 80 | // [END analyticsdata_run_report_response] 81 | } 82 | // [END analytics_data_quickstart] 83 | -------------------------------------------------------------------------------- /google-analytics-admin/testing/sample_helpers.php: -------------------------------------------------------------------------------- 1 | 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[]']; 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 | } 90 | -------------------------------------------------------------------------------- /google-analytics-data/testing/sample_helpers.php: -------------------------------------------------------------------------------- 1 | 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[]']; 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 | } 90 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_realtime_report.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 51 | ->setDimensions([new Dimension(['name' => 'country'])]) 52 | ->setMetrics([new Metric(['name' => 'activeUsers'])]); 53 | $response = $client->runRealtimeReport($request); 54 | 55 | printRunRealtimeReportResponse($response); 56 | } 57 | 58 | /** 59 | * Print results of a runRealtimeReport call. 60 | * @param RunRealtimeReportResponse $response 61 | */ 62 | function printRunRealtimeReportResponse(RunRealtimeReportResponse $response) 63 | { 64 | // [START analyticsdata_print_run_realtime_report_response_header] 65 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 66 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 67 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 68 | } 69 | foreach ($response->getMetricHeaders() as $metricHeader) { 70 | printf( 71 | 'Metric header name: %s (%s)%s', 72 | $metricHeader->getName(), 73 | MetricType::name($metricHeader->getType()), 74 | PHP_EOL 75 | ); 76 | } 77 | // [END analyticsdata_print_run_realtime_report_response_header] 78 | 79 | // [START analyticsdata_print_run_realtime_report_response_rows] 80 | print 'Report result: ' . PHP_EOL; 81 | 82 | foreach ($response->getRows() as $row) { 83 | printf( 84 | '%s %s' . PHP_EOL, 85 | $row->getDimensionValues()[0]->getValue(), 86 | $row->getMetricValues()[0]->getValue() 87 | ); 88 | } 89 | // [END analyticsdata_print_run_realtime_report_response_rows] 90 | } 91 | // [END analyticsdata_run_realtime_report] 92 | 93 | // The following 2 lines are only needed to run the samples 94 | require_once __DIR__ . '/../testing/sample_helpers.php'; 95 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 96 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement 9 | (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you 12 | own the intellectual property, then you'll need to sign an 13 | [individual CLA](https://developers.google.com/open-source/cla/individual). 14 | * If you work for a company that wants to allow you to contribute your work, 15 | then you'll need to sign a 16 | [corporate CLA](https://developers.google.com/open-source/cla/corporate). 17 | 18 | Follow either of the two links above to access the appropriate CLA and 19 | instructions for how to sign and return it. Once we receive it, we'll be able to 20 | accept your pull requests. 21 | 22 | ## Contributing A Patch 23 | 24 | 1. Submit an issue describing your proposed change. 25 | 1. The repo owner will respond to your issue promptly. 26 | 1. If your proposed change is accepted, and you haven't already done so, sign a 27 | Contributor License Agreement (see details above). 28 | 1. Fork this repo, develop and test your code changes. 29 | 1. Ensure that your code adheres to the existing style in the sample to which 30 | you are contributing. 31 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 32 | 1. Submit a pull request. 33 | 34 | ## Writing a new sample 35 | 36 | Write samples according to the [sample style guide](https://googlecloudplatform.github.io/samples-style-guide/). 37 | 38 | ## Testing your code changes 39 | 40 | ### Install dependencies 41 | 42 | Change into the directory of the project you want to test (either 43 | `google-analytics-admin` or `google-analytics-data`), configure 44 | [Composer](http://getcomposer.org/doc/00-intro.md) and install dependencies as 45 | described in the directory's `README.md`. 46 | 47 | ### Environment variables 48 | Some tests require specific environment variables to run. PHPUnit will skip the tests 49 | if these environment variables are not found. Run `phpunit -v` for a message detailing 50 | which environment variables are missing. Then you can set those environment variables 51 | to run against any sample project as follows: 52 | 53 | ``` 54 | export GOOGLE_PROJECT_ID=YOUR_PROJECT_ID 55 | export GA_TEST_PROPERTY_ID=YOUR_GA4_PROPERTY_ID 56 | # This value is only required by Admin API samples tests. 57 | export GA_TEST_ACCOUNT_ID= 58 | ``` 59 | 60 | ### Run the tests 61 | 62 | Once the dependencies are installed and the environment variables set, you can run the 63 | tests in a samples directory. For example: 64 | 65 | ``` 66 | cd google-analytics-data 67 | # Execute the "phpunit" installed for the shared dependencies 68 | ./vendor/bin/phpunit 69 | ``` 70 | 71 | Use `phpunit -v` to get a more detailed output if there are errors. 72 | 73 | ## Style 74 | 75 | The [Google Cloud Samples Style Guide][style-guide] is considered the primary 76 | guidelines for all Google Cloud samples. 77 | 78 | [style-guide]: https://googlecloudplatform.github.io/samples-style-guide/ 79 | 80 | Samples in this repository also follow the [PSR2][psr2] and [PSR4][psr4] 81 | recommendations. This is enforced using [PHP CS Fixer][php-cs-fixer], using the config in [.php-cs-fixer.dist.php](.php-cs-fixer.dist.php) 82 | 83 | Install that by running 84 | 85 | ``` 86 | composer require --dev friendsofphp/php-cs-fixer 87 | ``` 88 | 89 | Then to fix your directory or file run 90 | 91 | ``` 92 | ./vendor/bin/php-cs-fixer fix --config .php-cs-fixer.dist.php . 93 | ./vendor/bin/php-cs-fixer fix --config .php-cs-fixer.dist.php path/to/file 94 | ``` 95 | 96 | [psr2]: http://www.php-fig.org/psr/psr-2/ 97 | [psr4]: http://www.php-fig.org/psr/psr-4/ 98 | [php-cs-fixer]: https://github.com/FriendsOfPHP/PHP-CS-Fixer 99 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 48 | ->setDateRanges([ 49 | new DateRange([ 50 | 'start_date' => '2020-09-01', 51 | 'end_date' => '2020-09-15', 52 | ]), 53 | ]) 54 | ->setDimensions([ 55 | new Dimension([ 56 | 'name' => 'country', 57 | ]), 58 | ]) 59 | ->setMetrics([ 60 | new Metric([ 61 | 'name' => 'activeUsers', 62 | ]), 63 | ]); 64 | $response = $client->runReport($request); 65 | 66 | printRunReportResponse($response); 67 | } 68 | 69 | /** 70 | * Print results of a runReport call. 71 | * @param RunReportResponse $response 72 | */ 73 | function printRunReportResponse(RunReportResponse $response) 74 | { 75 | // [START analyticsdata_print_run_report_response_header] 76 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 77 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 78 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 79 | } 80 | foreach ($response->getMetricHeaders() as $metricHeader) { 81 | printf( 82 | 'Metric header name: %s (%s)%s', 83 | $metricHeader->getName(), 84 | MetricType::name($metricHeader->getType()), 85 | PHP_EOL 86 | ); 87 | } 88 | // [END analyticsdata_print_run_report_response_header] 89 | 90 | // [START analyticsdata_print_run_report_response_rows] 91 | print 'Report result: ' . PHP_EOL; 92 | 93 | foreach ($response->getRows() as $row) { 94 | print $row->getDimensionValues()[0]->getValue() 95 | . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL; 96 | } 97 | // [END analyticsdata_print_run_report_response_rows] 98 | } 99 | // [END analyticsdata_run_report] 100 | 101 | // The following 2 lines are only needed to run the samples 102 | require_once __DIR__ . '/../testing/sample_helpers.php'; 103 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 104 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_realtime_report_with_multiple_metrics.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 51 | ->setDimensions([new Dimension(['name' => 'unifiedScreenName'])]) 52 | ->setMetrics([ 53 | new Metric(['name' => 'screenPageViews']), 54 | new Metric(['name' => 'keyEvents']), 55 | ]); 56 | $response = $client->runRealtimeReport($request); 57 | 58 | printRunRealtimeReportWithMultipleMetricsResponse($response); 59 | } 60 | 61 | /** 62 | * Print results of a runRealtimeReport call. 63 | * @param RunRealtimeReportResponse $response 64 | */ 65 | function printRunRealtimeReportWithMultipleMetricsResponse(RunRealtimeReportResponse $response) 66 | { 67 | // [START analyticsdata_print_run_realtime_report_response_header] 68 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 69 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 70 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 71 | } 72 | foreach ($response->getMetricHeaders() as $metricHeader) { 73 | printf( 74 | 'Metric header name: %s (%s)%s', 75 | $metricHeader->getName(), 76 | MetricType::name($metricHeader->getType()), 77 | PHP_EOL 78 | ); 79 | } 80 | // [END analyticsdata_print_run_realtime_report_response_header] 81 | 82 | // [START analyticsdata_print_run_realtime_report_response_rows] 83 | print 'Report result: ' . PHP_EOL; 84 | 85 | foreach ($response->getRows() as $row) { 86 | printf( 87 | '%s %s' . PHP_EOL, 88 | $row->getDimensionValues()[0]->getValue(), 89 | $row->getMetricValues()[0]->getValue() 90 | ); 91 | } 92 | // [END analyticsdata_print_run_realtime_report_response_rows] 93 | } 94 | // [END analyticsdata_run_realtime_report_with_multiple_metrics] 95 | 96 | // The following 2 lines are only needed to run the samples 97 | require_once __DIR__ . '/../testing/sample_helpers.php'; 98 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 99 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_realtime_report_with_multiple_dimensions.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 51 | ->setDimensions([ 52 | new Dimension(['name' => 'country']), 53 | new Dimension(['name' => 'city']), 54 | ]) 55 | ->setMetrics([new Metric(['name' => 'activeUsers'])]); 56 | $response = $client->runRealtimeReport($request); 57 | 58 | printRunRealtimeReportWithMultipleDimensionsResponse($response); 59 | } 60 | 61 | /** 62 | * Print results of a runRealtimeReport call. 63 | * @param RunRealtimeReportResponse $response 64 | */ 65 | function printRunRealtimeReportWithMultipleDimensionsResponse(RunRealtimeReportResponse $response) 66 | { 67 | // [START analyticsdata_print_run_realtime_report_response_header] 68 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 69 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 70 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 71 | } 72 | foreach ($response->getMetricHeaders() as $metricHeader) { 73 | printf( 74 | 'Metric header name: %s (%s)%s', 75 | $metricHeader->getName(), 76 | MetricType::name($metricHeader->getType()), 77 | PHP_EOL 78 | ); 79 | } 80 | // [END analyticsdata_print_run_realtime_report_response_header] 81 | 82 | // [START analyticsdata_print_run_realtime_report_response_rows] 83 | print 'Report result: ' . PHP_EOL; 84 | 85 | foreach ($response->getRows() as $row) { 86 | printf( 87 | '%s %s' . PHP_EOL, 88 | $row->getDimensionValues()[0]->getValue(), 89 | $row->getMetricValues()[0]->getValue() 90 | ); 91 | } 92 | // [END analyticsdata_print_run_realtime_report_response_rows] 93 | } 94 | // [END analyticsdata_run_realtime_report_with_multiple_dimensions] 95 | 96 | // The following 2 lines are only needed to run the samples 97 | require_once __DIR__ . '/../testing/sample_helpers.php'; 98 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 99 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_multiple_metrics.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 52 | ->setDimensions([new Dimension(['name' => 'date'])]) 53 | ->setMetrics([ 54 | new Metric(['name' => 'activeUsers']), 55 | new Metric(['name' => 'newUsers']), 56 | new Metric(['name' => 'totalRevenue']) 57 | ]) 58 | ->setDateRanges([ 59 | new DateRange([ 60 | 'start_date' => '7daysAgo', 61 | 'end_date' => 'today', 62 | ]) 63 | ]); 64 | $response = $client->runReport($request); 65 | 66 | printRunReportResponseWithMultipleMetrics($response); 67 | } 68 | 69 | /** 70 | * Print results of a runReport call. 71 | * @param RunReportResponse $response 72 | */ 73 | function printRunReportResponseWithMultipleMetrics(RunReportResponse $response) 74 | { 75 | // [START analyticsdata_print_run_report_response_header] 76 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 77 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 78 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 79 | } 80 | foreach ($response->getMetricHeaders() as $metricHeader) { 81 | printf( 82 | 'Metric header name: %s (%s)' . PHP_EOL, 83 | $metricHeader->getName(), 84 | MetricType::name($metricHeader->getType()) 85 | ); 86 | } 87 | // [END analyticsdata_print_run_report_response_header] 88 | 89 | // [START analyticsdata_print_run_report_response_rows] 90 | print 'Report result: ' . PHP_EOL; 91 | 92 | foreach ($response->getRows() as $row) { 93 | printf( 94 | '%s %s' . PHP_EOL, 95 | $row->getDimensionValues()[0]->getValue(), 96 | $row->getMetricValues()[0]->getValue() 97 | ); 98 | } 99 | // [END analyticsdata_print_run_report_response_rows] 100 | } 101 | // [END analyticsdata_run_report_with_multiple_metrics] 102 | 103 | // The following 2 lines are only needed to run the samples 104 | require_once __DIR__ . '/../testing/sample_helpers.php'; 105 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 106 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_date_ranges.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 52 | ->setDateRanges([ 53 | new DateRange([ 54 | 'start_date' => '2019-08-01', 55 | 'end_date' => '2019-08-14', 56 | ]), 57 | new DateRange([ 58 | 'start_date' => '2020-08-01', 59 | 'end_date' => '2020-08-14', 60 | ]), 61 | ]) 62 | ->setDimensions([new Dimension(['name' => 'platform'])]) 63 | ->setMetrics([new Metric(['name' => 'activeUsers'])]); 64 | $response = $client->runReport($request); 65 | 66 | printRunReportResponseWithDateRanges($response); 67 | } 68 | 69 | /** 70 | * Print results of a runReport call. 71 | * @param RunReportResponse $response 72 | */ 73 | function printRunReportResponseWithDateRanges(RunReportResponse $response) 74 | { 75 | // [START analyticsdata_print_run_report_response_header] 76 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 77 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 78 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 79 | } 80 | foreach ($response->getMetricHeaders() as $metricHeader) { 81 | printf( 82 | 'Metric header name: %s (%s)' . PHP_EOL, 83 | $metricHeader->getName(), 84 | MetricType::name($metricHeader->getType()) 85 | ); 86 | } 87 | // [END analyticsdata_print_run_report_response_header] 88 | 89 | // [START analyticsdata_print_run_report_response_rows] 90 | print 'Report result: ' . PHP_EOL; 91 | 92 | foreach ($response->getRows() as $row) { 93 | printf( 94 | '%s %s' . PHP_EOL, 95 | $row->getDimensionValues()[0]->getValue(), 96 | $row->getMetricValues()[0]->getValue() 97 | ); 98 | } 99 | // [END analyticsdata_print_run_report_response_rows] 100 | } 101 | // [END analyticsdata_run_report_with_date_ranges] 102 | 103 | // The following 2 lines are only needed to run the samples 104 | require_once __DIR__ . '/../testing/sample_helpers.php'; 105 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 106 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_multiple_dimensions.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 52 | ->setDimensions([ 53 | new Dimension(['name' => 'country']), 54 | new Dimension(['name' => 'region']), 55 | new Dimension(['name' => 'city']), 56 | ]) 57 | ->setMetrics([new Metric(['name' => 'activeUsers'])]) 58 | ->setDateRanges([ 59 | new DateRange([ 60 | 'start_date' => '7daysAgo', 61 | 'end_date' => 'today', 62 | ]) 63 | ]); 64 | $response = $client->runReport($request); 65 | 66 | printRunReportResponseWithMultipleDimensions($response); 67 | } 68 | 69 | /** 70 | * Print results of a runReport call. 71 | * @param RunReportResponse $response 72 | */ 73 | function printRunReportResponseWithMultipleDimensions(RunReportResponse $response) 74 | { 75 | // [START analyticsdata_print_run_report_response_header] 76 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 77 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 78 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 79 | } 80 | foreach ($response->getMetricHeaders() as $metricHeader) { 81 | printf( 82 | 'Metric header name: %s (%s)' . PHP_EOL, 83 | $metricHeader->getName(), 84 | MetricType::name($metricHeader->getType()) 85 | ); 86 | } 87 | // [END analyticsdata_print_run_report_response_header] 88 | 89 | // [START analyticsdata_print_run_report_response_rows] 90 | print 'Report result: ' . PHP_EOL; 91 | 92 | foreach ($response->getRows() as $row) { 93 | printf( 94 | '%s %s' . PHP_EOL, 95 | $row->getDimensionValues()[0]->getValue(), 96 | $row->getMetricValues()[0]->getValue() 97 | ); 98 | } 99 | // [END analyticsdata_print_run_report_response_rows] 100 | } 101 | // [END analyticsdata_run_report_with_multiple_dimensions] 102 | 103 | // The following 2 lines are only needed to run the samples 104 | require_once __DIR__ . '/../testing/sample_helpers.php'; 105 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 106 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_realtime_report_with_minute_ranges.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 57 | ->setMetrics([ 58 | new Metric(['name' => 'activeUsers']), 59 | ]) 60 | ->setMinuteRanges([ 61 | new MinuteRange(['name' => '0-4 minutes ago', 'start_minutes_ago' => 4]), 62 | new MinuteRange(['name' => '25-29 minutes ago', 'start_minutes_ago' => 29, 'end_minutes_ago' => 25]), 63 | ]); 64 | $response = $client->runRealtimeReport($request); 65 | 66 | printRunRealtimeReportWithMinuteRangesResponse($response); 67 | } 68 | 69 | /** 70 | * Print results of a runRealtimeReport call. 71 | * @param RunRealtimeReportResponse $response 72 | */ 73 | function printRunRealtimeReportWithMinuteRangesResponse(RunRealtimeReportResponse $response) 74 | { 75 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 76 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 77 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 78 | } 79 | foreach ($response->getMetricHeaders() as $metricHeader) { 80 | printf( 81 | 'Metric header name: %s (%s)%s', 82 | $metricHeader->getName(), 83 | MetricType::name($metricHeader->getType()), 84 | PHP_EOL 85 | ); 86 | } 87 | 88 | print 'Report result: ' . PHP_EOL; 89 | foreach ($response->getRows() as $row) { 90 | printf( 91 | '%s %s' . PHP_EOL, 92 | $row->getDimensionValues()[0]->getValue(), 93 | $row->getMetricValues()[0]->getValue() 94 | ); 95 | } 96 | } 97 | // [END analyticsdata_run_realtime_report_with_minute_ranges] 98 | 99 | // The following 2 lines are only needed to run the samples 100 | require_once __DIR__ . '/../testing/sample_helpers.php'; 101 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 102 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_named_date_ranges.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 52 | ->setDateRanges([ 53 | new DateRange([ 54 | 'start_date' => '2020-01-01', 55 | 'end_date' => '2020-01-31', 56 | 'name' => 'year_ago', 57 | ]), 58 | new DateRange([ 59 | 'start_date' => '2021-01-01', 60 | 'end_date' => '2021-01-31', 61 | 'name' => 'current_year', 62 | ]), 63 | ]) 64 | ->setDimensions([new Dimension(['name' => 'country'])]) 65 | ->setMetrics([new Metric(['name' => 'sessions'])]); 66 | $response = $client->runReport($request); 67 | 68 | printRunReportResponseWithNamedDateRanges($response); 69 | } 70 | 71 | /** 72 | * Print results of a runReport call. 73 | * @param RunReportResponse $response 74 | */ 75 | function printRunReportResponseWithNamedDateRanges(RunReportResponse $response) 76 | { 77 | // [START analyticsdata_print_run_report_response_header] 78 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 79 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 80 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 81 | } 82 | foreach ($response->getMetricHeaders() as $metricHeader) { 83 | printf( 84 | 'Metric header name: %s (%s)' . PHP_EOL, 85 | $metricHeader->getName(), 86 | MetricType::name($metricHeader->getType()) 87 | ); 88 | } 89 | // [END analyticsdata_print_run_report_response_header] 90 | 91 | // [START analyticsdata_print_run_report_response_rows] 92 | print 'Report result: ' . PHP_EOL; 93 | 94 | foreach ($response->getRows() as $row) { 95 | printf( 96 | '%s %s' . PHP_EOL, 97 | $row->getDimensionValues()[0]->getValue(), 98 | $row->getMetricValues()[0]->getValue() 99 | ); 100 | } 101 | // [END analyticsdata_print_run_report_response_rows] 102 | } 103 | // [END analyticsdata_run_report_with_named_date_ranges] 104 | 105 | // The following 2 lines are only needed to run the samples 106 | require_once __DIR__ . '/../testing/sample_helpers.php'; 107 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 108 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_aggregations.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 54 | ->setDimensions([new Dimension(['name' => 'country'])]) 55 | ->setMetrics([new Metric(['name' => 'sessions'])]) 56 | ->setDateRanges([ 57 | new DateRange([ 58 | 'start_date' => '365daysAgo', 59 | 'end_date' => 'today', 60 | ]), 61 | ]) 62 | ->setMetricAggregations([ 63 | MetricAggregation::TOTAL, 64 | MetricAggregation::MAXIMUM, 65 | MetricAggregation::MINIMUM 66 | ]); 67 | $response = $client->runReport($request); 68 | 69 | printRunReportResponseWithAggregations($response); 70 | } 71 | 72 | /** 73 | * Print results of a runReport call. 74 | * @param RunReportResponse $response 75 | */ 76 | function printRunReportResponseWithAggregations($response) 77 | { 78 | // [START analyticsdata_print_run_report_response_header] 79 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 80 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 81 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 82 | } 83 | foreach ($response->getMetricHeaders() as $metricHeader) { 84 | printf( 85 | 'Metric header name: %s (%s)' . PHP_EOL, 86 | $metricHeader->getName(), 87 | MetricType::name($metricHeader->getType()) 88 | ); 89 | } 90 | // [END analyticsdata_print_run_report_response_header] 91 | 92 | // [START analyticsdata_print_run_report_response_rows] 93 | print 'Report result: ' . PHP_EOL; 94 | 95 | foreach ($response->getRows() as $row) { 96 | printf( 97 | '%s %s' . PHP_EOL, 98 | $row->getDimensionValues()[0]->getValue(), 99 | $row->getMetricValues()[0]->getValue() 100 | ); 101 | } 102 | // [END analyticsdata_print_run_report_response_rows] 103 | } 104 | // [END analyticsdata_run_report_with_aggregations] 105 | 106 | // The following 2 lines are only needed to run the samples 107 | require_once __DIR__ . '/../testing/sample_helpers.php'; 108 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 109 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_pivot_report.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 56 | ->setDateRanges([new DateRange([ 57 | 'start_date' => '2021-01-01', 58 | 'end_date' => '2021-01-30', 59 | ]), 60 | ]) 61 | ->setPivots([ 62 | new Pivot([ 63 | 'field_names' => ['country'], 64 | 'limit' => 250, 65 | 'order_bys' => [new OrderBy([ 66 | 'dimension' => new DimensionOrderBy([ 67 | 'dimension_name' => 'country', 68 | ]), 69 | ])], 70 | ]), 71 | new Pivot([ 72 | 'field_names' => ['browser'], 73 | 'offset' => 3, 74 | 'limit' => 3, 75 | 'order_bys' => [new OrderBy([ 76 | 'metric' => new MetricOrderBy([ 77 | 'metric_name' => 'sessions', 78 | ]), 79 | 'desc' => true, 80 | ])], 81 | ]), 82 | ]) 83 | ->setMetrics([new Metric(['name' => 'sessions'])]) 84 | ->setDimensions([ 85 | new Dimension(['name' => 'country']), 86 | new Dimension(['name' => 'browser']), 87 | ]); 88 | $response = $client->runPivotReport($request); 89 | 90 | printPivotReportResponse($response); 91 | } 92 | 93 | /** 94 | * Print results of a runPivotReport call. 95 | * @param RunPivotReportResponse $response 96 | */ 97 | function printPivotReportResponse(RunPivotReportResponse $response) 98 | { 99 | // [START analyticsdata_print_run_pivot_report_response] 100 | print 'Report result: ' . PHP_EOL; 101 | 102 | foreach ($response->getRows() as $row) { 103 | printf( 104 | '%s %s' . PHP_EOL, 105 | $row->getDimensionValues()[0]->getValue(), 106 | $row->getMetricValues()[0]->getValue() 107 | ); 108 | } 109 | // [END analyticsdata_print_run_pivot_report_response] 110 | } 111 | // [END analyticsdata_run_pivot_report] 112 | 113 | // The following 2 lines are only needed to run the samples 114 | require_once __DIR__ . '/../testing/sample_helpers.php'; 115 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 116 | -------------------------------------------------------------------------------- /google-analytics-data/quickstart_oauth2/index.php: -------------------------------------------------------------------------------- 1 | 'https://www.googleapis.com/auth/analytics.readonly', 43 | 'tokenCredentialUri' => 'https://oauth2.googleapis.com/token', 44 | 'authorizationUri' => $keys->{'web'}->{'auth_uri'}, 45 | 'clientId' => $keys->{'web'}->{'client_id'}, 46 | 'clientSecret' => $keys->{'web'}->{'client_secret'}, 47 | 'redirectUri' => 'http://' . $_SERVER['HTTP_HOST'] . '/', 48 | ]); 49 | 50 | if (isset($_SESSION['access_token']) && $_SESSION['access_token'] 51 | && isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) { 52 | // This is the final step of the OAuth2 authorization process, where an 53 | // OAuth2 access token is available and can be used to set up a client. 54 | $oauth->setAccessToken($_SESSION['access_token']); 55 | $oauth->setRefreshToken($_SESSION['refresh_token']); 56 | 57 | try { 58 | // Make an API call. 59 | $client = new BetaAnalyticsDataClient(['credentials' => $oauth]); 60 | $request = (new RunReportRequest()) 61 | ->setProperty('properties/' . $property_id) 62 | ->setDateRanges([ 63 | new DateRange([ 64 | 'start_date' => '2020-03-31', 65 | 'end_date' => 'today', 66 | ]), 67 | ]) 68 | ->setDimensions([new Dimension([ 69 | 'name' => 'city', 70 | ]), 71 | ]) 72 | ->setMetrics([new Metric([ 73 | 'name' => 'activeUsers', 74 | ]) 75 | ]); 76 | $response = $client->runReport($request); 77 | 78 | // Print results of an API call. 79 | print 'Report result:
'; 80 | 81 | foreach ($response->getRows() as $row) { 82 | print $row->getDimensionValues()[0]->getValue() 83 | . ' ' . $row->getMetricValues()[0]->getValue() . '
'; 84 | } 85 | } catch (ApiException $e) { 86 | // Print an error message. 87 | print $e->getMessage(); 88 | } 89 | } elseif (isset($_GET['code']) && $_GET['code']) { 90 | // If an OAuth2 authorization code is present in the URL, exchange it for 91 | // an access token. 92 | $oauth->setCode($_GET['code']); 93 | $oauth->fetchAuthToken(); 94 | 95 | // Persist the acquired access token in a session. 96 | $_SESSION['access_token'] = $oauth->getAccessToken(); 97 | 98 | // Persist the acquired refresh token in a session. 99 | $_SESSION['refresh_token'] = $oauth->getRefreshToken(); 100 | 101 | // Refresh the current page. 102 | $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/'; 103 | header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 104 | } else { 105 | // Redirect to Google's OAuth 2.0 server. 106 | $auth_url = $oauth->buildFullAuthorizationUri(); 107 | header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); 108 | } 109 | // [END analyticsdata_quickstart_oauth2] 110 | -------------------------------------------------------------------------------- /google-analytics-data/src/get_common_metadata.php: -------------------------------------------------------------------------------- 1 | setName($formattedName); 57 | $response = $client->getMetadata($request); 58 | } catch (ApiException $ex) { 59 | printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); 60 | } 61 | 62 | print('Dimensions and metrics available for all Google Analytics 4 properties:'); 63 | printGetCommonMetadata($response); 64 | } 65 | 66 | /** 67 | * Print results of a getMetadata call. 68 | * @param Metadata $response 69 | */ 70 | function printGetCommonMetadata(Metadata $response) 71 | { 72 | // [START analyticsdata_print_get_metadata_response] 73 | foreach ($response->getDimensions() as $dimension) { 74 | print('DIMENSION' . PHP_EOL); 75 | printf( 76 | '%s (%s): %s' . PHP_EOL, 77 | $dimension->getApiName(), 78 | $dimension->getUiName(), 79 | $dimension->getDescription(), 80 | ); 81 | printf( 82 | 'custom definition: %s' . PHP_EOL, 83 | $dimension->getCustomDefinition() ? 'true' : 'false' 84 | ); 85 | if ($dimension->getDeprecatedApiNames()->count() > 0) { 86 | print('Deprecated API names: '); 87 | foreach ($dimension->getDeprecatedApiNames() as $name) { 88 | print($name . ','); 89 | } 90 | print(PHP_EOL); 91 | } 92 | print(PHP_EOL); 93 | } 94 | 95 | foreach ($response->getMetrics() as $metric) { 96 | print('METRIC' . PHP_EOL); 97 | printf( 98 | '%s (%s): %s' . PHP_EOL, 99 | $metric->getApiName(), 100 | $metric->getUiName(), 101 | $metric->getDescription(), 102 | ); 103 | printf( 104 | 'custom definition: %s' . PHP_EOL, 105 | $metric->getCustomDefinition() ? 'true' : 'false' 106 | ); 107 | if ($metric->getDeprecatedApiNames()->count() > 0) { 108 | print('Deprecated API names: '); 109 | foreach ($metric->getDeprecatedApiNames() as $name) { 110 | print($name . ','); 111 | } 112 | print(PHP_EOL); 113 | } 114 | print(PHP_EOL); 115 | } 116 | // [END analyticsdata_print_get_metadata_response] 117 | } 118 | // [END analyticsdata_get_common_metadata] 119 | 120 | // The following 2 lines are only needed to run the samples 121 | require_once __DIR__ . '/../testing/sample_helpers.php'; 122 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 123 | -------------------------------------------------------------------------------- /google-analytics-data/src/get_metadata_by_property_id.php: -------------------------------------------------------------------------------- 1 | setName($formattedName); 53 | $response = $client->getMetadata($request); 54 | } catch (ApiException $ex) { 55 | printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); 56 | } 57 | 58 | printf( 59 | 'Dimensions and metrics available for Google Analytics 4 property' 60 | . ' %s (including custom fields):' . PHP_EOL, 61 | $propertyId 62 | ); 63 | printGetMetadataByPropertyId($response); 64 | } 65 | 66 | /** 67 | * Print results of a getMetadata call. 68 | * @param Metadata $response 69 | */ 70 | function printGetMetadataByPropertyId(Metadata $response) 71 | { 72 | // [START analyticsdata_print_get_metadata_response] 73 | foreach ($response->getDimensions() as $dimension) { 74 | print('DIMENSION' . PHP_EOL); 75 | printf( 76 | '%s (%s): %s' . PHP_EOL, 77 | $dimension->getApiName(), 78 | $dimension->getUiName(), 79 | $dimension->getDescription(), 80 | ); 81 | printf( 82 | 'custom definition: %s' . PHP_EOL, 83 | $dimension->getCustomDefinition() ? 'true' : 'false' 84 | ); 85 | if ($dimension->getDeprecatedApiNames()->count() > 0) { 86 | print('Deprecated API names: '); 87 | foreach ($dimension->getDeprecatedApiNames() as $name) { 88 | print($name . ','); 89 | } 90 | print(PHP_EOL); 91 | } 92 | print(PHP_EOL); 93 | } 94 | 95 | foreach ($response->getMetrics() as $metric) { 96 | print('METRIC' . PHP_EOL); 97 | printf( 98 | '%s (%s): %s' . PHP_EOL, 99 | $metric->getApiName(), 100 | $metric->getUiName(), 101 | $metric->getDescription(), 102 | ); 103 | printf( 104 | 'custom definition: %s' . PHP_EOL, 105 | $metric->getCustomDefinition() ? 'true' : 'false' 106 | ); 107 | if ($metric->getDeprecatedApiNames()->count() > 0) { 108 | print('Deprecated API names: '); 109 | foreach ($metric->getDeprecatedApiNames() as $name) { 110 | print($name . ','); 111 | } 112 | print(PHP_EOL); 113 | } 114 | print(PHP_EOL); 115 | } 116 | // [END analyticsdata_print_get_metadata_response] 117 | } 118 | // [END analyticsdata_get_metadata_by_property_id] 119 | 120 | // The following 2 lines are only needed to run the samples 121 | require_once __DIR__ . '/../testing/sample_helpers.php'; 122 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 123 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_ordering.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 55 | ->setDimensions([new Dimension(['name' => 'date'])]) 56 | ->setMetrics([ 57 | new Metric(['name' => 'activeUsers']), 58 | new Metric(['name' => 'newUsers']), 59 | new Metric(['name' => 'totalRevenue']), 60 | ]) 61 | ->setDateRanges([ 62 | new DateRange([ 63 | 'start_date' => '7daysAgo', 64 | 'end_date' => 'today', 65 | ]), 66 | ]) 67 | ->setOrderBys([ 68 | new OrderBy([ 69 | 'metric' => new MetricOrderBy([ 70 | 'metric_name' => 'totalRevenue', 71 | ]), 72 | 'desc' => true, 73 | ]), 74 | ]); 75 | $response = $client->runReport($request); 76 | 77 | printRunReportResponseWithOrdering($response); 78 | } 79 | 80 | /** 81 | * Print results of a runReport call. 82 | * @param RunReportResponse $response 83 | */ 84 | function printRunReportResponseWithOrdering(RunReportResponse $response) 85 | { 86 | // [START analyticsdata_print_run_report_response_header] 87 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 88 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 89 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 90 | } 91 | foreach ($response->getMetricHeaders() as $metricHeader) { 92 | printf( 93 | 'Metric header name: %s (%s)' . PHP_EOL, 94 | $metricHeader->getName(), 95 | MetricType::name($metricHeader->getType()) 96 | ); 97 | } 98 | // [END analyticsdata_print_run_report_response_header] 99 | 100 | // [START analyticsdata_print_run_report_response_rows] 101 | print 'Report result: ' . PHP_EOL; 102 | 103 | foreach ($response->getRows() as $row) { 104 | printf( 105 | '%s %s' . PHP_EOL, 106 | $row->getDimensionValues()[0]->getValue(), 107 | $row->getMetricValues()[0]->getValue() 108 | ); 109 | } 110 | // [END analyticsdata_print_run_report_response_rows] 111 | } 112 | // [END analyticsdata_run_report_with_ordering] 113 | 114 | // The following 2 lines are only needed to run the samples 115 | require_once __DIR__ . '/../testing/sample_helpers.php'; 116 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 117 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_property_quota.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 51 | ->setReturnPropertyQuota(true) 52 | ->setDimensions([new Dimension(['name' => 'country'])]) 53 | ->setMetrics([new Metric(['name' => 'activeUsers'])]) 54 | ->setDateRanges([ 55 | new DateRange([ 56 | 'start_date' => '7daysAgo', 57 | 'end_date' => 'today', 58 | ]), 59 | ]); 60 | $response = $client->runReport($request); 61 | 62 | printRunReportResponseWithPropertyQuota($response); 63 | } 64 | 65 | /** 66 | * Print results of a runReport call. 67 | * @param RunReportResponse $response 68 | */ 69 | function printRunReportResponseWithPropertyQuota(RunReportResponse $response) 70 | { 71 | // [START analyticsdata_run_report_with_property_quota_print_response] 72 | if ($response->hasPropertyQuota()) { 73 | $propertyQuota = $response->getPropertyQuota(); 74 | $tokensPerDay = $propertyQuota->getTokensPerDay(); 75 | $tokensPerHour = $propertyQuota->getTokensPerHour(); 76 | $concurrentRequests = $propertyQuota->getConcurrentRequests(); 77 | $serverErrors = $propertyQuota->getServerErrorsPerProjectPerHour(); 78 | $thresholdedRequests = $propertyQuota->getPotentiallyThresholdedRequestsPerHour(); 79 | 80 | printf( 81 | 'Tokens per day quota consumed: %s, remaining: %s' . PHP_EOL, 82 | $tokensPerDay->getConsumed(), 83 | $tokensPerDay->getRemaining(), 84 | ); 85 | printf( 86 | 'Tokens per hour quota consumed: %s, remaining: %s' . PHP_EOL, 87 | $tokensPerHour->getConsumed(), 88 | $tokensPerHour->getRemaining(), 89 | ); 90 | printf( 91 | 'Concurrent requests quota consumed: %s, remaining: %s' . PHP_EOL, 92 | $concurrentRequests->getConsumed(), 93 | $concurrentRequests->getRemaining(), 94 | ); 95 | printf( 96 | 'Server errors per project per hour quota consumed: %s, remaining: %s' . PHP_EOL, 97 | $serverErrors->getConsumed(), 98 | $serverErrors->getRemaining(), 99 | ); 100 | printf( 101 | 'Potentially thresholded requests per hour quota consumed: %s, remaining: %s' . PHP_EOL, 102 | $thresholdedRequests->getConsumed(), 103 | $thresholdedRequests->getRemaining(), 104 | ); 105 | } 106 | // [END analyticsdata_run_report_with_property_quota_print_response] 107 | } 108 | // [END analyticsdata_run_report_with_property_quota] 109 | 110 | // The following 2 lines are only needed to run the samples 111 | require_once __DIR__ . '/../testing/sample_helpers.php'; 112 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 113 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_dimension_filter.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 59 | ->setDimensions([new Dimension(['name' => 'date'])]) 60 | ->setMetrics([new Metric(['name' => 'eventCount'])]) 61 | ->setDateRanges([ 62 | new DateRange([ 63 | 'start_date' => '7daysAgo', 64 | 'end_date' => 'yesterday', 65 | ]) 66 | ]) 67 | ->setDimensionFilter(new FilterExpression([ 68 | 'filter' => new Filter([ 69 | 'field_name' => 'eventName', 70 | 'string_filter' => new StringFilter([ 71 | 'value' => 'first_open' 72 | ]), 73 | ]), 74 | ])); 75 | $response = $client->runReport($request); 76 | 77 | printRunReportResponseWithDimensionFilter($response); 78 | } 79 | 80 | /** 81 | * Print results of a runReport call. 82 | * @param RunReportResponse $response 83 | */ 84 | function printRunReportResponseWithDimensionFilter(RunReportResponse $response) 85 | { 86 | // [START analyticsdata_print_run_report_response_header] 87 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 88 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 89 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 90 | } 91 | foreach ($response->getMetricHeaders() as $metricHeader) { 92 | printf( 93 | 'Metric header name: %s (%s)' . PHP_EOL, 94 | $metricHeader->getName(), 95 | MetricType::name($metricHeader->getType()) 96 | ); 97 | } 98 | // [END analyticsdata_print_run_report_response_header] 99 | 100 | // [START analyticsdata_print_run_report_response_rows] 101 | print 'Report result: ' . PHP_EOL; 102 | 103 | foreach ($response->getRows() as $row) { 104 | printf( 105 | '%s %s' . PHP_EOL, 106 | $row->getDimensionValues()[0]->getValue(), 107 | $row->getMetricValues()[0]->getValue() 108 | ); 109 | } 110 | // [END analyticsdata_print_run_report_response_rows] 111 | } 112 | // [END analyticsdata_run_report_with_dimension_filter] 113 | 114 | // The following 2 lines are only needed to run the samples 115 | require_once __DIR__ . '/../testing/sample_helpers.php'; 116 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 117 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_batch_report.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 53 | ->setRequests([ 54 | new RunReportRequest([ 55 | 'dimensions' => [ 56 | new Dimension(['name' => 'country']), 57 | new Dimension(['name' => 'region']), 58 | new Dimension(['name' => 'city']), 59 | ], 60 | 'metrics' => [new Metric(['name' => 'activeUsers'])], 61 | 'date_ranges' => [new DateRange([ 62 | 'start_date' => '2021-01-03', 63 | 'end_date' => '2021-01-09', 64 | ]), 65 | ], 66 | ]), 67 | new RunReportRequest([ 68 | 'dimensions' => [new Dimension(['name' => 'browser'])], 69 | 'metrics' => [new Metric(['name' => 'activeUsers'])], 70 | 'date_ranges' => [new DateRange([ 71 | 'start_date' => '2021-01-01', 72 | 'end_date' => '2021-01-31', 73 | ]), 74 | ], 75 | ]), 76 | ]); 77 | $response = $client->batchRunReports($request); 78 | 79 | print 'Batch report results' . PHP_EOL; 80 | foreach ($response->getReports() as $report) { 81 | printBatchRunReportsResponse($report); 82 | } 83 | } 84 | 85 | /** 86 | * Print results of a runReport call. 87 | * @param RunReportResponse $response 88 | */ 89 | function printBatchRunReportsResponse(RunReportResponse $response) 90 | { 91 | // [START analyticsdata_print_run_report_response_header] 92 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 93 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 94 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 95 | } 96 | foreach ($response->getMetricHeaders() as $metricHeader) { 97 | printf( 98 | 'Metric header name: %s (%s)' . PHP_EOL, 99 | $metricHeader->getName(), 100 | MetricType::name($metricHeader->getType()) 101 | ); 102 | } 103 | // [END analyticsdata_print_run_report_response_header] 104 | 105 | // [START analyticsdata_print_run_report_response_rows] 106 | print 'Report result: ' . PHP_EOL; 107 | 108 | foreach ($response->getRows() as $row) { 109 | printf( 110 | '%s %s' . PHP_EOL, 111 | $row->getDimensionValues()[0]->getValue(), 112 | $row->getMetricValues()[0]->getValue() 113 | ); 114 | } 115 | // [END analyticsdata_print_run_report_response_rows] 116 | } 117 | // [END analyticsdata_run_batch_report] 118 | 119 | // The following 2 lines are only needed to run the samples 120 | require_once __DIR__ . '/../testing/sample_helpers.php'; 121 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 122 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_dimension_exclude_filter.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 59 | ->setDimensions([new Dimension(['name' => 'pageTitle'])]) 60 | ->setMetrics([new Metric(['name' => 'sessions'])]) 61 | ->setDateRanges([new DateRange([ 62 | 'start_date' => '7daysAgo', 63 | 'end_date' => 'yesterday', 64 | ]) 65 | ]) 66 | ->setDimensionFilter(new FilterExpression([ 67 | 'not_expression' => new FilterExpression([ 68 | 'filter' => new Filter([ 69 | 'field_name' => 'pageTitle', 70 | 'string_filter' => new StringFilter([ 71 | 'value' => 'My Homepage', 72 | ]), 73 | ]), 74 | ]), 75 | ])); 76 | $response = $client->runReport($request); 77 | 78 | printRunReportResponseWithDimensionExcludeFilter($response); 79 | } 80 | 81 | /** 82 | * Print results of a runReport call. 83 | * @param RunReportResponse $response 84 | */ 85 | function printRunReportResponseWithDimensionExcludeFilter(RunReportResponse $response) 86 | { 87 | // [START analyticsdata_print_run_report_response_header] 88 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 89 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 90 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 91 | } 92 | foreach ($response->getMetricHeaders() as $metricHeader) { 93 | printf( 94 | 'Metric header name: %s (%s)' . PHP_EOL, 95 | $metricHeader->getName(), 96 | MetricType::name($metricHeader->getType()) 97 | ); 98 | } 99 | // [END analyticsdata_print_run_report_response_header] 100 | 101 | // [START analyticsdata_print_run_report_response_rows] 102 | print 'Report result: ' . PHP_EOL; 103 | 104 | foreach ($response->getRows() as $row) { 105 | printf( 106 | '%s %s' . PHP_EOL, 107 | $row->getDimensionValues()[0]->getValue(), 108 | $row->getMetricValues()[0]->getValue() 109 | ); 110 | } 111 | // [END analyticsdata_print_run_report_response_rows] 112 | } 113 | // [END analyticsdata_run_report_with_dimension_exclude_filter] 114 | 115 | // The following 2 lines are only needed to run the samples 116 | require_once __DIR__ . '/../testing/sample_helpers.php'; 117 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 118 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_dimension_in_list_filter.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 60 | ->setDimensions([new Dimension(['name' => 'eventName'])]) 61 | ->setMetrics([new Metric(['name' => 'sessions'])]) 62 | ->setDateRanges([new DateRange([ 63 | 'start_date' => '7daysAgo', 64 | 'end_date' => 'yesterday', 65 | ]) 66 | ]) 67 | ->setDimensionFilter(new FilterExpression([ 68 | 'filter' => new Filter([ 69 | 'field_name' => 'eventName', 70 | 'in_list_filter' => new InListFilter([ 71 | 'values' => [ 72 | 'purchase', 73 | 'in_app_purchase', 74 | 'app_store_subscription_renew', 75 | ], 76 | ]), 77 | ]), 78 | ])); 79 | $response = $client->runReport($request); 80 | 81 | printRunReportResponseWithDimensionInListFilter($response); 82 | } 83 | 84 | /** 85 | * Print results of a runReport call. 86 | * @param RunReportResponse $response 87 | */ 88 | function printRunReportResponseWithDimensionInListFilter(RunReportResponse $response) 89 | { 90 | // [START analyticsdata_print_run_report_response_header] 91 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 92 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 93 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 94 | } 95 | foreach ($response->getMetricHeaders() as $metricHeader) { 96 | printf( 97 | 'Metric header name: %s (%s)' . PHP_EOL, 98 | $metricHeader->getName(), 99 | MetricType::name($metricHeader->getType()) 100 | ); 101 | } 102 | // [END analyticsdata_print_run_report_response_header] 103 | 104 | // [START analyticsdata_print_run_report_response_rows] 105 | print 'Report result: ' . PHP_EOL; 106 | 107 | foreach ($response->getRows() as $row) { 108 | printf( 109 | '%s %s' . PHP_EOL, 110 | $row->getDimensionValues()[0]->getValue(), 111 | $row->getMetricValues()[0]->getValue() 112 | ); 113 | } 114 | // [END analyticsdata_print_run_report_response_rows] 115 | } 116 | // [END analyticsdata_run_report_with_dimension_in_list_filter] 117 | 118 | // The following 2 lines are only needed to run the samples 119 | require_once __DIR__ . '/../testing/sample_helpers.php'; 120 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 121 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_cohorts.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 57 | ->setDimensions([ 58 | new Dimension(['name' => 'cohort']), 59 | new Dimension(['name' => 'cohortNthWeek']), 60 | ]) 61 | ->setMetrics([ 62 | new Metric(['name' => 'cohortActiveUsers']), 63 | new Metric([ 64 | 'name' => 'cohortRetentionRate', 65 | 'expression' => 'cohortActiveUsers/cohortTotalUsers' 66 | ]) 67 | ]) 68 | ->setCohortSpec(new CohortSpec([ 69 | 'cohorts' => [ 70 | new Cohort([ 71 | 'dimension' => 'firstSessionDate', 72 | 'name' => 'cohort', 73 | 'date_range' => new DateRange([ 74 | 'start_date' => '2021-01-03', 75 | 'end_date' => '2021-01-09', 76 | ]), 77 | ]) 78 | ], 79 | 'cohorts_range' => new CohortsRange([ 80 | 'start_offset' => '0', 81 | 'end_offset' => '4', 82 | 'granularity' => '2', 83 | ]), 84 | ])); 85 | $response = $client->runReport($request); 86 | 87 | printRunReportResponseWithCohorts($response); 88 | } 89 | 90 | /** 91 | * Print results of a runReport call. 92 | * @param RunReportResponse $response 93 | */ 94 | function printRunReportResponseWithCohorts($response) 95 | { 96 | // [START analyticsdata_print_run_report_response_header] 97 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 98 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 99 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 100 | } 101 | foreach ($response->getMetricHeaders() as $metricHeader) { 102 | printf( 103 | 'Metric header name: %s (%s)' . PHP_EOL, 104 | $metricHeader->getName(), 105 | MetricType::name($metricHeader->getType()) 106 | ); 107 | } 108 | // [END analyticsdata_print_run_report_response_header] 109 | 110 | // [START analyticsdata_print_run_report_response_rows] 111 | print 'Report result: ' . PHP_EOL; 112 | 113 | foreach ($response->getRows() as $row) { 114 | printf( 115 | '%s %s' . PHP_EOL, 116 | $row->getDimensionValues()[0]->getValue(), 117 | $row->getMetricValues()[0]->getValue() 118 | ); 119 | } 120 | // [END analyticsdata_print_run_report_response_rows] 121 | } 122 | // [END analyticsdata_run_report_with_cohorts] 123 | 124 | // The following 2 lines are only needed to run the samples 125 | require_once __DIR__ . '/../testing/sample_helpers.php'; 126 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 127 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_pagination.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 54 | ->setDateRanges([ 55 | new DateRange([ 56 | 'start_date' => '350daysAgo', 57 | 'end_date' => 'yesterday', 58 | ]) 59 | ]) 60 | ->setDimensions([ 61 | new Dimension(['name' => 'firstUserSource']), 62 | new Dimension(['name' => 'firstUserMedium']), 63 | new Dimension(['name' => 'firstUserCampaignName']), 64 | ]) 65 | ->setMetrics([ 66 | new Metric(['name' => 'sessions']), 67 | new Metric(['name' => 'keyEvents']), 68 | new Metric(['name' => 'totalRevenue']), 69 | ]) 70 | ->setLimit(100000) 71 | ->setOffset(0); 72 | 73 | $requestCount = 1; 74 | printf('Sending request #%d' . PHP_EOL, $requestCount); 75 | 76 | $response = $client->runReport($request); 77 | # [END analyticsdata_run_report_with_pagination_page1] 78 | 79 | printRunReportResponseWithPagination($response, $requestCount); 80 | 81 | // [START analyticsdata_run_report_with_pagination_page2] 82 | $rowsReceived = count($response->getRows()); 83 | $totalRows = $response->getRowCount(); 84 | 85 | // Run the same report with an increased offset value to retrieve each additional 86 | // page until all rows are received. 87 | while ($rowsReceived < $totalRows) { 88 | $request = $request->setOffset($rowsReceived); 89 | $requestCount++; 90 | printf('Sending request #%d' . PHP_EOL, $requestCount); 91 | 92 | $response = $client->runReport($request); 93 | $rowsReceived += count($response->getRows()); 94 | printRunReportResponseWithPagination($response, $requestCount); 95 | } 96 | // [END analyticsdata_run_report_with_pagination_page2] 97 | } 98 | 99 | /** 100 | * Print results of a runReport call. 101 | * @param RunReportResponse $response 102 | * @param int $requestCount 103 | */ 104 | function printRunReportResponseWithPagination(RunReportResponse $response, int $requestCount) 105 | { 106 | // [START analyticsdata_print_run_report_response_header] 107 | printf('%s rows received for request #%d%s', count($response->getRows()), $requestCount, PHP_EOL); 108 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 109 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 110 | } 111 | foreach ($response->getMetricHeaders() as $metricHeader) { 112 | printf( 113 | 'Metric header name: %s (%s)' . PHP_EOL, 114 | $metricHeader->getName(), 115 | MetricType::name($metricHeader->getType()) 116 | ); 117 | } 118 | // [END analyticsdata_print_run_report_response_header] 119 | 120 | // [START analyticsdata_print_run_report_response_rows] 121 | print 'Report result: ' . PHP_EOL; 122 | 123 | foreach ($response->getRows() as $row) { 124 | printf( 125 | '%s %s' . PHP_EOL, 126 | $row->getDimensionValues()[0]->getValue(), 127 | $row->getMetricValues()[0]->getValue() 128 | ); 129 | } 130 | // [END analyticsdata_print_run_report_response_rows] 131 | } 132 | // [END analyticsdata_run_report_with_pagination] 133 | 134 | // The following 2 lines are only needed to run the samples 135 | require_once __DIR__ . '/../testing/sample_helpers.php'; 136 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 137 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_multiple_dimension_filters.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 61 | ->setDimensions([new Dimension(['name' => 'browser'])]) 62 | ->setMetrics([new Metric(['name' => 'activeUsers'])]) 63 | ->setDateRanges([ 64 | new DateRange([ 65 | 'start_date' => '7daysAgo', 66 | 'end_date' => 'yesterday', 67 | ]), 68 | ]) 69 | ->setDimensionFilter(new FilterExpression([ 70 | 'and_group' => new FilterExpressionList([ 71 | 'expressions' => [ 72 | new FilterExpression([ 73 | 'filter' => new Filter([ 74 | 'field_name' => 'browser', 75 | 'string_filter' => new StringFilter([ 76 | 'value' => 'Chrome', 77 | ]) 78 | ]), 79 | ]), 80 | new FilterExpression([ 81 | 'filter' => new Filter([ 82 | 'field_name' => 'countryId', 83 | 'string_filter' => new StringFilter([ 84 | 'value' => 'US', 85 | ]) 86 | ]), 87 | ]), 88 | ], 89 | ]), 90 | ])); 91 | $response = $client->runReport($request); 92 | 93 | printRunReportResponseWithMultipleDimensionFilters($response); 94 | } 95 | 96 | /** 97 | * Print results of a runReport call. 98 | * @param RunReportResponse $response 99 | */ 100 | function printRunReportResponseWithMultipleDimensionFilters(RunReportResponse $response) 101 | { 102 | // [START analyticsdata_print_run_report_response_header] 103 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 104 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 105 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 106 | } 107 | foreach ($response->getMetricHeaders() as $metricHeader) { 108 | printf( 109 | 'Metric header name: %s (%s)' . PHP_EOL, 110 | $metricHeader->getName(), 111 | MetricType::name($metricHeader->getType()) 112 | ); 113 | } 114 | // [END analyticsdata_print_run_report_response_header] 115 | 116 | // [START analyticsdata_print_run_report_response_rows] 117 | print 'Report result: ' . PHP_EOL; 118 | 119 | foreach ($response->getRows() as $row) { 120 | printf( 121 | '%s %s' . PHP_EOL, 122 | $row->getDimensionValues()[0]->getValue(), 123 | $row->getMetricValues()[0]->getValue() 124 | ); 125 | } 126 | // [END analyticsdata_print_run_report_response_rows] 127 | } 128 | // [END analyticsdata_run_report_with_multiple_dimension_filters] 129 | 130 | // The following 2 lines are only needed to run the samples 131 | require_once __DIR__ . '/../testing/sample_helpers.php'; 132 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 133 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_report_with_dimension_and_metric_filters.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 63 | ->setDimensions([new Dimension(['name' => 'city'])]) 64 | ->setMetrics([new Metric(['name' => 'activeUsers'])]) 65 | ->setDateRanges([new DateRange([ 66 | 'start_date' => '2020-03-31', 67 | 'end_date' => 'today', 68 | ]), 69 | ]) 70 | ->setMetricFilter(new FilterExpression([ 71 | 'filter' => new Filter([ 72 | 'field_name' => 'sessions', 73 | 'numeric_filter' => new NumericFilter([ 74 | 'operation' => Operation::GREATER_THAN, 75 | 'value' => new NumericValue([ 76 | 'int64_value' => 1000, 77 | ]), 78 | ]), 79 | ]), 80 | ])) 81 | ->setDimensionFilter(new FilterExpression([ 82 | 'and_group' => new FilterExpressionList([ 83 | 'expressions' => [ 84 | new FilterExpression([ 85 | 'filter' => new Filter([ 86 | 'field_name' => 'platform', 87 | 'string_filter' => new StringFilter([ 88 | 'match_type' => MatchType::EXACT, 89 | 'value' => 'Android', 90 | ]) 91 | ]), 92 | ]), 93 | new FilterExpression([ 94 | 'filter' => new Filter([ 95 | 'field_name' => 'eventName', 96 | 'string_filter' => new StringFilter([ 97 | 'match_type' => MatchType::EXACT, 98 | 'value' => 'in_app_purchase', 99 | ]) 100 | ]) 101 | ]), 102 | ], 103 | ]), 104 | ])); 105 | $response = $client->runReport($request); 106 | 107 | printRunReportResponseWithDimensionAndMetricFilters($response); 108 | } 109 | 110 | /** 111 | * Print results of a runReport call. 112 | * @param RunReportResponse $response 113 | */ 114 | function printRunReportResponseWithDimensionAndMetricFilters(RunReportResponse $response) 115 | { 116 | // [START analyticsdata_print_run_report_response_header] 117 | printf('%s rows received%s', $response->getRowCount(), PHP_EOL); 118 | foreach ($response->getDimensionHeaders() as $dimensionHeader) { 119 | printf('Dimension header name: %s%s', $dimensionHeader->getName(), PHP_EOL); 120 | } 121 | foreach ($response->getMetricHeaders() as $metricHeader) { 122 | printf( 123 | 'Metric header name: %s (%s)' . PHP_EOL, 124 | $metricHeader->getName(), 125 | MetricType::name($metricHeader->getType()) 126 | ); 127 | } 128 | // [END analyticsdata_print_run_report_response_header] 129 | 130 | // [START analyticsdata_print_run_report_response_rows] 131 | print 'Report result: ' . PHP_EOL; 132 | 133 | foreach ($response->getRows() as $row) { 134 | printf( 135 | '%s %s' . PHP_EOL, 136 | $row->getDimensionValues()[0]->getValue(), 137 | $row->getMetricValues()[0]->getValue() 138 | ); 139 | } 140 | // [END analyticsdata_print_run_report_response_rows] 141 | } 142 | // [END analyticsdata_run_report_with_dimension_and_metric_filters] 143 | 144 | // The following 2 lines are only needed to run the samples 145 | require_once __DIR__ . '/../testing/sample_helpers.php'; 146 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 147 | -------------------------------------------------------------------------------- /google-analytics-data/test/analyticsDataTest.php: -------------------------------------------------------------------------------- 1 | runFunctionSnippet('run_report', [$propertyId]); 34 | 35 | $this->assertStringContainsString('Report result', $output); 36 | } 37 | 38 | public function testClientFromJsonCredentials() 39 | { 40 | $jsonCredentials = self::requireEnv('GOOGLE_APPLICATION_CREDENTIALS'); 41 | $this->runFunctionSnippet('client_from_json_credentials', [$jsonCredentials]); 42 | 43 | $client = $this->getLastReturnedSnippetValue(); 44 | 45 | $this->assertInstanceOf(BetaAnalyticsDataClient::class, $client); 46 | 47 | try { 48 | $this->runFunctionSnippet('client_from_json_credentials', ['does-not-exist.json']); 49 | $this->fail('Non-existant json credentials should throw exception'); 50 | } catch (ValidationException $ex) { 51 | $this->assertStringContainsString('does-not-exist.json', $ex->getMessage()); 52 | } 53 | } 54 | 55 | public function testGetCommonMetadata() 56 | { 57 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 58 | $output = $this->runFunctionSnippet('get_common_metadata'); 59 | 60 | $this->assertStringContainsString('Dimensions and metrics', $output); 61 | } 62 | 63 | public function testGetMetadataByPropertyId() 64 | { 65 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 66 | $output = $this->runFunctionSnippet('get_metadata_by_property_id', [$propertyId]); 67 | 68 | $this->assertStringContainsString('Dimensions and metrics', $output); 69 | } 70 | 71 | public function testRunRealtimeReport() 72 | { 73 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 74 | $output = $this->runFunctionSnippet('run_realtime_report', [$propertyId]); 75 | 76 | $this->assertStringContainsString('Report result', $output); 77 | } 78 | 79 | public function testRunRealtimeReportWithMultipleDimensions() 80 | { 81 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 82 | $output = $this->runFunctionSnippet('run_realtime_report_with_multiple_dimensions', [$propertyId]); 83 | 84 | $this->assertStringContainsString('Report result', $output); 85 | } 86 | 87 | public function testRunBatchReport() 88 | { 89 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 90 | $output = $this->runFunctionSnippet('run_batch_report', [$propertyId]); 91 | 92 | $this->assertStringContainsString('Batch report result', $output); 93 | $this->assertStringContainsString('Report result', $output); 94 | } 95 | 96 | public function testRunPivotReport() 97 | { 98 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 99 | $output = $this->runFunctionSnippet('run_pivot_report', [$propertyId]); 100 | 101 | $this->assertStringContainsString('Report result', $output); 102 | } 103 | 104 | public function testRunRunRealtimeReportWithMinuteRanges() 105 | { 106 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 107 | $output = $this->runFunctionSnippet('run_realtime_report_with_minute_ranges', [$propertyId]); 108 | 109 | $this->assertStringContainsString('Report result', $output); 110 | } 111 | 112 | public function testRunRunRealtimeReportWithMultipleMetrics() 113 | { 114 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 115 | $output = $this->runFunctionSnippet('run_realtime_report_with_multiple_metrics', [$propertyId]); 116 | 117 | $this->assertStringContainsString('Report result', $output); 118 | } 119 | 120 | public function testRunReportWithDimensionExcludeFilter() 121 | { 122 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 123 | $output = $this->runFunctionSnippet('run_report_with_dimension_exclude_filter', [$propertyId]); 124 | 125 | $this->assertStringContainsString('Report result', $output); 126 | } 127 | 128 | public function testRunReportWithDimensionAndMetricFilters() 129 | { 130 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 131 | $output = $this->runFunctionSnippet('run_report_with_dimension_and_metric_filters', [$propertyId]); 132 | 133 | $this->assertStringContainsString('Report result', $output); 134 | } 135 | 136 | public function testRunReportWithDimensionFilter() 137 | { 138 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 139 | $output = $this->runFunctionSnippet('run_report_with_dimension_filter', [$propertyId]); 140 | 141 | $this->assertStringContainsString('Report result', $output); 142 | } 143 | 144 | public function testRunReportWithMultipleDimensionFilters() 145 | { 146 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 147 | $output = $this->runFunctionSnippet('run_report_with_multiple_dimension_filters', [$propertyId]); 148 | 149 | $this->assertStringContainsString('Report result', $output); 150 | } 151 | 152 | public function testRunReportWithMultipleMetrics() 153 | { 154 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 155 | $output = $this->runFunctionSnippet('run_report_with_multiple_metrics', [$propertyId]); 156 | 157 | $this->assertStringContainsString('Report result', $output); 158 | } 159 | 160 | public function testRunReportWithDimensionInListFilter() 161 | { 162 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 163 | $output = $this->runFunctionSnippet('run_report_with_dimension_in_list_filter', [$propertyId]); 164 | 165 | $this->assertStringContainsString('Report result', $output); 166 | } 167 | 168 | public function testRunReportWithNamedDateRanges() 169 | { 170 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 171 | $output = $this->runFunctionSnippet('run_report_with_named_date_ranges', [$propertyId]); 172 | 173 | $this->assertStringContainsString('Report result', $output); 174 | } 175 | 176 | public function testRunReportWithMultipleDimensions() 177 | { 178 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 179 | $output = $this->runFunctionSnippet('run_report_with_multiple_dimensions', [$propertyId]); 180 | 181 | $this->assertStringContainsString('Report result', $output); 182 | } 183 | 184 | public function testRunReportWithDateRanges() 185 | { 186 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 187 | $output = $this->runFunctionSnippet('run_report_with_date_ranges', [$propertyId]); 188 | 189 | $this->assertStringContainsString('Report result', $output); 190 | } 191 | 192 | public function testRunReportWithCohorts() 193 | { 194 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 195 | $output = $this->runFunctionSnippet('run_report_with_cohorts', [$propertyId]); 196 | 197 | $this->assertStringContainsString('Report result', $output); 198 | } 199 | 200 | public function testRunReportWithAggregations() 201 | { 202 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 203 | $output = $this->runFunctionSnippet('run_report_with_aggregations', [$propertyId]); 204 | 205 | $this->assertStringContainsString('Report result', $output); 206 | } 207 | 208 | public function testRunReportWithOrdering() 209 | { 210 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 211 | $output = $this->runFunctionSnippet('run_report_with_ordering', [$propertyId]); 212 | 213 | $this->assertStringContainsString('Report result', $output); 214 | } 215 | 216 | public function testRunReportWithPagination() 217 | { 218 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 219 | $output = $this->runFunctionSnippet('run_report_with_pagination', [$propertyId]); 220 | 221 | $this->assertStringContainsString('Report result', $output); 222 | } 223 | 224 | public function testRunReportWithPropertyQuota() 225 | { 226 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 227 | $output = $this->runFunctionSnippet('run_report_with_property_quota', [$propertyId]); 228 | 229 | $this->assertStringContainsString('Tokens per day quota consumed', $output); 230 | } 231 | 232 | public function testRunFunnelReport() 233 | { 234 | $propertyId = self::requireEnv('GA_TEST_PROPERTY_ID'); 235 | $output = $this->runFunctionSnippet('run_funnel_report', [$propertyId]); 236 | 237 | $this->assertStringContainsString('FUNNEL VISUALIZATION', $output); 238 | $this->assertStringContainsString('FUNNEL TABLE', $output); 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /google-analytics-data/src/run_funnel_report.php: -------------------------------------------------------------------------------- 1 | setProperty('properties/' . $propertyId) 67 | ->setDateRanges([ 68 | new DateRange([ 69 | 'start_date' => '30daysAgo', 70 | 'end_date' => 'today', 71 | ]), 72 | ]) 73 | ->setFunnelBreakdown( 74 | new FunnelBreakdown([ 75 | 'breakdown_dimension' => 76 | new Dimension([ 77 | 'name' => 'deviceCategory' 78 | ]) 79 | ]) 80 | ) 81 | ->setFunnel(new Funnel()); 82 | 83 | // Add funnel steps to the funnel. 84 | 85 | // 1. Add first open/visit step. 86 | $request->getFunnel()->getSteps()[] = new FunnelStep([ 87 | 'name' => 'First open/visit', 88 | 'filter_expression' => new FunnelFilterExpression([ 89 | 'or_group' => new FunnelFilterExpressionList([ 90 | 'expressions' => [ 91 | new FunnelFilterExpression([ 92 | 'funnel_event_filter' => new FunnelEventFilter([ 93 | 'event_name' => 'first_open', 94 | ]) 95 | ]), 96 | new FunnelFilterExpression([ 97 | 'funnel_event_filter' => new FunnelEventFilter([ 98 | 'event_name' => 'first_visit' 99 | ]) 100 | ]) 101 | ] 102 | ]) 103 | ]) 104 | ]); 105 | 106 | // 2. Add organic visitors step. 107 | $request->getFunnel()->getSteps()[] = new FunnelStep([ 108 | 'name' => 'Organic visitors', 109 | 'filter_expression' => new FunnelFilterExpression([ 110 | 'funnel_field_filter' => new FunnelFieldFilter([ 111 | 'field_name' => 'firstUserMedium', 112 | 'string_filter' => new StringFilter([ 113 | 'match_type' => MatchType::CONTAINS, 114 | 'case_sensitive' => false, 115 | 'value' => 'organic', 116 | ]) 117 | ]) 118 | ]) 119 | ]); 120 | 121 | // 3. Add session start step. 122 | $request->getFunnel()->getSteps()[] = new FunnelStep([ 123 | 'name' => 'Session start', 124 | 'filter_expression' => new FunnelFilterExpression([ 125 | 'funnel_event_filter' => new FunnelEventFilter([ 126 | 'event_name' => 'session_start', 127 | ]) 128 | ]) 129 | ]); 130 | 131 | // 4. Add screen/page view step. 132 | $request->getFunnel()->getSteps()[] = new FunnelStep([ 133 | 'name' => 'Screen/Page view', 134 | 'filter_expression' => new FunnelFilterExpression([ 135 | 'or_group' => new FunnelFilterExpressionList([ 136 | 'expressions' => [ 137 | new FunnelFilterExpression([ 138 | 'funnel_event_filter' => new FunnelEventFilter([ 139 | 'event_name' => 'screen_view', 140 | ]) 141 | ]), 142 | new FunnelFilterExpression([ 143 | 'funnel_event_filter' => new FunnelEventFilter([ 144 | 'event_name' => 'page_view' 145 | ]) 146 | ]) 147 | ] 148 | ]) 149 | ]) 150 | ]); 151 | 152 | // 5. Add purchase step. 153 | $request->getFunnel()->getSteps()[] = new FunnelStep([ 154 | 'name' => 'Purchase', 155 | 'filter_expression' => new FunnelFilterExpression([ 156 | 'or_group' => new FunnelFilterExpressionList([ 157 | 'expressions' => [ 158 | new FunnelFilterExpression([ 159 | 'funnel_event_filter' => new FunnelEventFilter([ 160 | 'event_name' => 'purchase', 161 | ]) 162 | ]), 163 | new FunnelFilterExpression([ 164 | 'funnel_event_filter' => new FunnelEventFilter([ 165 | 'event_name' => 'in_app_purchase' 166 | ]) 167 | ]) 168 | ] 169 | ]) 170 | ]) 171 | ]); 172 | 173 | // Make an API call. 174 | $response = $client->runFunnelReport($request); 175 | 176 | printRunFunnelReportResponse($response); 177 | } 178 | 179 | // [START analyticsdata_print_run_funnel_report_response] 180 | /** 181 | * Print results of a runFunnelReport call. 182 | * @param RunFunnelReportResponse $response 183 | */ 184 | function printRunFunnelReportResponse(RunFunnelReportResponse $response) 185 | { 186 | print 'Report result: ' . PHP_EOL; 187 | print '=== FUNNEL VISUALIZATION ===' . PHP_EOL; 188 | printFunnelSubReport($response->getFunnelVisualization()); 189 | 190 | print '=== FUNNEL TABLE ===' . PHP_EOL; 191 | printFunnelSubReport($response->getFunnelTable()); 192 | } 193 | 194 | /** 195 | * Print the contents of a FunnelSubReport object. 196 | * @param FunnelSubReport $subReport 197 | */ 198 | function printFunnelSubReport(FunnelSubReport $subReport) 199 | { 200 | print 'Dimension headers:' . PHP_EOL; 201 | foreach ($subReport->getDimensionHeaders() as $dimensionHeader) { 202 | print $dimensionHeader->getName() . PHP_EOL; 203 | } 204 | 205 | print PHP_EOL . 'Metric headers:' . PHP_EOL; 206 | foreach ($subReport->getMetricHeaders() as $metricHeader) { 207 | print $metricHeader->getName() . PHP_EOL; 208 | } 209 | 210 | print PHP_EOL . 'Dimension and metric values for each row in the report:'; 211 | foreach ($subReport->getRows() as $rowIndex => $row) { 212 | print PHP_EOL . 'Row #' . $rowIndex . PHP_EOL; 213 | foreach ($row->getDimensionValues() as $dimIndex => $dimValue) { 214 | $dimName = $subReport->getDimensionHeaders()[$dimIndex]->getName(); 215 | print $dimName . ": '" . $dimValue->getValue() . "'" . PHP_EOL; 216 | } 217 | foreach ($row->getMetricValues() as $metricIndex => $metricValue) { 218 | $metricName = $subReport->getMetricHeaders()[$metricIndex]->getName(); 219 | print $metricName . ": '" . $metricValue->getValue() . "'" . PHP_EOL; 220 | } 221 | } 222 | 223 | print PHP_EOL . 'Sampling metadata for each date range:' . PHP_EOL; 224 | foreach ($subReport->getMetadata()->getSamplingMetadatas() as $metadataIndex => $metadata) { 225 | printf('Sampling metadata for date range #%d: samplesReadCount=%d' . 226 | 'samplingSpaceSize=%d%s', 227 | $metadataIndex, $metadata->getSamplesReadCount(), $metadata->getSamplingSpaceSize(), PHP_EOL); 228 | } 229 | } 230 | // [END analyticsdata_print_run_funnel_report_response] 231 | // [END analyticsdata_run_funnel_report] 232 | 233 | // The following 2 lines are only needed to run the samples 234 | require_once __DIR__ . '/../testing/sample_helpers.php'; 235 | return \Google\Analytics\Data\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv); 236 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------