### List Properties Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Provides a code example for listing properties associated with a specific account. This method supports pagination. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); try { $properties = $analyticsAdminServiceClient->listProperties('accounts/12345'); foreach ($properties->iterateAllElements() as $property) { print_r($property); } } catch (Exception $e) { echo 'Error listing properties: ' . $e->getMessage(); } ``` -------------------------------- ### Install Google Analytics Admin Client Source: https://github.com/googleapis/php-analytics-admin/blob/main/README.md Installs the Google Analytics Admin client library using Composer. ```sh composer require google/analytics-admin ``` -------------------------------- ### Configuration Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/README.md Details on client setup and configuration options, including credentials, transport settings (gRPC vs REST), retry policies, logging, monitoring, and environment variable usage, with complete configuration examples. ```APIDOC ## Configuration ### Description This section covers the necessary steps and options for setting up and configuring the Google Analytics Admin API client library. ### Options - Credentials configuration - Transport options (gRPC vs REST) - Retry settings - Logging and monitoring - Environment variables - Complete configuration examples ``` -------------------------------- ### Get Account Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Provides a code example for retrieving a specific Google Analytics account. Ensure you have the necessary permissions and the account ID. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); try { $response = $analyticsAdminServiceClient->getAccount('accounts/12345'); print_r($response); } catch (Exception $e) { echo 'Error getting account: ' . $e->getMessage(); } ``` -------------------------------- ### Run Access Report Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Demonstrates how to run an access report for a property. This is used to retrieve data about user access and behavior. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\RunAccessReportRequest; use Google\Analytics\Admin\V1beta\DateRange; use Google\Analytics\Admin\V1beta\Dimension; use Google\Analytics\Admin\V1beta\Metric; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $request = new RunAccessReportRequest(); $request->setProperty('properties/12345'); $request->setDateRanges([ (new DateRange())->setStartDate('2023-01-01')->setEndDate('today'), ]); $request->setDimensions([ (new Dimension())->setName('country'), ]); $request->setMetrics([ (new Metric())->setName('activeUsers'), ]); try { $response = $analyticsAdminServiceClient->runAccessReport($request); foreach ($response->getRows() as $row) { print_r($row); } } catch (Exception $e) { echo 'Error running access report: ' . $e->getMessage(); } ``` -------------------------------- ### Create a Data Stream Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Example for creating a new data stream (e.g., for a website) within a property. ```php require 'vendor/autoload.php'; use Google\\Analytics\\Admin\\\\V1beta\\\\AnalyticsAdminServiceClient; use Google\\\\Analytics\\Admin\\\\V1beta\\\\DataStream; $client = new AnalyticsAdminServiceClient(); $parent = 'properties/12345'; // Replace with your property ID $dataStream = new DataStream(); $dataStream->setDisplayName('My Website Stream'); $dataStream->setWebStreamDataStream(new DataStream\WebStreamDataStream()); $newDataStream = $client->createDataStream(['parent' => $parent, 'dataStream' => $dataStream]); printf('Created data stream: %s\n', $newDataStream->getName()); ``` -------------------------------- ### Create Account Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Shows the process of creating a new Google Analytics account. This requires specifying the account details in the request object. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\Account; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $account = new Account(); $account->setDisplayName('My New Account'); $account->setIndustryCategory('OTHER'); $account->setRegionCode('US'); try { $newAccount = $analyticsAdminServiceClient->createAccount($account); print_r($newAccount); } catch (Exception $e) { echo 'Error creating account: ' . $e->getMessage(); } ``` -------------------------------- ### Create a Custom Metric Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Example for creating a custom metric for a property. ```php require 'vendor/autoload.php'; use Google\\Analytics\\Admin\\\\V1beta\\\\AnalyticsAdminServiceClient; use Google\\\\Analytics\\Admin\\\\V1beta\\\\CustomMetric; $client = new AnalyticsAdminServiceClient(); $parent = 'properties/12345'; // Replace with your property ID $customMetric = new CustomMetric(); $customMetric->setDisplayName('Video Plays'); $customMetric->setParameterName('video_plays'); // e.g., 'video_plays' $customMetric->setMeasurementUnit(CustomMetric::MEASUREMENT_UNIT_STANDARD); $customMetric->setScope(CustomMetric::SCOPE_EVENT); $newCustomMetric = $client->createCustomMetric(['parent' => $parent, 'customMetric' => $customMetric]); printf('Created custom metric: %s\n', $newCustomMetric->getName()); ``` -------------------------------- ### Client Configuration Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/INDEX.md Comprehensive guide on configuring the client, including options for credentials, transport, retries, and logging. ```APIDOC ## Client Configuration This section details how to configure the API client for various scenarios. ### Configuration Options Refer to [configuration.md](configuration.md) for documentation on: - `ClientOptions` parameters - Credentials configuration - Transport selection (gRPC vs REST) - Retry settings - Logging configuration - Call-level options - Environment variables - Complete usage examples ``` -------------------------------- ### Search Change History Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Shows how to search the change history for a property. This is useful for auditing and understanding recent modifications. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); try { $response = $analyticsAdminServiceClient->searchChangeHistoryEvents('properties/12345'); foreach ($response->getChangeHistoryEvents() as $event) { print_r($event); } } catch (Exception $e) { echo 'Error searching change history: ' . $e->getMessage(); } ``` -------------------------------- ### Set up Measurement Protocol Data Streams Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Demonstrates the prerequisites and setup for using the Measurement Protocol, which allows sending data directly to Google Analytics. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\MeasurementProtocolSecret; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $secret = new MeasurementProtocolSecret(); $secret->setDisplayName('My Web Stream Secret'); try { // First, ensure you have a web data stream created. // $webStream = $analyticsAdminServiceClient->createWebDataStream(...); // Then, create a secret for it: $newSecret = $analyticsAdminServiceClient->createMeasurementProtocolSecret('properties/12345/dataStreams/67890', $secret); echo 'Measurement Protocol secret created: ' . $newSecret->getSecretValue(); } catch (Exception $e) { echo 'Error setting up Measurement Protocol: ' . $e->getMessage(); } ``` -------------------------------- ### Create Web Data Stream Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Illustrates creating a web data stream for a property. This involves specifying the parent property and web stream details. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\WebDataStream; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $webDataStream = new WebDataStream(); $webDataStream->setDisplayName('My Web Stream'); $webDataStream->setWebStreamData(['default_uri' => 'https://example.com']); try { $newStream = $analyticsAdminServiceClient->createWebDataStream('properties/12345', $webDataStream); print_r($newStream); } catch (Exception $e) { echo 'Error creating web data stream: ' . $e->getMessage(); } ``` -------------------------------- ### Full Method Documentation Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/INDEX.md Complete documentation for all API methods, including detailed parameter descriptions and usage examples. ```APIDOC ## Full Method Documentation This section provides exhaustive documentation for every method available in the API. ### Accessing Method Details Refer to [AnalyticsAdminServiceClient.md](api-reference/AnalyticsAdminServiceClient.md) for: - The complete signature of each method with all parameters - Detailed descriptions for each parameter - Comprehensive usage examples - Signatures for asynchronous methods ``` -------------------------------- ### Create iOS Data Stream Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Shows how to create an iOS data stream for a property. Requires specifying the parent property and iOS stream details like bundle ID. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\ IosAppDataStream; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $iosAppStream = new IosAppDataStream(); $iosAppStream->setDisplayName('My iOS App Stream'); $iosAppStream->setBundleId('com.example.iosapp'); try { $newStream = $analyticsAdminServiceClient->createIosAppDataStream('properties/12345', $iosAppStream); print_r($newStream); } catch (Exception $e) { echo 'Error creating iOS data stream: ' . $e->getMessage(); } ``` -------------------------------- ### Complete Google Analytics Admin Client Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/configuration.md Demonstrates comprehensive client initialization with custom credentials, logging, and API endpoint configuration. Includes making an API call with specific call options and error handling. ```php use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\GetAccountRequest; use Google\Auth\Credentials\ServiceAccountCredentials; use Google\ApiCore\Options\ClientOptions; use Google\ApiCore\RetrySettings; use Monolog\Logger; use Monolog\Handlers\StreamHandler; // Set up logging $logger = new Logger('analytics-admin'); $logger->pushHandler(new StreamHandler('php://stderr', Logger::INFO)); // Create credentials $scopes = [ 'https://www.googleapis.com/auth/analytics.readonly', ]; $keyFile = '/path/to/service-account-key.json'; $keyJson = json_decode(file_get_contents($keyFile), true); $credentials = new ServiceAccountCredentials($scopes, $keyJson); // Create client with comprehensive configuration $options = new ClientOptions([ 'credentials' => $credentials, 'apiEndpoint' => 'analyticsadmin.googleapis.com:443', 'transport' => 'grpc', // or 'rest' 'logger' => $logger, 'universeDomain' => 'googleapis.com', ]); $client = new AnalyticsAdminServiceClient($options); // Make API call with call-specific options $request = (new GetAccountRequest()) ->setName('accounts/100'); $callOptions = [ 'retrySettings' => new RetrySettings([ 'maxAttempts' => 3, 'initialRetryDelayMillis' => 100, 'maxRetryDelayMillis' => 5000, 'totalTimeoutMillis' => 30000, ]), ]; try { $account = $client->getAccount($request, $callOptions); echo "Account: " . $account->getDisplayName(); } catch (\Google\ApiCore\ApiException $ex) { $logger->error("API Error: " . $ex->getMessage()); } ``` -------------------------------- ### Create Custom Metric Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Illustrates creating a custom metric for a property. Requires specifying the parent property and metric details like name and type. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\CustomMetric; use Google\Analytics\Admin\V1beta\CustomMetricScopeEnum; use Google\Analytics\Admin\V1beta\CustomMetric\MeasurementUnit; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $customMetric = new CustomMetric(); $customMetric->setDisplayName('Video Plays'); $customMetric->setScope(CustomMetricScopeEnum::EVENT_SCOPE); $customMetric->setMeasurementUnit(MeasurementUnit::COUNT); $customMetric->setParameterName('video_plays'); // e.g., for event parameters try { $newMetric = $analyticsAdminServiceClient->createCustomMetric('properties/12345', $customMetric); print_r($newMetric); } catch (Exception $e) { echo 'Error creating custom metric: ' . $e->getMessage(); } ``` -------------------------------- ### Create a Google Analytics Account Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Example of creating a new Google Analytics account using the API. ```php require 'vendor/autoload.php'; use Google\\Analytics\\Admin\\\\V1beta\\\\AnalyticsAdminServiceClient; use Google\\\\Analytics\\Admin\\\\V1beta\\\\Account; $client = new AnalyticsAdminServiceClient(); $account = new Account(); $account->setDisplayName('My New Account'); $account->setIndustryCategory('TECHNOLOGY'); $newAccount = $client->createAccount($account); printf('Created account: %s\n', $newAccount->getName()); ``` -------------------------------- ### Create Android Data Stream Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Demonstrates creating an Android data stream for a property. Requires specifying the parent property and Android stream details like package name. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\AndroidAppDataStream; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $androidAppStream = new AndroidAppDataStream(); $androidAppStream->setDisplayName('My Android App Stream'); $androidAppStream->setPackageName('com.example.androidapp'); try { $newStream = $analyticsAdminServiceClient->createAndroidAppDataStream('properties/12345', $androidAppStream); print_r($newStream); } catch (Exception $e) { echo 'Error creating Android data stream: ' . $e->getMessage(); } ``` -------------------------------- ### Exponential Backoff Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Illustrates the concept of exponential backoff in API request retries. ```php // This is handled automatically by the client library's retry settings. // The 'retry_settings' array in the client constructor configures: // - initial_retry_delay: The first delay after a failed request. // - retry_delay_multiplier: Factor by which the delay increases. // - max_retry_delay: The maximum delay between retries. // Example configuration (see previous snippet for full context): $client = new AnalyticsAdminServiceClient([ 'retry_settings' => [ 'initial_retry_delay' => '1s', 'retry_delay_multiplier' => 2.0, // Doubles the delay each time 'max_retry_delay' => '30s' ] ]); ``` -------------------------------- ### Delete Account Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Provides a code example for deleting a Google Analytics account. Note that deleted accounts cannot be recovered. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); try { $analyticsAdminServiceClient->deleteAccount('accounts/12345'); echo 'Account deleted successfully.'; } catch (Exception $e) { echo 'Error deleting account: ' . $e->getMessage(); } ``` -------------------------------- ### Example Usage of GetAccountRequest Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Request-Response-Types.md Demonstrates how to build and use a GetAccountRequest to fetch an Account resource using the AnalyticsAdminServiceClient. Ensure the account name is correctly formatted. ```php use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\GetAccountRequest; $client = new AnalyticsAdminServiceClient(); $request = GetAccountRequest::build( AnalyticsAdminServiceClient::accountName('100') ); $account = $client->getAccount($request); ``` -------------------------------- ### Example Usage of CreatePropertyRequest Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Request-Response-Types.md Demonstrates how to instantiate and populate a CreatePropertyRequest to create a new website property. Ensure the parent account exists and property details like displayName and timeZone are provided. ```php use Google\Analytics\Admin\V1beta\CreatePropertyRequest; use Google\Analytics\Admin\V1beta\Property; $property = new Property(); $property->setDisplayName('My Website') ->setTimeZone('America/Los_Angeles') ->setCurrencyCode('USD'); $request = new CreatePropertyRequest(); $request->setParent(AnalyticsAdminServiceClient::accountName('100')) ->setProperty($property); $newProperty = $client->createProperty($request); ``` -------------------------------- ### Create a Web Property Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Example for creating a new web property within a Google Analytics account. ```php require 'vendor/autoload.php'; use Google\\Analytics\\Admin\\\\V1beta\\\\AnalyticsAdminServiceClient; use Google\\\\Analytics\\Admin\\\\V1beta\\\\Property; $client = new AnalyticsAdminServiceClient(); $property = new Property(); $property->setDisplayName('My Website'); $property->setIndustryCategory('OTHER'); $property->setWebsiteUrl('https://example.com'); $newProperty = $client->createProperty($property); printf('Created property: %s\n', $newProperty->getName()); ``` -------------------------------- ### Create a Custom Dimension Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Example for creating a custom dimension for a property. ```php require 'vendor/autoload.php'; use Google\\Analytics\\Admin\\\\V1beta\\\\AnalyticsAdminServiceClient; use Google\\\\Analytics\\Admin\\\\V1beta\\\\CustomDimension; $client = new AnalyticsAdminServiceClient(); $parent = 'properties/12345'; // Replace with your property ID $customDimension = new CustomDimension(); $customDimension->setDisplayName('User Type'); $customDimension->setParameterName('user_type'); // e.g., 'user_type' $customDimension->setScope(CustomDimension::SCOPE_USER); $newCustomDimension = $client->createCustomDimension(['parent' => $parent, 'customDimension' => $customDimension]); printf('Created custom dimension: %s\n', $newCustomDimension->getName()); ``` -------------------------------- ### Create Property Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Illustrates how to create a new Google Analytics property. Requires specifying property details like display name and industry category. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\Property; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $property = new Property(); $property->setDisplayName('My New Property'); $property->setIndustryCategory('OTHER'); $property->setAccount('accounts/12345'); // Parent account try { $newProperty = $analyticsAdminServiceClient->createProperty($property); print_r($newProperty); } catch (Exception $e) { echo 'Error creating property: ' . $e->getMessage(); } ``` -------------------------------- ### List Accounts Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Illustrates how to list all Google Analytics accounts accessible to the authenticated user. This method supports pagination for large result sets. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); try { $accounts = $analyticsAdminServiceClient->listAccounts(); foreach ($accounts->iterateAllElements() as $account) { print_r($account); } } catch (Exception $e) { echo 'Error listing accounts: ' . $e->getMessage(); } ``` -------------------------------- ### Common Patterns Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/INDEX.md Provides real-world code examples organized by feature, helping users with common tasks like managing accounts, properties, and dimensions. ```APIDOC ## Common Patterns This section provides real-world code examples for common tasks. ### Usage Refer to [Common-Patterns.md](api-reference/Common-Patterns.md) for examples on: - Accounts management - Properties management - Dimensions and metrics - And more... ``` -------------------------------- ### Create Custom Dimension Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Shows how to create a custom dimension for a property. Requires specifying the parent property and dimension details like name and scope. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\CustomDimension; use Google\Analytics\Admin\V1beta\CustomDimensionScopeEnum; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $customDimension = new CustomDimension(); $customDimension->setDisplayName('User Type'); $customDimension->setScope(CustomDimensionScopeEnum::PROPERTY_SCOPE); $customDimension->setParameterName('user_type'); // e.g., for event parameters try { $newDimension = $analyticsAdminServiceClient->createCustomDimension('properties/12345', $customDimension); print_r($newDimension); } catch (Exception $e) { echo 'Error creating custom dimension: ' . $e->getMessage(); } ``` -------------------------------- ### Link Google Ads Account Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Shows how to link a Google Ads account to a Google Analytics property. This enables data sharing between the two platforms. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\GoogleAdsLink; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $googleAdsLink = new GoogleAdsLink(); $googleAdsLink->setGoogleAdsAccountId('123-456-7890'); // Your Google Ads Customer ID try { $newLink = $analyticsAdminServiceClient->createGoogleAdsLink('properties/12345', $googleAdsLink); print_r($newLink); } catch (Exception $e) { echo 'Error linking Google Ads account: ' . $e->getMessage(); } ``` -------------------------------- ### Update Account Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Demonstrates how to update an existing Google Analytics account. Only fields provided in the request will be updated. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\Account; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $account = new Account(); $account->setName('accounts/12345'); // Resource name of the account to update $account->setDisplayName('Updated Account Name'); try { $updatedAccount = $analyticsAdminServiceClient->updateAccount($account); print_r($updatedAccount); } catch (Exception $e) { echo 'Error updating account: ' . $e->getMessage(); } ``` -------------------------------- ### Get Google Analytics Account Information Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/README.md Initialize the client and retrieve account details. Ensure GOOGLE_APPLICATION_CREDENTIALS environment variable is set for authentication. ```php use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\GetAccountRequest; // Initialize client (uses GOOGLE_APPLICATION_CREDENTIALS) $client = new AnalyticsAdminServiceClient(); // Get account information $accountName = AnalyticsAdminServiceClient::accountName('100'); $request = (new GetAccountRequest())->setName($accountName); try { $account = $client->getAccount($request); echo "Account: " . $account->getDisplayName(); } catch (\Google\ApiCore\ApiException $ex) { echo "Error: " . $ex->getMessage(); } ``` -------------------------------- ### Method Patterns Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/README.md Explains the consistent patterns for common API operations like Get, List, Create, Update, Delete, and Archive, along with their expected return types. ```APIDOC ## Method Patterns All API methods follow consistent patterns: **Get operations** return the single resource: ```php $account = $client->getAccount($request); // Returns: Account ``` **List operations** return paginated results: ```php $response = $client->listAccounts($request); // Returns: PagedListResponse foreach ($response as $account) { ... } ``` **Create operations** return the created resource: ```php $property = $client->createProperty($request); // Returns: Property ``` **Update operations** return the updated resource: ```php $updated = $client->updateProperty($request); // Returns: Property ``` **Delete operations** return void or the deleted resource: ```php $client->deleteDataStream($request); // Returns: void ``` **Archive operations** archive custom dimensions/metrics instead of deleting: ```php $client->archiveCustomDimension($request); // Returns: void ``` ``` -------------------------------- ### Archive Property Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Shows how to archive a Google Analytics property. Archived properties stop collecting data but historical data is retained. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); try { $analyticsAdminServiceClient->archiveProperty('properties/12345'); echo 'Property archived successfully.'; } catch (Exception $e) { echo 'Error archiving property: ' . $e->getMessage(); } ``` -------------------------------- ### Example Usage of ListAccountsRequest in PHP Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Request-Response-Types.md Demonstrates how to instantiate and use the ListAccountsRequest to fetch a list of Google Analytics accounts. It shows setting the page size and iterating through the response. ```php use Google\Analytics\Admin\V1beta\ListAccountsRequest; $request = new ListAccountsRequest(); $request->setPageSize(50); $response = $client->listAccounts($request); foreach ($response as $account) { echo $account->getDisplayName() . "\n"; } ``` -------------------------------- ### Handle FAILED_PRECONDITION for Measurement Protocol Secret Creation Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/errors.md This example demonstrates how to handle FAILED_PRECONDITION errors, which occur when prerequisites like acknowledging user data collection are not met before creating a measurement protocol secret. ```php try { // Must acknowledge user data collection first $request = (new CreateMeasurementProtocolSecretRequest()) ->setParent('properties/1000/dataStreams/2000') ->setMeasurementProtocolSecret(new MeasurementProtocolSecret()); $client->createMeasurementProtocolSecret($request); } catch (ApiException $ex) { if ($ex->getStatus() === 'FAILED_PRECONDITION') { echo "Prerequisites not met: " . $ex->getMessage(); // Acknowledge user data collection first $ackRequest = (new AcknowledgeUserDataCollectionRequest()) ->setProperty('properties/1000'); $client->acknowledgeUserDataCollection($ackRequest); } } ``` -------------------------------- ### Update Property Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Request-Response-Types.md Demonstrates how to update a property using the UpdatePropertyRequest. This involves retrieving the current property, modifying its fields, and then creating a request with the updated property and an update mask. ```php use Google\Analytics\Admin\V1beta\UpdatePropertyRequest; use Google\Protobuf\FieldMask; $property = $client->getProperty($getRequest); $property->setDisplayName('New Name'); $request = new UpdatePropertyRequest(); $request->setProperty($property) ->setUpdateMask(new FieldMask(['paths' => ['display_name']])); $updated = $client->updateProperty($request); ``` -------------------------------- ### Basic Error Handling with ApiException Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Common-Patterns.md Implement basic error handling for API calls using a try-catch block to catch ApiException. This example demonstrates logging the error and handling specific status codes like NOT_FOUND, PERMISSION_DENIED, and INVALID_ARGUMENT. ```php use Google\ApiCore\ApiException; try { $account = $client->getAccount($request); } catch (ApiException $ex) { // Log error error_log("API Error: " . $ex->getStatus() . " - " . $ex->getMessage()); // Handle by status code switch ($ex->getStatus()) { case 'NOT_FOUND': echo "Resource not found"; break; case 'PERMISSION_DENIED': echo "Access denied - check credentials"; break; case 'INVALID_ARGUMENT': echo "Invalid request data"; break; default: throw $ex; } } ``` -------------------------------- ### Initialize Client with Service Account Key Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Common-Patterns.md This method allows authentication using a service account key file. Ensure you have the correct scopes defined for your operations. ```php use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; use Google\Auth\Credentials\ServiceAccountCredentials; use Google\ApiCore\Options\ClientOptions; $scopes = [ 'https://www.googleapis.com/auth/analytics.edit', 'https://www.googleapis.com/auth/analytics.readonly', ]; $serviceAccountJson = json_decode( file_get_contents('/path/to/service-account-key.json'), true ); $credentials = new ServiceAccountCredentials($scopes, $serviceAccountJson); $options = new ClientOptions(['credentials' => $credentials]); $client = new AnalyticsAdminServiceClient($options); ``` -------------------------------- ### Handle INTERNAL Server Error Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/errors.md This example demonstrates handling INTERNAL server errors, which indicate unexpected backend issues. It advises retrying with exponential backoff and contacting support if the problem persists. ```php try { $response = $client->getAccount($request); } catch (ApiException $ex) { if ($ex->getStatus() === 'INTERNAL') { echo "Internal server error. Contact support if problem persists."; // Implement retry with backoff } } ``` -------------------------------- ### Comprehensive Error Handling for getAccountWithRetry Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/errors.md Implement detailed error handling for API calls, distinguishing between ValidationException and ApiException. This example shows how to manage specific ApiException status codes like NOT_FOUND, PERMISSION_DENIED, and handles retries for transient errors like UNAVAILABLE or INTERNAL. ```php use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\GetAccountRequest; use Google\Analytics\Admin\V1beta\CreatePropertyRequest; use Google\Analytics\Admin\V1beta\Property; use Google\ApiCore\ApiException; use Google\ApiCore\ValidationException; class AnalyticsAdminWrapper { private $client; private $maxRetries = 3; public function __construct(AnalyticsAdminServiceClient $client) { $this->client = $client; } public function getAccountWithRetry(string $accountId, int $attempt = 0): Account { try { $accountName = AnalyticsAdminServiceClient::accountName($accountId); $request = (new GetAccountRequest())->setName($accountName); return $this->client->getAccount($request); } catch (ValidationException $ex) { // Validation errors are not retryable throw new \RuntimeException("Invalid account ID: " . $ex->getMessage()); } catch (ApiException $ex) { // Handle specific error codes switch ($ex->getStatus()) { case 'NOT_FOUND': throw new \RuntimeException("Account not found: $accountId"); case 'PERMISSION_DENIED': throw new \RuntimeException("Insufficient permissions for account: $accountId"); case 'INVALID_ARGUMENT': throw new \RuntimeException("Invalid request: " . $ex->getMessage()); case 'UNAVAILABLE': case 'DEADLINE_EXCEEDED': // Retry with exponential backoff if ($attempt < $this->maxRetries) { $delay = min(pow(2, $attempt) * 1000, 32000); // Cap at 32s usleep($delay * 1000); return $this->getAccountWithRetry($accountId, $attempt + 1); } throw new \RuntimeException("API unavailable after $this->maxRetries attempts"); case 'RESOURCE_EXHAUSTED': throw new \RuntimeException("Quota exceeded. Please try again later."); case 'INTERNAL': if ($attempt < $this->maxRetries) { $delay = min(pow(2, $attempt) * 1000, 32000); usleep($delay * 1000); return $this->getAccountWithRetry($accountId, $attempt + 1); } throw new \RuntimeException("Internal server error after $this->maxRetries attempts"); default: throw new \RuntimeException( "Unexpected error: " . $ex->getStatus() . " - " . $ex->getMessage() ); } } } public function createPropertySafe(string $accountId, array $propertyData): Property { try { $property = new Property(); $property->setDisplayName($propertyData['displayName']) ->setTimeZone($propertyData['timeZone']) ->setCurrencyCode($propertyData['currencyCode'] ?? 'USD'); $accountName = AnalyticsAdminServiceClient::accountName($accountId); $request = (new CreatePropertyRequest()) ->setParent($accountName) ->setProperty($property); return $this->client->createProperty($request); } catch (ApiException $ex) { switch ($ex->getStatus()) { case 'INVALID_ARGUMENT': throw new \InvalidArgumentException( "Invalid property configuration: " . $ex->getMessage() ); case 'FAILED_PRECONDITION': throw new \RuntimeException( "Cannot create property - prerequisites not met: " . $ex->getMessage() ); case 'NOT_FOUND': throw new \RuntimeException("Account not found: $accountId"); case 'PERMISSION_DENIED': throw new \RuntimeException("Insufficient permissions to create property"); default: throw $ex; } } } } ``` -------------------------------- ### Get Resource Request Type Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/types.md All Get*Request types require a 'name' field containing the fully-qualified resource name. This example shows the structure for GetAccountRequest. ```php class GetAccountRequest extends \Google\Protobuf\Internal\Message { protected $name = ''; public function getName() public function setName($var) } ``` -------------------------------- ### Handle UNAVAILABLE Error for Temporary Service Issues Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/errors.md This code example shows how to detect and handle UNAVAILABLE errors, which signal temporary API service disruptions. It includes a basic retry mechanism. ```php try { $response = $client->getAccount($request); } catch (ApiException $ex) { if ($ex->getStatus() === 'UNAVAILABLE') { echo "API temporarily unavailable. Retrying..."; // Implement automatic retry sleep(5); // Retry logic here } } ``` -------------------------------- ### Initialize Client with ClientOptions Object Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/configuration.md Instantiate the AnalyticsAdminServiceClient using a ClientOptions object, specifying various configuration parameters. ```php use Google\ApiCore\Options\ClientOptions; $options = new ClientOptions([ 'apiEndpoint' => 'analyticsadmin.googleapis.com:443', 'credentials' => $credentialsWrapper, 'transport' => 'grpc', // ... other options ]); $client = new AnalyticsAdminServiceClient($options); ``` -------------------------------- ### Delete Property Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Provides a code example for deleting a Google Analytics property. Deleted properties cannot be recovered. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); try { $analyticsAdminServiceClient->deleteProperty('properties/12345'); echo 'Property deleted successfully.'; } catch (Exception $e) { echo 'Error deleting property: ' . $e->getMessage(); } ``` -------------------------------- ### Instantiate AnalyticsAdminServiceClient Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/AnalyticsAdminServiceClient.md Shows how to create an instance of the AnalyticsAdminServiceClient using default configuration or with custom client options. ```php use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; use Google\ApiCore\Options\ClientOptions; // Using default configuration $client = new AnalyticsAdminServiceClient(); // Using custom options $options = new ClientOptions([ 'apiEndpoint' => 'analyticsadmin.googleapis.com:443', 'transport' => 'rest', ]); $client = new AnalyticsAdminServiceClient($options); ``` -------------------------------- ### Instantiate AnalyticsAdminServiceClient with all options Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Demonstrates how to instantiate the AnalyticsAdminServiceClient with various configuration options. This is useful for setting up custom retry policies, transport configurations, and other advanced settings. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\ApiCore\CredentialsWrapper; use Google\ApiCore\Transport\GrpcTransportFactory; $options = [ CredentialsWrapper::KEY_FILE_PUBLIC_CERT_PATH => '/path/to/your/cert.pem', CredentialsWrapper::KEY_FILE_PRIVATE_KEY_PATH => '/path/to/your/key.pem', CredentialsWrapper::KEY_FILE_PRIVATE_KEY_ID_PATH => '/path/to/your/key_id.pem', CredentialsWrapper::SCOPES => [ 'https://www.googleapis.com/auth/analytics.edit', 'https://www.googleapis.com/auth/analytics.readonly', ], 'transport' => GrpcTransportFactory::getDefaultTransport(), 'retrySettings' => [ 'initial_retry_delay_millis' => 100, 'retry_delay_multiplier' => 1.5, 'max_retry_delay_millis' => 60000, 'initial_rpc_timeout_millis' => 20000, 'rpc_timeout_multiplier' => 1.5, 'max_rpc_timeout_millis' => 60000, 'total_timeout_millis' => 600000, ], ]; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient($options); ``` -------------------------------- ### Getting a Single Account Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/README.md Retrieve a single account resource using the getAccount method. This is a synchronous operation. ```php $account = $client->getAccount($request); // Returns: Account ``` -------------------------------- ### Update Property Example Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Shows how to update an existing Google Analytics property. Only the fields provided in the request will be modified. ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\Property; $analyticsAdminServiceClient = new AnalyticsAdminServiceClient(); $property = new Property(); $property->setName('properties/12345'); // Resource name of the property to update $property->setDisplayName('Updated Property Name'); try { $updatedProperty = $analyticsAdminServiceClient->updateProperty($property); print_r($updatedProperty); } catch (Exception $e) { echo 'Error updating property: ' . $e->getMessage(); } ``` -------------------------------- ### Get Data Retention Settings Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Common-Patterns.md Retrieve the current data retention settings for a property. Requires the property's name. ```php use Google\Analytics\Admin\V1beta\GetDataRetentionSettingsRequest; $settingsName = 'properties/1000/dataRetentionSettings'; $request = (new GetDataRetentionSettingsRequest()) ->setName($settingsName); $settings = $client->getDataRetentionSettings($request); printf( "Retention: %d months\n", $settings->getEventDataRetention() ); ``` -------------------------------- ### Initialize Client with Application Default Credentials Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Common-Patterns.md Use this method for secure authentication when running on Google Cloud. It automatically uses the GOOGLE_APPLICATION_CREDENTIALS environment variable or the default service account. ```php use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; // Automatically uses GOOGLE_APPLICATION_CREDENTIALS environment variable // or default service account when running on GCP $client = new AnalyticsAdminServiceClient(); ``` -------------------------------- ### Get a Google Analytics Account Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/AnalyticsAdminServiceClient.md Retrieves a single Account by its resource name. Ensure you have the correct account name format. ```php use Google\Analytics\Admin\V1beta\Client\AnalyticsAdminServiceClient; use Google\Analytics\Admin\V1beta\GetAccountRequest; $client = new AnalyticsAdminServiceClient(); $accountName = AnalyticsAdminServiceClient::accountName('100'); $request = (new GetAccountRequest())->setName($accountName); try { $account = $client->getAccount($request); echo "Account: " . $account->getDisplayName(); } catch (ApiException $ex) { echo "Error: " . $ex->getMessage(); } ``` -------------------------------- ### AnalyticsAdminServiceClient Initialization Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Demonstrates how to initialize the AnalyticsAdminServiceClient with various configuration options. ```APIDOC ## Constructor The `AnalyticsAdminServiceClient` can be initialized with various options to configure its behavior, including authentication, transport, and retry policies. ### Constructor Signature ```php public function __construct(array $config = []) ``` ### Options - **credentials** (Google\Auth\Authentication\Credentials|string|array): The credentials to use for authentication. Can be a path to a service account key file, an instance of `Google\Auth\Authentication\CredentialsInterface`, or an array of credentials. - **endpoint** (string): The API endpoint to use. Defaults to `analyticsadmin.googleapis.com`. - **transport** (string): The transport layer to use. Can be `grpc` or `rest`. Defaults to `grpc`. - **retrySettings** (array): Configuration for retry policies. - **initialRetryDelayMillis** (int): The initial delay in milliseconds for retries. - **retryDelayMultiplier** (float): The multiplier for the retry delay. - **maxRetryDelayMillis** (int): The maximum delay in milliseconds for retries. - **initialRpcTimeoutMillis** (int): The initial timeout in milliseconds for RPC calls. - **rpcTimeoutMultiplier** (float): The multiplier for the RPC timeout. - **maxRpcTimeoutMillis** (int): The maximum timeout in milliseconds for RPC calls. - **totalTimeoutMillis** (int): The total timeout in milliseconds for all retries. ### Example ```php use Google\Analytics\Admin\V1beta\AnalyticsAdminServiceClient; // Initialize with default credentials $client = new AnalyticsAdminServiceClient(); // Initialize with a service account key file $client = new AnalyticsAdminServiceClient([ 'credentials' => '/path/to/your/keyfile.json', ]); // Initialize with custom endpoint and REST transport $client = new AnalyticsAdminServiceClient([ 'endpoint' => 'us-central1-analyticsadmin.googleapis.com', 'transport' => 'rest', ]); ``` ``` -------------------------------- ### Get Data Retention Settings Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Common-Patterns.md Retrieves the current data retention settings for a property. This includes the duration for which event data is retained. ```APIDOC ## Get Data Retention Settings ### Description Retrieves the current data retention settings for a property, including the duration for which event data is retained. ### Method `getDataRetentionSettings` ### Endpoint `properties/{propertyId}/dataRetentionSettings` (Implicit) ### Parameters #### Path Parameters - **name** (string) - Required - The name of the data retention settings to retrieve. Format: `properties/{propertyId}/dataRetentionSettings`. ### Response #### Success Response (200) - **event_data_retention** (integer) - The duration in months for which event data is retained. ``` -------------------------------- ### Get a Specific Account Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Common-Patterns.md Fetches details for a specific Analytics account using its ID. Includes error handling for API exceptions. ```php use Google\Analytics\Admin\V1beta\GetAccountRequest; use Google\ApiCore\ApiException; try { $accountName = AnalyticsAdminServiceClient::accountName('100'); $request = (new GetAccountRequest())->setName($accountName); $account = $client->getAccount($request); echo "Account: " . $account->getDisplayName(); } catch (ApiException $ex) { echo "Error: " . $ex->getMessage(); } ``` -------------------------------- ### Resource Name Formatting Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/README.md Demonstrates how to construct fully-qualified resource names using static formatting methods provided by the client library. ```APIDOC ## Resource Name Formatting Resources are identified by fully-qualified paths. Use the client's static formatting methods to build resource names: ```php $accountName = AnalyticsAdminServiceClient::accountName('100'); $propertyName = AnalyticsAdminServiceClient::propertyName('1000'); $streamName = AnalyticsAdminServiceClient::dataStreamName('1000', '2000'); ``` | Resource Type | Format | Example | |---------------|--------|---------| | Account | `accounts/{account}` | `accounts/100` | | Property | `properties/{property}` | `properties/1000` | | Data Stream | `properties/{property}/dataStreams/{stream}` | `properties/1000/dataStreams/2000` | | Custom Dimension | `properties/{property}/customDimensions/{dim}` | `properties/1000/customDimensions/1` | | Custom Metric | `properties/{property}/customMetrics/{metric}` | `properties/1000/customMetrics/1` | | Key Event | `properties/{property}/keyEvents/{event}` | `properties/1000/keyEvents/1` | | Firebase Link | `properties/{property}/firebaseLinks/{link}` | `properties/1000/firebaseLinks/1` | | Google Ads Link | `properties/{property}/googleAdsLinks/{link}` | `properties/1000/googleAdsLinks/1` | | Measurement Secret | `properties/{property}/dataStreams/{stream}/measurementProtocolSecrets/{secret}` | `properties/1000/dataStreams/2000/measurementProtocolSecrets/1` | ``` -------------------------------- ### Paginate Large Datasets - List Accounts Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/SUMMARY.txt Demonstrates how to paginate through results when listing accounts, useful for accounts with many properties. ```php require 'vendor/autoload.php'; use Google\\Analytics\\Admin\\\\V1beta\\\\AnalyticsAdminServiceClient; $client = new AnalyticsAdminServiceClient(); $pageSize = 10; // Number of results per page $accounts = $client->listAccounts(['pageSize' => $pageSize]); foreach ($accounts as $account) { // Process account printf('Account: %s\n', $account->getDisplayName()); } // The client library handles fetching subsequent pages automatically when iterating. ``` -------------------------------- ### Get Data Sharing Settings Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Common-Patterns.md Retrieve the data sharing settings for an account. Requires the account's data sharing settings name. ```php use Google\Analytics\Admin\V1beta\GetDataSharingSettingsRequest; $settingsName = 'accounts/100/dataSharingSettings'; $request = (new GetDataSharingSettingsRequest()) ->setName($settingsName); $settings = $client->getDataSharingSettings($request); printf( "Share with Google Support: %s\n", $settings->getSharingWithGoogleSupportEnabled() ? 'Yes' : 'No' ); ``` -------------------------------- ### Set Environment Variables for Client Configuration Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/configuration.md Configure the client's behavior using environment variables. Set the path to your service account key, enable SDK logging, or specify the default GCP project. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json export GOOGLE_SDK_PHP_LOGGING=true php my_script.php ``` -------------------------------- ### Configure Credentials with CredentialsConfig Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/configuration.md Configure authentication behavior using a credentials configuration array, including default scopes and quota project. ```php $options = [ 'credentialsConfig' => [ 'defaultScopes' => [ 'https://www.googleapis.com/auth/analytics.edit', 'https://www.googleapis.com/auth/analytics.readonly', ], 'quotaProject' => 'my-gcp-project', ], ]; ``` -------------------------------- ### Delete Resource Request Type Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/types.md Delete*Request types require a 'name' field specifying the resource to be deleted. This example shows the structure for DeletePropertyRequest. ```php class DeletePropertyRequest extends \Google\Protobuf\Internal\Message { protected $name = ''; } ``` -------------------------------- ### Create a Web Data Stream Source: https://github.com/googleapis/php-analytics-admin/blob/main/_autodocs/api-reference/Common-Patterns.md Use this snippet to create a new web data stream. Ensure you have the necessary client and property name set up. ```php use Google\Analytics\Admin\V1beta\CreateDataStreamRequest; use Google\Analytics\Admin\V1beta\DataStream; use Google\Analytics\Admin\V1beta\DataStream\WebStreamData; $webStreamData = new WebStreamData(); $webStreamData->setDefaultUri('https://example.com'); $dataStream = new DataStream(); $dataStream->setDisplayName('My Website') ->setType(\Google\Analytics\Admin\V1beta\DataStream\DataStreamType::WEB_DATA_STREAM) ->setWebStreamData($webStreamData); $propertyName = AnalyticsAdminServiceClient::propertyName('1000'); $request = (new CreateDataStreamRequest()) ->setParent($propertyName) ->setDataStream($dataStream); $stream = $client->createDataStream($request); printf( "Created web stream: %s (Measurement ID: %s)\\n", $stream->getName(), $stream->getWebStreamData()->getMeasurementId() ); ```