### Instantiate BetaAnalyticsDataClient with Minimal Configuration Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Instantiates the client using default credentials and configuration. This is the simplest way to get started. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; // Minimal - uses default credentials and configuration $client = new BetaAnalyticsDataClient(); ``` -------------------------------- ### Complete Report Retrieval and Processing Example Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportResponse.md A comprehensive example demonstrating how to initialize the client, construct a RunReportRequest, execute the report, and process various parts of the response including headers, data rows, aggregations, and quota status. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\DateRange; use Google\Analytics\Data\V1beta\MetricAggregation; $client = new BetaAnalyticsDataClient(); $request = (new RunReportRequest()) ->setProperty('properties/123456') ->setDimensions([new Dimension(['name' => 'country'])]) ->setMetrics([ new Metric(['name' => 'activeUsers']), new Metric(['name' => 'screenPageViews']), ]) ->setDateRanges([ new DateRange(['start_date' => '2024-01-01', 'end_date' => '2024-01-31']), ]) ->setMetricAggregations([MetricAggregation::TOTAL]) ->setReturnPropertyQuota(true); $response = $client->runReport($request); // Process headers echo "Response Type: " . $response->getKind() . "\n"; echo "Dimensions:\n"; foreach ($response->getDimensionHeaders() as $header) { echo " - " . $header->getName() . "\n"; } echo "Metrics:\n"; foreach ($response->getMetricHeaders() as $header) { echo " - " . $header->getName() . " (" . $header->getType() . ")\n"; } // Process data rows echo "\nData:\n"; foreach ($response->getRows() as $row) { $country = $row->getDimensionValues()[0]->getValue(); $users = $row->getMetricValues()[0]->getValue(); $views = $row->getMetricValues()[1]->getValue(); printf("%s: %s active users, %s page views\n", $country, $users, $views); } // Process aggregations if ($response->getTotals()->count() > 0) { $total = $response->getTotals()[0]; $totalUsers = $total->getMetricValues()[0]->getValue(); $totalViews = $total->getMetricValues()[1]->getValue(); echo "\nTotals:\n"; printf("Total: %s active users, %s page views\n", $totalUsers, $totalViews); } // Check quota $quota = $response->getPropertyQuota(); if ($quota) { $daily = $quota->getTokensPerDay(); $remaining = $daily->getLimit() - $daily->getConsumed(); echo "\nQuota Status:\n"; echo "Daily tokens used: " . $daily->getConsumed() . " / " . $daily->getLimit() . "\n"; echo "Daily tokens remaining: " . $remaining . "\n"; } // Pagination $total = $response->getRowCount(); $returned = count($response->getRows()); if ($returned < $total) { echo "\nNote: " . ($total - $returned) . " more rows available.\n"; echo "Use offset parameter to fetch remaining rows.\n"; } ``` -------------------------------- ### Code Examples Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/INDEX.md A collection of over 15 complete usage examples, demonstrating real-world patterns like pagination, filtering, batch processing, and helper functions for tasks such as CSV export. ```APIDOC ## Code Examples ### Description Practical, runnable examples to help users quickly integrate and utilize the API client library. ### Example Categories - 15+ complete usage examples. - Real-world patterns: pagination, filtering, batch processing. - Helper functions: CSV export, data transformation. ``` -------------------------------- ### Install Google Analytics Data Client for PHP Source: https://github.com/googleapis/php-analytics-data/blob/main/README.md Install the Google Analytics Data client library for PHP using Composer. ```sh composer require google/analytics-data ``` -------------------------------- ### Example Async Usage Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/BetaAnalyticsDataClient.md Demonstrates how to use asynchronous methods with BetaAnalyticsDataClient. The `runReportAsync` method returns a Promise, which can be waited upon to get the response. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\RunReportRequest; $client = new BetaAnalyticsDataClient(); $request = (new RunReportRequest())->setProperty('properties/123456'); $promise = $client->runReportAsync($request); $response = $promise->wait(); // Blocks until complete ``` -------------------------------- ### Accessing Total Metric Values Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportResponse.md Retrieve aggregated total metric values if the 'TOTAL' aggregation was requested. This example shows how to get the total for the first metric. ```php if ($response->getTotals()->count() > 0) { foreach ($response->getTotals() as $totalRow) { $totalUsers = $totalRow->getMetricValues()[0]->getValue(); echo "Total active users: " . $totalUsers . "\n"; } } ``` -------------------------------- ### ValidationException Example Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/errors.md Illustrates how to catch and handle ValidationException, which is thrown for client-side validation failures before an API call is made. The example shows catching the exception and printing its message. ```APIDOC ## ValidationException Example ### Description Handles client-side validation errors by catching `ValidationException`. ### Method `try...catch` block for `Google\Api\Core\ValidationException` ### Example ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\ApiCore\ValidationException; $client = new BetaAnalyticsDataClient(); try { // parseName with invalid format $parts = BetaAnalyticsDataClient::parseName('invalid-resource-name'); } catch (ValidationException $ex) { echo "Validation failed: " . $ex->getMessage() . "\n"; } ``` ``` -------------------------------- ### Check gRPC Extension Installation Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Verifies if the gRPC extension is loaded and displays its version. This is crucial for enabling connection reuse and improving performance. ```php if (extension_loaded('grpc')) { echo "gRPC extension is installed\n"; echo "gRPC version: " . phpversion('grpc') . "\n"; } else { echo "gRPC extension not found\n"; } ``` -------------------------------- ### Run a Basic Report with BetaAnalyticsDataClient Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Use the BetaAnalyticsDataClient to run a report for a specific property, dimensions, metrics, and date range. This example shows how to fetch active users by country for a given month. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\DateRange; $client = new BetaAnalyticsDataClient(); $request = (new RunReportRequest()) ->setProperty('properties/123456') ->setDimensions([new Dimension(['name' => 'country'])]) ->setMetrics([new Metric(['name' => 'activeUsers'])]) ->setDateRanges([ new DateRange([ 'start_date' => '2024-01-01', 'end_date' => '2024-01-31', ]), ]); $response = $client->runReport($request); foreach ($response->getRows() as $row) { $country = $row->getDimensionValues()[0]->getValue(); $users = $row->getMetricValues()[0]->getValue(); echo "$country: $users active users\n"; } ``` -------------------------------- ### Run a Report with Complex Configurations in PHP Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md This snippet shows a complete example of building a RunReportRequest with dimensions, metrics, date ranges, dimension and metric filters, ordering, limits, and metric aggregations. It then executes the report and iterates through the results. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\DateRange; use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Filter; use Google\Analytics\Data\V1beta\StringFilter; use Google\Analytics\Data\V1beta\OrderBy; use Google\Analytics\Data\V1beta\OrderByMetric; use Google\Analytics\Data\V1beta\MetricAggregation; $client = new BetaAnalyticsDataClient(); $request = (new RunReportRequest()) ->setProperty('properties/123456') ->setDimensions([ new Dimension(['name' => 'country']), new Dimension(['name' => 'city']), ]) ->setMetrics([ new Metric(['name' => 'activeUsers']), new Metric(['name' => 'screenPageViews']), ]) ->setDateRanges([ new DateRange([ 'start_date' => '2024-01-01', 'end_date' => '2024-01-31', ]), ]) ->setDimensionFilter( (new FilterExpression()) ->setFilter((new Filter()) ->setFieldName('country') ->setStringFilter((new StringFilter()) ->setMatchType('EXACT') ->setValue('United States') ) ) ) ->setMetricFilter( (new FilterExpression()) ->setFilter((new Filter()) ->setFieldName('activeUsers') ->setNumericFilter((new NumericFilter()) ->setOperation('GREATER_THAN') ->setValue(100) ) ) ) ->setOrderBys([ (new OrderBy()) ->setMetric(new OrderByMetric(['metric_name' => 'screenPageViews'])) ->setDesc(true), ]) ->setLimit(100) ->setOffset(0) ->setCurrencyCode('USD') ->setKeepEmptyRows(false) ->setReturnPropertyQuota(true) ->setMetricAggregations([ MetricAggregation::TOTAL, MetricAggregation::MINIMUM, MetricAggregation::MAXIMUM, ]); $response = $client->runReport($request); foreach ($response->getRows() as $row) { $country = $row->getDimensionValues()[0]->getValue(); $city = $row->getDimensionValues()[1]->getValue(); $users = $row->getMetricValues()[0]->getValue(); $views = $row->getMetricValues()[1]->getValue(); printf("%s, %s: %s users, %s views\n", $country, $city, $users, $views); } echo "Total tokens used today: " . $response->getPropertyQuota()->getTokensPerDay()->getConsumed(); ``` -------------------------------- ### V1beta to V1 API Migration Example Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Illustrates the namespace change required for migrating from the v1beta to the future v1 version of the Analytics Data API client. ```php // Currently (v1beta): use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; // Future (v1): use Google\Analytics\Data\V1\Client\AnalyticsDataClient; ``` -------------------------------- ### Configure Transport to gRPC Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Explicitly set the transport to gRPC for improved performance. Ensure the gRPC PECL extension is installed. ```php $client = new BetaAnalyticsDataClient(['transport' => 'grpc']); ``` -------------------------------- ### Enable Logging with Monolog Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Configures the BetaAnalyticsDataClient to use Monolog for logging, directing debug messages to standard error. Ensure Monolog is installed and configured. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Monolog\Logger; use Monolog\Handler\StreamHandler; $logger = new Logger('analytics'); $logger->pushHandler(new StreamHandler('php://stderr', Logger::DEBUG)); $client = new BetaAnalyticsDataClient(['logger' => $logger]); ``` -------------------------------- ### Set Order By Clause Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Configure how report rows are ordered or sorted. This example demonstrates sorting by a metric in descending order. ```php use Google\Analytics\Data\V1beta\OrderBy; use Google\Analytics\Data\V1beta\OrderByMetric; // Sort by metric descending $orderBy = (new OrderBy()) ->setMetric(new OrderByMetric(['metric_name' => 'activeUsers'])) ->setDesc(true); $request->setOrderBys([$orderBy]); ``` -------------------------------- ### Accessing Minimum Metric Values Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportResponse.md Retrieve the minimum values for each metric if the 'MINIMUM' aggregation was requested. This example accesses the minimum value for the first metric. ```php if ($response->getMinimums()->count() > 0) { $minUsersRow = $response->getMinimums()[0]; $minUsers = $minUsersRow->getMetricValues()[0]->getValue(); echo "Minimum daily active users: " . $minUsers . "\n"; } ``` -------------------------------- ### ApiException Example Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/errors.md Demonstrates how to catch and handle ApiException, which is thrown when an API error occurs. It shows how to access the error code and message, and provides conditional logic for common error codes. ```APIDOC ## ApiException Example ### Description Handles API errors by catching `ApiException` and inspecting its properties like `code` and `message`. ### Method `try...catch` block for `Google\Api\Core\ApiException` ### Example ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\ApiCore\ApiException; $client = new BetaAnalyticsDataClient(); $request = new RunReportRequest(['property' => 'properties/invalid']); try { $response = $client->runReport($request); } catch (ApiException $ex) { echo "Error Code: " . $ex->getCode() . "\n"; echo "Message: " . $ex->getMessage() . "\n"; if ($ex->getCode() == 3) { // INVALID_ARGUMENT echo "Request parameter is invalid\n"; } elseif ($ex->getCode() == 7) { // PERMISSION_DENIED echo "Check your authentication and scopes\n"; } elseif ($ex->getCode() == 14) { // UNAVAILABLE echo "Service is temporarily unavailable, retrying...\n"; } } ``` ``` -------------------------------- ### Error Handling with ApiException Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Implement try-catch blocks to handle API exceptions. This example shows how to catch quota exceeded errors and retry. ```php use Google\ApiCore\ApiException; try { $response = $client->runReport($request); } catch (ApiException $ex) { // Get error code (gRPC status code 0-16) $code = $ex->getCode(); // Common codes: // 3 = INVALID_ARGUMENT (bad parameters) // 5 = NOT_FOUND (resource not found) // 7 = PERMISSION_DENIED (auth/authz failed) // 8 = RESOURCE_EXHAUSTED (quota exceeded) // 14 = UNAVAILABLE (service down) if ($code == 8) { // Quota exceeded - wait and retry sleep(60); $response = $client->runReport($request); } } ``` -------------------------------- ### Accessing Maximum Metric Values Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportResponse.md Retrieve the maximum values for each metric if the 'MAXIMUM' aggregation was requested. This example accesses the maximum value for the first metric. ```php if ($response->getMaximums()->count() > 0) { $maxUsersRow = $response->getMaximums()[0]; $maxUsers = $maxUsersRow->getMetricValues()[0]->getValue(); echo "Maximum daily active users: " . $maxUsers . "\n"; } ``` -------------------------------- ### Get Property Quotas Snapshot Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/AlphaAnalyticsDataClient.md Returns the current quota state for the property. Use this to check current usage against defined limits. ```php public function getPropertyQuotasSnapshot(GetPropertyQuotasSnapshotRequest $request, array $callOptions = []): PropertyQuotasSnapshot ``` -------------------------------- ### Set Offset for Pagination Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Configure the starting row for paginated results. Ensure this is a non-negative integer. Used in conjunction with `limit`. ```php // Get rows 100-199 $request->setOffset(100); $request->setLimit(100); ``` -------------------------------- ### Get Real-Time Active Users Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Retrieve real-time active users for a given property. This is useful for monitoring current engagement. ```php $response = $client->runRealtimeReport((new RunRealtimeReportRequest()) ->setProperty('properties/123456') ->setMetrics([new Metric(['name' => 'activeUsers'])]) ); ``` -------------------------------- ### Configure Custom API Endpoint Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Use this snippet to point the client to a custom API endpoint, often used for testing or specific deployment scenarios. Ensure the 'apiEndpoint' and 'universeDomain' match your custom setup. ```php // For use with analytics API on custom domain $client = new BetaAnalyticsDataClient([ 'apiEndpoint' => 'custom.domain.com:443', 'universeDomain' => 'custom.domain.com', 'credentials' => $credentials, ]); ``` -------------------------------- ### Get Report Task Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/AlphaAnalyticsDataClient.md Retrieves configuration metadata for a specific report task. Use this when you need to check the details of an existing report task. ```php public function getReportTask(GetReportTaskRequest $request, array $callOptions = []): ReportTask ``` -------------------------------- ### Handle ApiException in PHP Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/errors.md Catch and process ApiException for API-related errors. This example demonstrates checking specific gRPC status codes to provide tailored user feedback or retry logic. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\ApiCore\ApiException; $client = new BetaAnalyticsDataClient(); $request = new RunReportRequest(['property' => 'properties/invalid']); try { $response = $client->runReport($request); } catch (ApiException $ex) { echo "Error Code: " . $ex->getCode() . "\n"; echo "Message: " . $ex->getMessage() . "\n"; if ($ex->getCode() == 3) { // INVALID_ARGUMENT echo "Request parameter is invalid\n"; } elseif ($ex->getCode() == 7) { // PERMISSION_DENIED echo "Check your authentication and scopes\n"; } elseif ($ex->getCode() == 14) { // UNAVAILABLE echo "Service is temporarily unavailable, retrying...\n"; } } ``` -------------------------------- ### Initialize Client with Application Default Credentials Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Instantiate the client using Application Default Credentials. This is the recommended authentication method. ```php $client = new BetaAnalyticsDataClient(); ``` -------------------------------- ### Initialize Client with Service Account Credentials Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Authenticate using a service account JSON file. Ensure the file path is correct and the service account has the necessary permissions. ```php use Google\Auth\Credentials\ServiceAccountCredentials; $credentials = new ServiceAccountCredentials( ['https://www.googleapis.com/auth/analytics.readonly'], json_decode(file_get_contents('/path/to/service-account.json'), true) ); $client = new BetaAnalyticsDataClient(['credentials' => $credentials]); ``` -------------------------------- ### Instantiate BetaAnalyticsDataClient with Application Default Credentials Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Demonstrates initializing the client, which automatically utilizes Application Default Credentials. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; // Uses Application Default Credentials automatically $client = new BetaAnalyticsDataClient(); ``` -------------------------------- ### Instantiate BetaAnalyticsDataClient Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/BetaAnalyticsDataClient.md Creates a new instance of the BetaAnalyticsDataClient with optional configuration, using service account credentials. Ensure the path to your service account JSON file is correct. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Auth\Credentials\ServiceAccountCredentials; $scopes = ['https://www.googleapis.com/auth/analytics.readonly']; $credentials = new ServiceAccountCredentials($scopes, json_decode( file_get_contents('/path/to/service-account.json'), true )); $client = new BetaAnalyticsDataClient(['credentials' => $credentials]); ``` -------------------------------- ### Get Active Users by Country Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Run a report to get active users by country, ordered by active users in descending order. This snippet requires a property ID and specifies a date range. ```php $response = $client->runReport((new RunReportRequest()) ->setProperty('properties/123456') ->setDimensions([new Dimension(['name' => 'country'])]) ->setMetrics([new Metric(['name' => 'activeUsers'])]) ->setDateRanges([new DateRange([ 'start_date' => '2024-01-01', 'end_date' => '2024-01-31', ])]) ->setOrderBys([ (new OrderBy()) ->setMetric(new OrderByMetric(['metric_name' => 'activeUsers'])) ->setDesc(true) ]) ->setLimit(100)); foreach ($response->getRows() as $row) { echo $row->getDimensionValues()[0]->getValue() . ": " . $row->getMetricValues()[0]->getValue() . " users\n"; } ``` -------------------------------- ### Configuration Options Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/INDEX.md Documentation covering all constructor options, authentication methods (service account, OAuth, ADC), transport configurations (gRPC, REST), and guidance on performance tuning. ```APIDOC ## Configuration Options ### Description Details on how to configure the client library for various use cases, including authentication, transport protocols, and performance optimization. ### Constructor Options - All documented constructor options are available. ### Authentication - Service account authentication - OAuth 2.0 authentication - Application Default Credentials (ADC) ### Transport Configuration - gRPC transport - REST transport ### Performance Tuning - Guidance on optimizing client performance. ``` -------------------------------- ### getAudienceList Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/AlphaAnalyticsDataClient.md Gets configuration metadata about a specific audience list. ```APIDOC ## getAudienceList ### Description Gets configuration metadata about a specific audience list. ### Method GET ### Endpoint /v1alpha/{name=properties/*/audienceLists/*} ### Parameters #### Path Parameters - **name** (string) - Required - The audience list resource name. Format: `properties/{propertyId}/audienceLists/{audienceListId}` ### Response #### Success Response (200) - **response** (AudienceList) - The audience list metadata #### Response Example ```json { "name": "properties/123456/audienceLists/abcdef123456", "displayName": "Example Audience List", "description": "Users who visited the product page." } ``` ``` -------------------------------- ### Get Metadata Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Retrieves information about available dimensions and metrics. ```APIDOC ## Get Metadata ### Description Retrieves information about available dimensions and metrics. ### Method `getMetadata(GetMetadataRequest $request)` ### Parameters #### Request Body - **request** (GetMetadataRequest) - An object for the metadata request. ``` -------------------------------- ### Get Audience Export Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Retrieves the status of an existing audience export. ```APIDOC ## Get Audience Export ### Description Retrieves the status of an existing audience export. ### Method `getAudienceExport(GetAudienceExportRequest $request)` ### Parameters #### Request Body - **request** (GetAudienceExportRequest) - An object specifying the audience export to retrieve. ``` -------------------------------- ### Get Property Quotas Snapshot Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Retrieves a snapshot of the quota usage for a property. ```APIDOC ## Get Property Quotas Snapshot ### Description Retrieves a snapshot of the quota usage for a property. ### Method `getPropertyQuotasSnapshot(GetPropertyQuotasSnapshotRequest $request)` ### Parameters #### Request Body - **request** (GetPropertyQuotasSnapshotRequest) - An object specifying the property for which to get quota information. ``` -------------------------------- ### GetMetadataRequest Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/types.md Request to get available metadata for a property. Requires the metadata resource name. ```APIDOC ## GetMetadataRequest ### Description Request to get available metadata. ### Parameters #### Path Parameters - **name** (string) - Yes - Metadata resource name (e.g., "properties/123456/metadata") ``` -------------------------------- ### Check Protobuf Extension Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Verify if the native protobuf extension is loaded, which significantly improves performance compared to the pure-PHP implementation. ```php extension_loaded('protobuf') ? 'native' : 'pure-PHP' ``` -------------------------------- ### Instantiate BetaAnalyticsDataClient with Options Array Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Instantiates the client with specific API endpoint and transport options provided in an array. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; // With options array $client = new BetaAnalyticsDataClient([ 'apiEndpoint' => 'analyticsdata.googleapis.com:443', 'transport' => 'grpc', ]); ``` -------------------------------- ### DimensionFilter Field Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Sets and gets the filter expression for dimension values, acting as a WHERE clause. ```APIDOC ## dimensionFilter ### getDimensionFilter ```php public function getDimensionFilter(): ?FilterExpression ``` ### setDimensionFilter ```php public function setDimensionFilter(FilterExpression $var): self ``` ### clearDimensionFilter ```php public function clearDimensionFilter(): self ``` Filters for dimension values (WHERE clause). Metrics cannot be filtered at this level. **Example:** ```php use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Filter; use Google\Analytics\Data\V1beta\StringFilter; $filter = (new Filter()) ->setFieldName('country') ->setStringFilter((new StringFilter()) ->setMatchType('EXACT') ->setValue('United States') ); $filterExpression = (new FilterExpression()) ->setFilter($filter); $request->setDimensionFilter($filterExpression); ``` ``` -------------------------------- ### Initialize Client with User Credentials (OAuth) Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Authenticate using user OAuth credentials. This is typically used for interactive applications. ```php use Google\Auth\OAuth2; $oauth2 = new OAuth2([...]); $client = new BetaAnalyticsDataClient(['credentials' => $oauth2]); ``` -------------------------------- ### Dimensions Field Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Sets and gets the dimensions to include in the report. Dimensions break down metrics. ```APIDOC ## dimensions ### getDimensions ```php public function getDimensions(): RepeatedField ``` ### setDimensions ```php public function setDimensions(array $var): self ``` The dimensions to include in the report. Dimensions are attributes that break down metrics (like country, city, device). **Constraints:** - Maximum 9 dimensions per request - Each dimension must be a valid Dimension object - Some dimensions are not available for certain report types **Returns:** `RepeatedField` - Traversable collection of dimensions **Example:** ```php use Google\Analytics\Data\V1beta\Dimension; $request->setDimensions([ new Dimension(['name' => 'country']), new Dimension(['name' => 'city']), new Dimension(['name' => 'deviceCategory']), ]); foreach ($request->getDimensions() as $dimension) { echo $dimension->getName() . "\n"; } ``` ``` -------------------------------- ### Property Field Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Sets and gets the Google Analytics property identifier for the report request. ```APIDOC ## property ### getProperty ```php public function getProperty(): string ``` ### setProperty ```php public function setProperty(string $var): self ``` The Google Analytics property identifier. **Format:** `properties/{PROPERTY_ID}` (e.g., `properties/123456`) **Required:** Yes **Example:** ```php $request->setProperty('properties/123456'); echo $request->getProperty(); // "properties/123456" ``` ``` -------------------------------- ### Instantiate AlphaAnalyticsDataClient Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/AlphaAnalyticsDataClient.md Creates a new instance of the AlphaAnalyticsDataClient with optional configuration. Use this to begin interacting with the API. ```php public function __construct(array|ClientOptions $options = []) ``` -------------------------------- ### Instantiate BetaAnalyticsDataClient with Service Account Authentication Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Shows how to authenticate using a service account by providing a ServiceAccountCredentials object. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\Auth\Credentials\ServiceAccountCredentials; $scopes = ['https://www.googleapis.com/auth/analytics.readonly']; $credentials = new ServiceAccountCredentials( $scopes, json_decode( file_get_contents('/path/to/service-account-key.json'), true ) ); $client = new BetaAnalyticsDataClient([ 'credentials' => $credentials, ]); ``` -------------------------------- ### offset Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Sets the starting row number for pagination. Used in conjunction with the limit parameter. ```APIDOC ## setOffset ### Description Sets the starting row number for pagination. This is a 0-based index. Used with `limit` for pagination. ### Method ```php public function setOffset(int $var): self ``` ### Parameters * **var** (int) - Required - The 0-based row number to start from. ### Constraints - Non-negative integer - Default: 0 ### Request Example ```php // Get rows 100-199 $request->setOffset(100); $request->setLimit(100); ``` ``` -------------------------------- ### Instantiate BetaAnalyticsDataClient with ClientOptions Object Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Instantiates the client using a ClientOptions object to configure the API endpoint. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Google\ApiCore\Options\ClientOptions; $options = new ClientOptions(); $options->setApiEndpoint('analyticsdata.googleapis.com:443'); $client = new BetaAnalyticsDataClient($options); ``` -------------------------------- ### Get Operations Client Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/BetaAnalyticsDataClient.md Returns the OperationsClient for managing long-running operations, such as creating audience exports. ```php public function getOperationsClient(): OperationsClient ``` -------------------------------- ### DateRanges Field Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Sets and gets the date ranges for the report data, allowing for period comparisons. ```APIDOC ## dateRanges ### getDateRanges ```php public function getDateRanges(): RepeatedField ``` ### setDateRanges ```php public function setDateRanges(array $var): self ``` Date ranges for the report data. Multiple date ranges can be used to compare periods. **Constraints:** - Required for standard reports - Unspecified for cohort requests - Dates in YYYY-MM-DD format - Start date must be before or equal to end date **Returns:** `RepeatedField` - Collection of date ranges **Example:** ```php use Google\Analytics\Data\V1beta\DateRange; // Single date range $request->setDateRanges([ new DateRange([ 'start_date' => '2024-01-01', 'end_date' => '2024-01-31', ]), ]); // Multiple date ranges for comparison $request->setDateRanges([ new DateRange([ 'start_date' => '2024-01-01', 'end_date' => '2024-01-31', ]), new DateRange([ 'start_date' => '2023-01-01', 'end_date' => '2023-01-31', ]), ]); ``` ``` -------------------------------- ### Metrics Field Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Sets and gets the metrics to measure in the report. Metrics are measurements of user activity. ```APIDOC ## metrics ### getMetrics ```php public function getMetrics(): RepeatedField ``` ### setMetrics ```php public function setMetrics(array $var): self ``` The metrics to measure. Metrics are measurements of user activity (like active users, screen pageviews). **Constraints:** - At least one metric is typically required for useful reports - Maximum recommended: 10 metrics **Returns:** `RepeatedField` - Collection of metrics **Example:** ```php use Google\Analytics\Data\V1beta\Metric; $request->setMetrics([ new Metric(['name' => 'activeUsers']), new Metric(['name' => 'screenPageViews']), new Metric(['name' => 'eventCount']), ]); ``` ``` -------------------------------- ### Set and Get Property Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Set the Google Analytics property identifier for the report request and retrieve it. ```php $request->setProperty('properties/123456'); echo $request->getProperty(); // "properties/123456" ``` -------------------------------- ### Instantiate RunReportRequest Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportRequest.md Create a new RunReportRequest object and initialize it with property, dimensions, metrics, and date ranges. ```php use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\DateRange; $request = new RunReportRequest([ 'property' => 'properties/123456', 'dimensions' => [ new Dimension(['name' => 'country']), ], 'metrics' => [ new Metric(['name' => 'activeUsers']), ], 'date_ranges' => [ new DateRange([ 'start_date' => '2024-01-01', 'end_date' => '2024-01-31', ]), ], ]); ``` -------------------------------- ### GetAudienceExportRequest Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/types.md Request to get a specific audience export. This operation requires the resource name of the audience export. ```APIDOC ## GetAudienceExportRequest ### Description Request to get an audience export. ### Parameters #### Path Parameters - **name** (string) - Yes - Resource name of the audience export ``` -------------------------------- ### Configure Logging Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Integrate Monolog for detailed logging of client operations. This snippet shows how to create a logger instance and push it to the client configuration. ```php use Google\Analytics\Data\V1beta\Client\BetaAnalyticsDataClient; use Monolog\Logger; use Monolog\Handler\StreamHandler; $logger = new Logger('analytics'); $logger->pushHandler(new StreamHandler('php://stderr', Logger::DEBUG)); $client = new BetaAnalyticsDataClient([ 'logger' => $logger, ]); ``` -------------------------------- ### Constructor Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/AlphaAnalyticsDataClient.md Creates a new instance of the AlphaAnalyticsDataClient with optional configuration. Accepts an array of options or a ClientOptions object. ```APIDOC ## Constructor ```php public function __construct(array|ClientOptions $options = []) ``` ### Description Creates a new instance of the AlphaAnalyticsDataClient with optional configuration. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | array|ClientOptions | No | [] | Configuration options for the client | ### Options Array Structure Same as BetaAnalyticsDataClient. See [BetaAnalyticsDataClient](BetaAnalyticsDataClient.md) constructor for details. ### Throws - `ValidationException` - If client options are invalid ``` -------------------------------- ### DateRange Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/types.md A date range for report analysis. This type defines the start and end dates for a reporting period. ```APIDOC ## DateRange ### Description A date range for report analysis. This type defines the start and end dates for a reporting period. ### Fields - **startDate** (string) - Required - Start date in YYYY-MM-DD format - **endDate** (string) - Required - End date in YYYY-MM-DD format ``` -------------------------------- ### Sorting Report Results Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Define sorting criteria for report results. This example sorts by 'screenPageViews' in descending order. ```php use Google\Analytics\Data\V1beta\OrderBy; use Google\Analytics\Data\V1beta\OrderByMetric; $orderBy = (new OrderBy()) ->setMetric(new OrderByMetric(['metric_name' => 'screenPageViews'])) ->setDesc(true); // Descending $request->setOrderBys([$orderBy]); ``` -------------------------------- ### Run Report with Pagination, Filtering, Sorting, and Quota Check Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Demonstrates how to construct and execute a `runReport` request, including setting dimensions, metrics, date ranges, pagination limits and offsets, dimension and metric filters, sorting, and optionally returning property quota information. It also includes error handling for API exceptions, specifically addressing quota exhaustion. ```APIDOC ## Run Report with Pagination, Filtering, Sorting, and Quota Check ### Description This example shows how to use the `runReport` method to fetch analytics data. It includes configurations for pagination, filtering by dimensions and metrics, sorting the results, and checking property quotas. Error handling for `ApiException` is also demonstrated, with a specific retry mechanism for quota exceeded errors. ### Method `runReport` ### Endpoint (Not applicable for SDK methods) ### Parameters #### Request Body (Implicit via `RunReportRequest` object) - **property** (string) - Required - The property to retrieve data for (e.g., 'properties/123456'). - **dimensions** (array) - Optional - Dimensions to break down metrics by. - **metrics** (array) - Optional - Metrics to measure user activity. - **dateRanges** (array) - Optional - Time periods to analyze. - **limit** (integer) - Optional - Rows per page for pagination. - **offset** (integer) - Optional - Starting row for pagination. - **dimensionFilter** (FilterExpression) - Optional - Conditions to include/exclude data based on dimensions. - **metricFilter** (FilterExpression) - Optional - Conditions to include/exclude data based on metrics. - **orderBys** (array of OrderBy) - Optional - Criteria for sorting the report results. - **returnPropertyQuota** (boolean) - Optional - If true, includes property quota information in the response. ### Request Example ```php use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient; use Google\Analytics\Data\V1beta\RunReportRequest; use Google\Analytics\Data\V1beta\Dimension; use Google\Analytics\Data\V1beta\Metric; use Google\Analytics\Data\V1beta\DateRange; use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Filter; use Google\Analytics\Data\V1beta\StringFilter; use Google\Analytics\Data\V1beta\NumericFilter; use Google\Analytics\Data\V1beta\OrderBy; use Google\Analytics\Data\V1beta\OrderByMetric; use Google\ApiCore\ApiException; // Assuming $client is an authenticated BetaAnalyticsDataClient instance $request = (new RunReportRequest()) ->setProperty('properties/123456') ->setDimensions([ new Dimension(['name' => 'country']), new Dimension(['name' => 'city']) ]) ->setMetrics([ new Metric(['name' => 'activeUsers']), new Metric(['name' => 'screenPageViews']) ]) ->setDateRanges([ new DateRange(['start_date' => '2023-01-01', 'end_date' => 'today']) ]) ->setLimit(10000) ->setOffset(0) ->setDimensionFilter( (new FilterExpression()) ->setFilter( (new Filter()) ->setFieldName('country') ->setStringFilter( (new StringFilter()) ->setMatchType('EXACT') ->setValue('United States') ) ) ) ->setMetricFilter( (new FilterExpression()) ->setFilter( (new Filter()) ->setFieldName('activeUsers') ->setNumericFilter( (new NumericFilter()) ->setOperation('GREATER_THAN') ->setValue(100) ) ) ) ->setOrderBys([ (new OrderBy()) ->setMetric(new OrderByMetric(['metric_name' => 'screenPageViews'])) ->setDesc(true) // Descending ]) ->setReturnPropertyQuota(true); try { $response = $client->runReport($request); // Process the report data foreach ($response->getRows() as $row) { // ... } // Check quota $quota = $response->getPropertyQuota(); $daily = $quota->getTokensPerDay(); echo "Daily tokens: " . $daily->getConsumed() . " / " . $daily->getLimit(); } catch (ApiException $ex) { // Handle API exceptions $code = $ex->getCode(); if ($code == 8) { // RESOURCE_EXHAUSTED (quota exceeded) sleep(60); // Retry the request $response = $client->runReport($request); } else { // Handle other errors echo "Error: " . $ex->getMessage(); } } ``` ### Response #### Success Response - **rows** (array) - The report data, with each row containing dimension and metric values. - **dimensionHeaders** (array) - Headers for the dimensions. - **metricHeaders** (array) - Headers for the metrics. - **propertyQuota** (PropertyQuota) - Quota information for the property, if `returnPropertyQuota` was true. - **metadata** (ResponseMetaData) - Metadata about the response. #### Response Example ```json { "rows": [ { "dimensionValues": { "value": ["United States", "New York"] }, "metricValues": { "value": ["150", "300"] } } ], "dimensionHeaders": [ {"name": "country"}, {"name": "city"} ], "metricHeaders": [ {"name": "activeUsers"}, {"name": "screenPageViews"} ], "propertyQuota": { "tokensPerDay": { "consumed": 5000, "limit": 10000 } }, "metadata": { "currencyCode": "USD", "timeZone": "America/Los_Angeles" } } ``` ### Error Handling - **`Google\ApiCore\ApiException`**: Thrown on API errors. - **Code 3 (INVALID_ARGUMENT)**: Bad parameters provided. - **Code 5 (NOT_FOUND)**: Resource not found. - **Code 7 (PERMISSION_DENIED)**: Authentication or authorization failed. - **Code 8 (RESOURCE_EXHAUSTED)**: Quota exceeded. Implement retry logic (e.g., `sleep(60)`). - **Code 14 (UNAVAILABLE)**: Service is down. ``` -------------------------------- ### Reuse Client Instance for Connection Pooling Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/configuration.md Demonstrates the correct way to reuse a BetaAnalyticsDataClient instance to improve performance in high-load scenarios by avoiding new connections per request. ```php // Bad: Creates new connection per request foreach ($requests as $request) { $client = new BetaAnalyticsDataClient(); $response = $client->runReport($request); } // Good: Reuse client $client = new BetaAnalyticsDataClient(); foreach ($requests as $request) { $response = $client->runReport($request); } ``` -------------------------------- ### Get Audience List Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/AlphaAnalyticsDataClient.md Retrieves configuration metadata for a specific audience list using its name. Requires a GetAudienceListRequest. ```php public function getAudienceList(GetAudienceListRequest $request, array $callOptions = []): AudienceList ``` -------------------------------- ### Kind Accessors Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/api-reference/ReportResponse.md Methods to get and set the 'kind' property, which identifies the response type. This is a fixed string value. ```APIDOC ## getKind ### Description Retrieves the fixed string identifying the response type. ### Method ```php public function getKind(): string ``` ### Returns - string: The response type identifier, always "analyticsData#runReport". ## setKind ### Description Sets the fixed string identifying the response type. ### Method ```php public function setKind(string $var): self ``` ### Parameters - **var** (string) - Required - The response type identifier to set. ### Value Always `"analyticsData#runReport"` ``` -------------------------------- ### Run Report with Pagination Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Construct a report request, setting limits and offsets for pagination. Fetch subsequent pages by adjusting the offset. ```php $request = (new RunReportRequest()) ->setProperty('properties/123456') ->setDimensions([...]) ->setMetrics([...]) ->setDateRanges([...]) ->setLimit(10000) // Rows per page ->setOffset(0); // Starting row $response = $client->runReport($request); // If rowCount > limit, fetch next page: $request->setOffset(10000); $response = $client->runReport($request); ``` -------------------------------- ### Dimension Filtering for Reports Source: https://github.com/googleapis/php-analytics-data/blob/main/_autodocs/README.md Apply dimension filters to narrow down report results, similar to a WHERE clause. This example filters by country. ```php use Google\Analytics\Data\V1beta\FilterExpression; use Google\Analytics\Data\V1beta\Filter; use Google\Analytics\Data\V1beta\StringFilter; $dimensionFilter = (new FilterExpression()) ->setFilter((new Filter()) ->setFieldName('country') ->setStringFilter((new StringFilter()) ->setMatchType('EXACT') ->setValue('United States') ) ); $request->setDimensionFilter($dimensionFilter); ```