<commit_before><?php

/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\CampaignManagement;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V3\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V3\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V3\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V3\ResourceNames;
use Google\Ads\GoogleAds\V3\Common\ExpandedTextAdInfo;
use Google\Ads\GoogleAds\V3\Common\KeywordInfo;
use Google\Ads\GoogleAds\V3\Common\ManualCpc;
use Google\Ads\GoogleAds\V3\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V3\Enums\AdGroupCriterionStatusEnum\AdGroupCriterionStatus;
use Google\Ads\GoogleAds\V3\Enums\AdGroupTypeEnum\AdGroupType;
use Google\Ads\GoogleAds\V3\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType;
use Google\Ads\GoogleAds\V3\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod;
use Google\Ads\GoogleAds\V3\Enums\CampaignStatusEnum\CampaignStatus;
use Google\Ads\GoogleAds\V3\Enums\KeywordMatchTypeEnum\KeywordMatchType;
use Google\Ads\GoogleAds\V3\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V3\Resources\Ad;
use Google\Ads\GoogleAds\V3\Resources\AdGroup;
use Google\Ads\GoogleAds\V3\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V3\Resources\AdGroupCriterion;
use Google\Ads\GoogleAds\V3\Resources\Campaign;
use Google\Ads\GoogleAds\V3\Resources\CampaignBudget;
use Google\Ads\GoogleAds\V3\Resources\CampaignCriterion;
use Google\Ads\GoogleAds\V3\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V3\Services\AdGroupCriterionOperation;
use Google\Ads\GoogleAds\V3\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V3\Services\CampaignBudgetOperation;
use Google\Ads\GoogleAds\V3\Services\CampaignCriterionOperation;
use Google\Ads\GoogleAds\V3\Services\CampaignOperation;
use Google\Ads\GoogleAds\V3\Services\MutateJobResult;
use Google\Ads\GoogleAds\V3\Services\MutateJobServiceClient;
use Google\Ads\GoogleAds\V3\Services\MutateOperation;
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Protobuf\BoolValue;
use Google\Protobuf\Int64Value;
use Google\Protobuf\StringValue;

/**
 * This example adds complete campaigns including campaign budgets, campaigns, ad groups and
 * keywords using MutateJobService.
 */
class AddCompleteCampaignsUsingMutateJob
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    private const NUMBER_OF_CAMPAIGNS_TO_ADD = 2;
    private const NUMBER_OF_AD_GROUPS_TO_ADD = 2;
    private const NUMBER_OF_KEYWORDS_TO_ADD = 4;
    private const POLL_FREQUENCY_SECONDS = 1;
    private const MAX_TOTAL_POLL_INTERVAL_SECONDS = 60;

    private const PAGE_SIZE = 1000;

    /** @var int the negative temporary ID used in mutate job operations. */
    private static $temporaryId = -1;

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        $mutateJobServiceClient = $googleAdsClient->getMutateJobServiceClient();

        $mutateJobResourceName = self::createMutateJob($mutateJobServiceClient, $customerId);
        self::addAllMutateJobOperations(
            $mutateJobServiceClient,
            $customerId,
            $mutateJobResourceName
        );
        $operationResponse = self::runMutateJob($mutateJobServiceClient, $mutateJobResourceName);
        self::pollMutateJob($operationResponse);
        self::fetchAndPrintResults($mutateJobServiceClient, $mutateJobResourceName);
    }

    /**
     * Creates a new mutate job for the specified customer ID.
     *
     * @param MutateJobServiceClient $mutateJobServiceClient the mutate job service client
     * @param int $customerId the customer ID
     * @return string the resource name of the created mutate job
     */
    private static function createMutateJob(
        MutateJobServiceClient $mutateJobServiceClient,
        int $customerId
    ) {
        $mutateJobResourceName =
            $mutateJobServiceClient->createMutateJob($customerId)->getResourceName();
        printf(
            "Created a mutate job with resource name: '%s'.%s",
            $mutateJobResourceName,
            PHP_EOL
        );
        return $mutateJobResourceName;
    }

    /**
     * Adds all mutate job operations to the mutate job. As this is the first time for this
     * mutate job, pass null as a sequence token. The response will contain the next sequence token
     * that you can use to upload more operations in the future.
     *
     * @param MutateJobServiceClient $mutateJobServiceClient the mutate job service client
     * @param int $customerId the customer ID
     * @param string $mutateJobResourceName the resource name of mutate job to which the mutate job
     *     operations will be added
     */
    private static function addAllMutateJobOperations(
        MutateJobServiceClient $mutateJobServiceClient,
        int $customerId,
        string $mutateJobResourceName
    ) {
        $response = $mutateJobServiceClient->addMutateJobOperations(
            $mutateJobResourceName,
            null,
            self::buildAllOperations($customerId)
        );
        printf(
            "%d mutate operations have been added so far.%s",
            $response->getTotalOperations(),
            PHP_EOL
        );
        // You can use this next sequence token for calling addMutateJobOperations() next time.
        printf(
            "Next sequence token for adding next operations is '%s'.%s",
            $response->getNextSequenceToken(),
            PHP_EOL
        );
    }

    /**
     * Requests the API to run the mutate job for executing all uploaded mutate job operations.
     *
     * @param MutateJobServiceClient $mutateJobServiceClient the mutate job service client
     * @param string $mutateJobResourceName the resource name of mutate job to be run
     * @return OperationResponse the operation response from running mutate job
     */
    private static function runMutateJob(
        MutateJobServiceClient $mutateJobServiceClient,<commit_msg>Change for an empty string for the sequence token (#319)<commit_after><?php

/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\CampaignManagement;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V3\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V3\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V3\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V3\ResourceNames;
use Google\Ads\GoogleAds\V3\Common\ExpandedTextAdInfo;
use Google\Ads\GoogleAds\V3\Common\KeywordInfo;
use Google\Ads\GoogleAds\V3\Common\ManualCpc;
use Google\Ads\GoogleAds\V3\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V3\Enums\AdGroupCriterionStatusEnum\AdGroupCriterionStatus;
use Google\Ads\GoogleAds\V3\Enums\AdGroupTypeEnum\AdGroupType;
use Google\Ads\GoogleAds\V3\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType;
use Google\Ads\GoogleAds\V3\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod;
use Google\Ads\GoogleAds\V3\Enums\CampaignStatusEnum\CampaignStatus;
use Google\Ads\GoogleAds\V3\Enums\KeywordMatchTypeEnum\KeywordMatchType;
use Google\Ads\GoogleAds\V3\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V3\Resources\Ad;
use Google\Ads\GoogleAds\V3\Resources\AdGroup;
use Google\Ads\GoogleAds\V3\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V3\Resources\AdGroupCriterion;
use Google\Ads\GoogleAds\V3\Resources\Campaign;
use Google\Ads\GoogleAds\V3\Resources\CampaignBudget;
use Google\Ads\GoogleAds\V3\Resources\CampaignCriterion;
use Google\Ads\GoogleAds\V3\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V3\Services\AdGroupCriterionOperation;
use Google\Ads\GoogleAds\V3\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V3\Services\CampaignBudgetOperation;
use Google\Ads\GoogleAds\V3\Services\CampaignCriterionOperation;
use Google\Ads\GoogleAds\V3\Services\CampaignOperation;
use Google\Ads\GoogleAds\V3\Services\MutateJobResult;
use Google\Ads\GoogleAds\V3\Services\MutateJobServiceClient;
use Google\Ads\GoogleAds\V3\Services\MutateOperation;
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Protobuf\BoolValue;
use Google\Protobuf\Int64Value;
use Google\Protobuf\StringValue;

/**
 * This example adds complete campaigns including campaign budgets, campaigns, ad groups and
 * keywords using MutateJobService.
 */
class AddCompleteCampaignsUsingMutateJob
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    private const NUMBER_OF_CAMPAIGNS_TO_ADD = 2;
    private const NUMBER_OF_AD_GROUPS_TO_ADD = 2;
    private const NUMBER_OF_KEYWORDS_TO_ADD = 4;
    private const POLL_FREQUENCY_SECONDS = 1;
    private const MAX_TOTAL_POLL_INTERVAL_SECONDS = 60;

    private const PAGE_SIZE = 1000;

    /** @var int the negative temporary ID used in mutate job operations. */
    private static $temporaryId = -1;

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        $mutateJobServiceClient = $googleAdsClient->getMutateJobServiceClient();

        $mutateJobResourceName = self::createMutateJob($mutateJobServiceClient, $customerId);
        self::addAllMutateJobOperations(
            $mutateJobServiceClient,
            $customerId,
            $mutateJobResourceName
        );
        $operationResponse = self::runMutateJob($mutateJobServiceClient, $mutateJobResourceName);
        self::pollMutateJob($operationResponse);
        self::fetchAndPrintResults($mutateJobServiceClient, $mutateJobResourceName);
    }

    /**
     * Creates a new mutate job for the specified customer ID.
     *
     * @param MutateJobServiceClient $mutateJobServiceClient the mutate job service client
     * @param int $customerId the customer ID
     * @return string the resource name of the created mutate job
     */
    private static function createMutateJob(
        MutateJobServiceClient $mutateJobServiceClient,
        int $customerId
    ) {
        $mutateJobResourceName =
            $mutateJobServiceClient->createMutateJob($customerId)->getResourceName();
        printf(
            "Created a mutate job with resource name: '%s'.%s",
            $mutateJobResourceName,
            PHP_EOL
        );
        return $mutateJobResourceName;
    }

    /**
     * Adds all mutate job operations to the mutate job. As this is the first time for this
     * mutate job, pass null as a sequence token. The response will contain the next sequence token
     * that you can use to upload more operations in the future.
     *
     * @param MutateJobServiceClient $mutateJobServiceClient the mutate job service client
     * @param int $customerId the customer ID
     * @param string $mutateJobResourceName the resource name of mutate job to which the mutate job
     *     operations will be added
     */
    private static function addAllMutateJobOperations(
        MutateJobServiceClient $mutateJobServiceClient,
        int $customerId,
        string $mutateJobResourceName
    ) {
        $response = $mutateJobServiceClient->addMutateJobOperations(
            $mutateJobResourceName,
            '',
            self::buildAllOperations($customerId)
        );
        printf(
            "%d mutate operations have been added so far.%s",
            $response->getTotalOperations(),
            PHP_EOL
        );
        // You can use this next sequence token for calling addMutateJobOperations() next time.
        printf(
            "Next sequence token for adding next operations is '%s'.%s",
            $response->getNextSequenceToken(),
            PHP_EOL
        );
    }

    /**
     * Requests the API to run the mutate job for executing all uploaded mutate job operations.
     *
     * @param MutateJobServiceClient $mutateJobServiceClient the mutate job service client
     * @param string $mutateJobResourceName the resource name of mutate job to be run
     * @return OperationResponse the operation response from running mutate job
     */
    private static function runMutateJob(
        MutateJobServiceClient $mutateJobServiceClient,
{'fraction_non_alphanumeric': 0.0855409967385707, 'fraction_numerical': 0.00692338502031241, 'mean_word_length': 3.017931034482759, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 43, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5012242', 'n_tokens_mistral': 5098, 'n_tokens_neox': 5014, 'n_words': 1217}