<?php
/*
 * Copyright 2021 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.
 */

/*
 * GENERATED CODE WARNING
 * Generated by gapic-generator-php from the file
 * https://github.com/googleapis/googleapis/blob/master/google/cloud/orchestration/airflow/service/v1/environments.proto
 * Updates to the above are reflected here through a refresh process.
 */

namespace Google\Cloud\Orchestration\Airflow\Service\V1\Gapic;

use Google\ApiCore\ApiException;
use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\GapicClientTrait;
use Google\ApiCore\LongRunning\OperationsClient;
use Google\ApiCore\OperationResponse;
use Google\ApiCore\RequestParamsHeaderDescriptor;
use Google\ApiCore\RetrySettings;
use Google\ApiCore\Transport\TransportInterface;
use Google\ApiCore\ValidationException;
use Google\Auth\FetchAuthTokenInterface;
use Google\Cloud\Orchestration\Airflow\Service\V1\CreateEnvironmentRequest;
use Google\Cloud\Orchestration\Airflow\Service\V1\DeleteEnvironmentRequest;
use Google\Cloud\Orchestration\Airflow\Service\V1\Environment;
use Google\Cloud\Orchestration\Airflow\Service\V1\GetEnvironmentRequest;
use Google\Cloud\Orchestration\Airflow\Service\V1\ListEnvironmentsRequest;
use Google\Cloud\Orchestration\Airflow\Service\V1\ListEnvironmentsResponse;
use Google\Cloud\Orchestration\Airflow\Service\V1\LoadSnapshotRequest;
use Google\Cloud\Orchestration\Airflow\Service\V1\SaveSnapshotRequest;
use Google\Cloud\Orchestration\Airflow\Service\V1\UpdateEnvironmentRequest;
use Google\LongRunning\Operation;
use Google\Protobuf\FieldMask;

/**
 * Service Description: Managed Apache Airflow Environments.
 *
 * This class provides the ability to make remote calls to the backing service through method
 * calls that map to API methods. Sample code to get started:
 *
 * ```
 * $environmentsClient = new EnvironmentsClient();
 * try {
 *     $operationResponse = $environmentsClient->createEnvironment();
 *     $operationResponse->pollUntilComplete();
 *     if ($operationResponse->operationSucceeded()) {
 *         $result = $operationResponse->getResult();
 *     // doSomethingWith($result)
 *     } else {
 *         $error = $operationResponse->getError();
 *         // handleError($error)
 *     }
 *     // Alternatively:
 *     // start the operation, keep the operation name, and resume later
 *     $operationResponse = $environmentsClient->createEnvironment();
 *     $operationName = $operationResponse->getName();
 *     // ... do other work
 *     $newOperationResponse = $environmentsClient->resumeOperation($operationName, 'createEnvironment');
 *     while (!$newOperationResponse->isDone()) {
 *         // ... do other work
 *         $newOperationResponse->reload();
 *     }
 *     if ($newOperationResponse->operationSucceeded()) {
 *         $result = $newOperationResponse->getResult();
 *     // doSomethingWith($result)
 *     } else {
 *         $error = $newOperationResponse->getError();
 *         // handleError($error)
 *     }
 * } finally {
 *     $environmentsClient->close();
 * }
 * ```
 */
class EnvironmentsGapicClient
{
    use GapicClientTrait;

    /** The name of the service. */
    const SERVICE_NAME = 'google.cloud.orchestration.airflow.service.v1.Environments';

    /** The default address of the service. */
    const SERVICE_ADDRESS = 'composer.googleapis.com';

    /** The default port of the service. */
    const DEFAULT_SERVICE_PORT = 443;

    /** The name of the code generator, to be included in the agent header. */
    const CODEGEN_NAME = 'gapic';

    /** The default scopes required by the service. */
    public static $serviceScopes = [
        'https://www.googleapis.com/auth/cloud-platform',
    ];

    private $operationsClient;

    private static function getClientDefaults()
    {
        return [
            'serviceName' => self::SERVICE_NAME,
            'apiEndpoint' =>
                self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT,
            'clientConfig' =>
                __DIR__ . '/../resources/environments_client_config.json',
            'descriptorsConfigPath' =>
                __DIR__ . '/../resources/environments_descriptor_config.php',
            'gcpApiConfigPath' =>
                __DIR__ . '/../resources/environments_grpc_config.json',
            'credentialsConfig' => [
                'defaultScopes' => self::$serviceScopes,
            ],
            'transportConfig' => [
                'rest' => [
                    'restClientConfigPath' =>
                        __DIR__ .
                        '/../resources/environments_rest_client_config.php',
                ],
            ],
        ];
    }

    /**
     * Return an OperationsClient object with the same endpoint as $this.
     *
     * @return OperationsClient
     */
    public function getOperationsClient()
    {
        return $this->operationsClient;
    }

    /**
     * Resume an existing long running operation that was previously started by a long
     * running API method. If $methodName is not provided, or does not match a long
     * running API method, then the operation can still be resumed, but the
     * OperationResponse object will not deserialize the final response.
     *
     * @param string $operationName The name of the long running operation
     * @param string $methodName    The name of the method used to start the operation
     *
     * @return OperationResponse
     */
    public function resumeOperation($operationName, $methodName = null)
    {
        $options = isset($this->descriptors[$methodName]['longRunning'])
            ? $this->descriptors[$methodName]['longRunning']
            : [];
        $operation = new OperationResponse(
            $operationName,
            $this->getOperationsClient(),
            $options
        );
        $operation->reload();
        return $operation;
    }

    /**
     * Constructor.
     *
     * @param array $options {
     *     Optional. Options for configuring the service API wrapper.
     *
     *     @type string $apiEndpoint
     *           The address of the API remote host. May optionally include the port, formatted
     *           as "<uri>:<port>". Default 'composer.googleapis.com:443'.
     *     @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials
     *           The credentials to be used by the client to authorize API calls. This option
     *           accepts either a path to a credentials file, or a decoded credentials file as a
     *           PHP array.
     *           *Advanced usage*: In addition, this option can also accept a pre-constructed
     *           {@see \Google\Auth\FetchAuthTokenInterface} object or
     *           {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these
     *           objects are provided, any settings in $credentialsConfig will be ignored.
     *     @type array $credentialsConfig
     *           Options used to configure credentials, including auth token caching, for the
     *           client. For a full list of supporting configuration options, see
     *           {@see \Google\ApiCore\CredentialsWrapper::build()} .
     *     @type bool $disableRetries
     *           Determines whether or not retries defined by the client configuration should be
     *           disabled. Defaults to `false`.
     *     @type string|array $clientConfig
     *           Client method configuration, including retry settings. This option can be either
     *           a path to a JSON file, or a PHP array containing the decoded JSON data. By
     *           default this settings points to the default client config file, which is
     *           provided in the resources folder.
     *     @type string|TransportInterface $transport
     *           The transport used for executing network requests. May be either the string
     *           `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system.
     *           *Advanced usage*: Additionally, it is possible to pass in an already
     *           instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note
     *           that when this object is provided, any settings in $transportConfig, and any
     *           $apiEndpoint setting, will be ignored.
     *     @type array $transportConfig
     *           Configuration options that will be used to construct the transport. Options for
     *           each supported transport type should be passed in a key for that transport. For
     *           example:
     *           $transportConfig = [
     *               'grpc' => [...],
     *               'rest' => [...],
     *           ];
     *           See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and
     *           {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the
     *           supported options.
     *     @type callable $clientCertSource
     *           A callable which returns the client cert as a string. This can be used to
     *           provide a certificate and private key to the transport layer for mTLS.
     * }
     *
     * @throws ValidationException
     */
    public function __construct(array $options = [])
    {
        $clientOptions = $this->buildClientOptions($options);
        $this->setClientOptions($clientOptions);
        $this->operationsClient = $this->createOperationsClient($clientOptions);
    }

    /**
     * Create a new environment.
     *
     * Sample code:
     * ```
     * $environmentsClient = new EnvironmentsClient();
     * try {
     *     $operationResponse = $environmentsClient->createEnvironment();
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $environmentsClient->createEnvironment();
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $environmentsClient->resumeOperation($operationName, 'createEnvironment');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $environmentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $parent
     *           The parent must be of the form
     *           "projects/{projectId}/locations/{locationId}".
     *     @type Environment $environment
     *           The environment to create.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function createEnvironment(array $optionalArgs = [])
    {
        $request = new CreateEnvironmentRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['parent'])) {
            $request->setParent($optionalArgs['parent']);
            $requestParamHeaders['parent'] = $optionalArgs['parent'];
        }

        if (isset($optionalArgs['environment'])) {
            $request->setEnvironment($optionalArgs['environment']);
        }

        $requestParams = new RequestParamsHeaderDescriptor(
            $requestParamHeaders
        );
        $optionalArgs['headers'] = isset($optionalArgs['headers'])
            ? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
            : $requestParams->getHeader();
        return $this->startOperationsCall(
            'CreateEnvironment',
            $optionalArgs,
            $request,
            $this->getOperationsClient()
        )->wait();
    }

    /**
     * Delete an environment.
     *
     * Sample code:
     * ```
     * $environmentsClient = new EnvironmentsClient();
     * try {
     *     $operationResponse = $environmentsClient->deleteEnvironment();
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         // operation succeeded and returns no value
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $environmentsClient->deleteEnvironment();
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $environmentsClient->resumeOperation($operationName, 'deleteEnvironment');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         // operation succeeded and returns no value
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $environmentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $name
     *           The environment to delete, in the form:
     *           "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function deleteEnvironment(array $optionalArgs = [])
    {
        $request = new DeleteEnvironmentRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['name'])) {
            $request->setName($optionalArgs['name']);
            $requestParamHeaders['name'] = $optionalArgs['name'];
        }

        $requestParams = new RequestParamsHeaderDescriptor(
            $requestParamHeaders
        );
        $optionalArgs['headers'] = isset($optionalArgs['headers'])
            ? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
            : $requestParams->getHeader();
        return $this->startOperationsCall(
            'DeleteEnvironment',
            $optionalArgs,
            $request,
            $this->getOperationsClient()
        )->wait();
    }

    /**
     * Get an existing environment.
     *
     * Sample code:
     * ```
     * $environmentsClient = new EnvironmentsClient();
     * try {
     *     $response = $environmentsClient->getEnvironment();
     * } finally {
     *     $environmentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $name
     *           The resource name of the environment to get, in the form:
     *           "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\Cloud\Orchestration\Airflow\Service\V1\Environment
     *
     * @throws ApiException if the remote call fails
     */
    public function getEnvironment(array $optionalArgs = [])
    {
        $request = new GetEnvironmentRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['name'])) {
            $request->setName($optionalArgs['name']);
            $requestParamHeaders['name'] = $optionalArgs['name'];
        }

        $requestParams = new RequestParamsHeaderDescriptor(
            $requestParamHeaders
        );
        $optionalArgs['headers'] = isset($optionalArgs['headers'])
            ? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
            : $requestParams->getHeader();
        return $this->startCall(
            'GetEnvironment',
            Environment::class,
            $optionalArgs,
            $request
        )->wait();
    }

    /**
     * List environments.
     *
     * Sample code:
     * ```
     * $environmentsClient = new EnvironmentsClient();
     * try {
     *     // Iterate over pages of elements
     *     $pagedResponse = $environmentsClient->listEnvironments();
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $environmentsClient->listEnvironments();
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $environmentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $parent
     *           List environments in the given project and location, in the form:
     *           "projects/{projectId}/locations/{locationId}"
     *     @type int $pageSize
     *           The maximum number of resources contained in the underlying API
     *           response. The API may return fewer values in a page, even if
     *           there are additional values to be retrieved.
     *     @type string $pageToken
     *           A page token is used to specify a page of values to be returned.
     *           If no page token is specified (the default), the first page
     *           of values will be returned. Any page token used here must have
     *           been generated by a previous call to the API.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\PagedListResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function listEnvironments(array $optionalArgs = [])
    {
        $request = new ListEnvironmentsRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['parent'])) {
            $request->setParent($optionalArgs['parent']);
            $requestParamHeaders['parent'] = $optionalArgs['parent'];
        }

        if (isset($optionalArgs['pageSize'])) {
            $request->setPageSize($optionalArgs['pageSize']);
        }

        if (isset($optionalArgs['pageToken'])) {
            $request->setPageToken($optionalArgs['pageToken']);
        }

        $requestParams = new RequestParamsHeaderDescriptor(
            $requestParamHeaders
        );
        $optionalArgs['headers'] = isset($optionalArgs['headers'])
            ? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
            : $requestParams->getHeader();
        return $this->getPagedListResponse(
            'ListEnvironments',
            $optionalArgs,
            ListEnvironmentsResponse::class,
            $request
        );
    }

    /**
     * Loads a snapshot of a Cloud Composer environment.
     *
     * As a result of this operation, a snapshot of environment's specified in
     * LoadSnapshotRequest is loaded into the environment.
     *
     * Sample code:
     * ```
     * $environmentsClient = new EnvironmentsClient();
     * try {
     *     $operationResponse = $environmentsClient->loadSnapshot();
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $environmentsClient->loadSnapshot();
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $environmentsClient->resumeOperation($operationName, 'loadSnapshot');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $environmentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $environment
     *           The resource name of the target environment in the form:
     *           "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
     *     @type string $snapshotPath
     *           A Cloud Storage path to a snapshot to load, e.g.:
     *           "gs://my-bucket/snapshots/project_location_environment_timestamp".
     *     @type bool $skipPypiPackagesInstallation
     *           Whether or not to skip installing Pypi packages when loading the
     *           environment's state.
     *     @type bool $skipEnvironmentVariablesSetting
     *           Whether or not to skip setting environment variables when loading the
     *           environment's state.
     *     @type bool $skipAirflowOverridesSetting
     *           Whether or not to skip setting Airflow overrides when loading the
     *           environment's state.
     *     @type bool $skipGcsDataCopying
     *           Whether or not to skip copying Cloud Storage data when loading the
     *           environment's state.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function loadSnapshot(array $optionalArgs = [])
    {
        $request = new LoadSnapshotRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['environment'])) {
            $request->setEnvironment($optionalArgs['environment']);
            $requestParamHeaders['environment'] = $optionalArgs['environment'];
        }

        if (isset($optionalArgs['snapshotPath'])) {
            $request->setSnapshotPath($optionalArgs['snapshotPath']);
        }

        if (isset($optionalArgs['skipPypiPackagesInstallation'])) {
            $request->setSkipPypiPackagesInstallation(
                $optionalArgs['skipPypiPackagesInstallation']
            );
        }

        if (isset($optionalArgs['skipEnvironmentVariablesSetting'])) {
            $request->setSkipEnvironmentVariablesSetting(
                $optionalArgs['skipEnvironmentVariablesSetting']
            );
        }

        if (isset($optionalArgs['skipAirflowOverridesSetting'])) {
            $request->setSkipAirflowOverridesSetting(
                $optionalArgs['skipAirflowOverridesSetting']
            );
        }

        if (isset($optionalArgs['skipGcsDataCopying'])) {
            $request->setSkipGcsDataCopying(
                $optionalArgs['skipGcsDataCopying']
            );
        }

        $requestParams = new RequestParamsHeaderDescriptor(
            $requestParamHeaders
        );
        $optionalArgs['headers'] = isset($optionalArgs['headers'])
            ? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
            : $requestParams->getHeader();
        return $this->startOperationsCall(
            'LoadSnapshot',
            $optionalArgs,
            $request,
            $this->getOperationsClient()
        )->wait();
    }

    /**
     * Creates a snapshots of a Cloud Composer environment.
     *
     * As a result of this operation, snapshot of environment's state is stored
     * in a location specified in the SaveSnapshotRequest.
     *
     * Sample code:
     * ```
     * $environmentsClient = new EnvironmentsClient();
     * try {
     *     $operationResponse = $environmentsClient->saveSnapshot();
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $environmentsClient->saveSnapshot();
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $environmentsClient->resumeOperation($operationName, 'saveSnapshot');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $environmentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $environment
     *           The resource name of the source environment in the form:
     *           "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
     *     @type string $snapshotLocation
     *           Location in a Cloud Storage where the snapshot is going to be stored, e.g.:
     *           "gs://my-bucket/snapshots".
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function saveSnapshot(array $optionalArgs = [])
    {
        $request = new SaveSnapshotRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['environment'])) {
            $request->setEnvironment($optionalArgs['environment']);
            $requestParamHeaders['environment'] = $optionalArgs['environment'];
        }

        if (isset($optionalArgs['snapshotLocation'])) {
            $request->setSnapshotLocation($optionalArgs['snapshotLocation']);
        }

        $requestParams = new RequestParamsHeaderDescriptor(
            $requestParamHeaders
        );
        $optionalArgs['headers'] = isset($optionalArgs['headers'])
            ? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
            : $requestParams->getHeader();
        return $this->startOperationsCall(
            'SaveSnapshot',
            $optionalArgs,
            $request,
            $this->getOperationsClient()
        )->wait();
    }

    /**
     * Update an environment.
     *
     * Sample code:
     * ```
     * $environmentsClient = new EnvironmentsClient();
     * try {
     *     $operationResponse = $environmentsClient->updateEnvironment();
     *     $operationResponse->pollUntilComplete();
     *     if ($operationResponse->operationSucceeded()) {
     *         $result = $operationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $operationResponse->getError();
     *         // handleError($error)
     *     }
     *     // Alternatively:
     *     // start the operation, keep the operation name, and resume later
     *     $operationResponse = $environmentsClient->updateEnvironment();
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $environmentsClient->resumeOperation($operationName, 'updateEnvironment');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $environmentsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $name
     *           The relative resource name of the environment to update, in the form:
     *           "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
     *     @type Environment $environment
     *           A patch environment. Fields specified by the `updateMask` will be copied
     *           from the patch environment into the environment under update.
     *     @type FieldMask $updateMask
     *           Required. A comma-separated list of paths, relative to `Environment`, of
     *           fields to update.
     *           For example, to set the version of scikit-learn to install in the
     *           environment to 0.19.0 and to remove an existing installation of
     *           numpy, the `updateMask` parameter would include the following two
     *           `paths` values: "config.softwareConfig.pypiPackages.scikit-learn" and
     *           "config.softwareConfig.pypiPackages.numpy". The included patch
     *           environment would specify the scikit-learn version as follows:
     *
     *           {
     *           "config":{
     *           "softwareConfig":{
     *           "pypiPackages":{
     *           "scikit-learn":"==0.19.0"
     *           }
     *           }
     *           }
     *           }
     *
     *           Note that in the above example, any existing PyPI packages
     *           other than scikit-learn and numpy will be unaffected.
     *
     *           Only one update type may be included in a single request's `updateMask`.
     *           For example, one cannot update both the PyPI packages and
     *           labels in the same request. However, it is possible to update multiple
     *           members of a map field simultaneously in the same request. For example,
     *           to set the labels "label1" and "label2" while clearing "label3" (assuming
     *           it already exists), one can
     *           provide the paths "labels.label1", "labels.label2", and "labels.label3"
     *           and populate the patch environment as follows:
     *
     *           {
     *           "labels":{
     *           "label1":"new-label1-value"
     *           "label2":"new-label2-value"
     *           }
     *           }
     *
     *           Note that in the above example, any existing labels that are not
     *           included in the `updateMask` will be unaffected.
     *
     *           It is also possible to replace an entire map field by providing the
     *           map field's path in the `updateMask`. The new value of the field will
     *           be that which is provided in the patch environment. For example, to
     *           delete all pre-existing user-specified PyPI packages and
     *           install botocore at version 1.7.14, the `updateMask` would contain
     *           the path "config.softwareConfig.pypiPackages", and
     *           the patch environment would be the following:
     *
     *           {
     *           "config":{
     *           "softwareConfig":{
     *           "pypiPackages":{
     *           "botocore":"==1.7.14"
     *           }
     *           }
     *           }
     *           }
     *
     *           **Note:** Only the following fields can be updated:
     *
     *           * `config.softwareConfig.pypiPackages`
     *           * Replace all custom custom PyPI packages. If a replacement
     *           package map is not included in `environment`, all custom
     *           PyPI packages are cleared. It is an error to provide both
     *           this mask and a mask specifying an individual package.
     *           * `config.softwareConfig.pypiPackages.`packagename
     *           * Update the custom PyPI package *packagename*,
     *           preserving other packages. To delete the package, include it in
     *           `updateMask`, and omit the mapping for it in
     *           `environment.config.softwareConfig.pypiPackages`. It is an error
     *           to provide both a mask of this form and the
     *           `config.softwareConfig.pypiPackages` mask.
     *           * `labels`
     *           * Replace all environment labels. If a replacement labels map is not
     *           included in `environment`, all labels are cleared. It is an error to
     *           provide both this mask and a mask specifying one or more individual
     *           labels.
     *           * `labels.`labelName
     *           * Set the label named *labelName*, while preserving other
     *           labels. To delete the label, include it in `updateMask` and omit its
     *           mapping in `environment.labels`. It is an error to provide both a
     *           mask of this form and the `labels` mask.
     *           * `config.nodeCount`
     *           * Horizontally scale the number of nodes in the environment. An integer
     *           greater than or equal to 3 must be provided in the `config.nodeCount`
     *           field. Supported for Cloud Composer environments in versions
     *           composer-1.*.*-airflow-*.*.*.
     *           * `config.webServerNetworkAccessControl`
     *           * Replace the environment's current `WebServerNetworkAccessControl`.
     *           * `config.softwareConfig.airflowConfigOverrides`
     *           * Replace all Apache Airflow config overrides. If a replacement config
     *           overrides map is not included in `environment`, all config overrides
     *           are cleared.
     *           It is an error to provide both this mask and a mask specifying one or
     *           more individual config overrides.
     *           * `config.softwareConfig.airflowConfigOverrides.`section-name
     *           * Override the Apache Airflow config property *name* in the
     *           section named *section*, preserving other properties. To
     *           delete the property override, include it in `updateMask` and omit its
     *           mapping in
     *           `environment.config.softwareConfig.airflowConfigOverrides`.
     *           It is an error to provide both a mask of this form and the
     *           `config.softwareConfig.airflowConfigOverrides` mask.
     *           * `config.softwareConfig.envVariables`
     *           * Replace all environment variables. If a replacement environment
     *           variable map is not included in `environment`, all custom environment
     *           variables are cleared.
     *           * `config.softwareConfig.schedulerCount`
     *           * Horizontally scale the number of schedulers in Airflow. A positive
     *           integer not greater than the number of nodes must be provided in the
     *           `config.softwareConfig.schedulerCount` field. Supported for Cloud
     *           Composer environments in versions composer-1.*.*-airflow-2.*.*.
     *           * `config.databaseConfig.machineType`
     *           * Cloud SQL machine type used by Airflow database.
     *           It has to be one of: db-n1-standard-2, db-n1-standard-4,
     *           db-n1-standard-8 or db-n1-standard-16. Supported for Cloud Composer
     *           environments in versions composer-1.*.*-airflow-*.*.*.
     *           * `config.webServerConfig.machineType`
     *           * Machine type on which Airflow web server is running.
     *           It has to be one of: composer-n1-webserver-2, composer-n1-webserver-4
     *           or composer-n1-webserver-8. Supported for Cloud Composer environments
     *           in versions composer-1.*.*-airflow-*.*.*.
     *     @type RetrySettings|array $retrySettings
     *           Retry settings to use for this call. Can be a {@see RetrySettings} object, or an
     *           associative array of retry settings parameters. See the documentation on
     *           {@see RetrySettings} for example usage.
     * }
     *
     * @return \Google\ApiCore\OperationResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function updateEnvironment(array $optionalArgs = [])
    {
        $request = new UpdateEnvironmentRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['name'])) {
            $request->setName($optionalArgs['name']);
            $requestParamHeaders['name'] = $optionalArgs['name'];
        }

        if (isset($optionalArgs['environment'])) {
            $request->setEnvironment($optionalArgs['environment']);
        }

        if (isset($optionalArgs['updateMask'])) {
            $request->setUpdateMask($optionalArgs['updateMask']);
        }

        $requestParams = new RequestParamsHeaderDescriptor(
            $requestParamHeaders
        );
        $optionalArgs['headers'] = isset($optionalArgs['headers'])
            ? array_merge($requestParams->getHeader(), $optionalArgs['headers'])
            : $requestParams->getHeader();
        return $this->startOperationsCall(
            'UpdateEnvironment',
            $optionalArgs,
            $request,
            $this->getOperationsClient()
        )->wait();
    }
}
