<?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/resourcemanager/v3/projects.proto
 * Updates to the above are reflected here through a refresh process.
 */

namespace Google\Cloud\ResourceManager\V3\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\PathTemplate;
use Google\ApiCore\RequestParamsHeaderDescriptor;
use Google\ApiCore\RetrySettings;
use Google\ApiCore\Transport\TransportInterface;
use Google\ApiCore\ValidationException;
use Google\Auth\FetchAuthTokenInterface;
use Google\Cloud\Iam\V1\GetIamPolicyRequest;
use Google\Cloud\Iam\V1\GetPolicyOptions;
use Google\Cloud\Iam\V1\Policy;
use Google\Cloud\Iam\V1\SetIamPolicyRequest;
use Google\Cloud\Iam\V1\TestIamPermissionsRequest;
use Google\Cloud\Iam\V1\TestIamPermissionsResponse;
use Google\Cloud\ResourceManager\V3\CreateProjectRequest;
use Google\Cloud\ResourceManager\V3\DeleteProjectRequest;
use Google\Cloud\ResourceManager\V3\GetProjectRequest;
use Google\Cloud\ResourceManager\V3\ListProjectsRequest;
use Google\Cloud\ResourceManager\V3\ListProjectsResponse;
use Google\Cloud\ResourceManager\V3\MoveProjectRequest;
use Google\Cloud\ResourceManager\V3\Project;
use Google\Cloud\ResourceManager\V3\SearchProjectsRequest;
use Google\Cloud\ResourceManager\V3\SearchProjectsResponse;
use Google\Cloud\ResourceManager\V3\UndeleteProjectRequest;
use Google\Cloud\ResourceManager\V3\UpdateProjectRequest;
use Google\LongRunning\Operation;
use Google\Protobuf\FieldMask;

/**
 * Service Description: Manages Google Cloud Projects.
 *
 * 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:
 *
 * ```
 * $projectsClient = new ProjectsClient();
 * try {
 *     $project = new Project();
 *     $operationResponse = $projectsClient->createProject($project);
 *     $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 = $projectsClient->createProject($project);
 *     $operationName = $operationResponse->getName();
 *     // ... do other work
 *     $newOperationResponse = $projectsClient->resumeOperation($operationName, 'createProject');
 *     while (!$newOperationResponse->isDone()) {
 *         // ... do other work
 *         $newOperationResponse->reload();
 *     }
 *     if ($newOperationResponse->operationSucceeded()) {
 *         $result = $newOperationResponse->getResult();
 *     // doSomethingWith($result)
 *     } else {
 *         $error = $newOperationResponse->getError();
 *         // handleError($error)
 *     }
 * } finally {
 *     $projectsClient->close();
 * }
 * ```
 *
 * Many parameters require resource names to be formatted in a particular way. To
 * assist with these names, this class includes a format method for each type of
 * name, and additionally a parseName method to extract the individual identifiers
 * contained within formatted names that are returned by the API.
 */
class ProjectsGapicClient
{
    use GapicClientTrait;

    /**
     * The name of the service.
     */
    const SERVICE_NAME = 'google.cloud.resourcemanager.v3.Projects';

    /**
     * The default address of the service.
     */
    const SERVICE_ADDRESS = 'cloudresourcemanager.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',
        'https://www.googleapis.com/auth/cloud-platform.read-only',
    ];

    private static $projectNameTemplate;

    private static $pathTemplateMap;

    private $operationsClient;

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

    private static function getProjectNameTemplate()
    {
        if (self::$projectNameTemplate == null) {
            self::$projectNameTemplate = new PathTemplate('projects/{project}');
        }

        return self::$projectNameTemplate;
    }

    private static function getPathTemplateMap()
    {
        if (self::$pathTemplateMap == null) {
            self::$pathTemplateMap = [
                'project' => self::getProjectNameTemplate(),
            ];
        }

        return self::$pathTemplateMap;
    }

    /**
     * Formats a string containing the fully-qualified path to represent a project
     * resource.
     *
     * @param string $project
     *
     * @return string The formatted project resource.
     */
    public static function projectName($project)
    {
        return self::getProjectNameTemplate()->render([
            'project' => $project,
        ]);
    }

    /**
     * Parses a formatted name string and returns an associative array of the components in the name.
     * The following name formats are supported:
     * Template: Pattern
     * - project: projects/{project}
     *
     * The optional $template argument can be supplied to specify a particular pattern,
     * and must match one of the templates listed above. If no $template argument is
     * provided, or if the $template argument does not match one of the templates
     * listed, then parseName will check each of the supported templates, and return
     * the first match.
     *
     * @param string $formattedName The formatted name string
     * @param string $template      Optional name of template to match
     *
     * @return array An associative array from name component IDs to component values.
     *
     * @throws ValidationException If $formattedName could not be matched.
     */
    public static function parseName($formattedName, $template = null)
    {
        $templateMap = self::getPathTemplateMap();
        if ($template) {
            if (!isset($templateMap[$template])) {
                throw new ValidationException("Template name $template does not exist");
            }

            return $templateMap[$template]->match($formattedName);
        }

        foreach ($templateMap as $templateName => $pathTemplate) {
            try {
                return $pathTemplate->match($formattedName);
            } catch (ValidationException $ex) {
                // Swallow the exception to continue trying other path templates
            }
        }

        throw new ValidationException("Input did not match any known format. Input: $formattedName");
    }

    /**
     * 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 $serviceAddress
     *           **Deprecated**. This option will be removed in a future major release. Please
     *           utilize the `$apiEndpoint` option instead.
     *     @type string $apiEndpoint
     *           The address of the API remote host. May optionally include the port, formatted
     *           as "<uri>:<port>". Default 'cloudresourcemanager.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
     *           $serviceAddress 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);
    }

    /**
     * Request that a new project be created. The result is an `Operation` which
     * can be used to track the creation process. This process usually takes a few
     * seconds, but can sometimes take much longer. The tracking `Operation` is
     * automatically deleted after a few hours, so there is no need to call
     * `DeleteOperation`.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $project = new Project();
     *     $operationResponse = $projectsClient->createProject($project);
     *     $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 = $projectsClient->createProject($project);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $projectsClient->resumeOperation($operationName, 'createProject');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param Project $project      Required. The Project to create.
     *
     *                              Project ID is required. If the requested ID is unavailable, the request
     *                              fails.
     *
     *                              If the `parent` field is set, the `resourcemanager.projects.create`
     *                              permission is checked on the parent resource. If no parent is set and
     *                              the authorization credentials belong to an Organziation, the parent
     *                              will be set to that Organization.
     * @param array   $optionalArgs {
     *     Optional.
     *
     *     @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 createProject($project, array $optionalArgs = [])
    {
        $request = new CreateProjectRequest();
        $request->setProject($project);
        return $this->startOperationsCall('CreateProject', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Marks the project identified by the specified
     * `name` (for example, `projects/415104041262`) for deletion.
     *
     * This method will only affect the project if it has a lifecycle state of
     * [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE].
     *
     * This method changes the Project's lifecycle state from
     * [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]
     * to [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED].
     * The deletion starts at an unspecified time,
     * at which point the Project is no longer accessible.
     *
     * Until the deletion completes, you can check the lifecycle state
     * checked by retrieving the project with [GetProject]
     * [google.cloud.resourcemanager.v3.Projects.GetProject],
     * and the project remains visible to [ListProjects]
     * [google.cloud.resourcemanager.v3.Projects.ListProjects].
     * However, you cannot update the project.
     *
     * After the deletion completes, the project is not retrievable by
     * the  [GetProject]
     * [google.cloud.resourcemanager.v3.Projects.GetProject],
     * [ListProjects]
     * [google.cloud.resourcemanager.v3.Projects.ListProjects], and
     * [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]
     * methods.
     *
     * This method behaves idempotently, such that deleting a `DELETE_REQUESTED`
     * project will not cause an error, but also won't do anything.
     *
     * The caller must have `resourcemanager.projects.delete` permissions for this
     * project.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $formattedName = $projectsClient->projectName('[PROJECT]');
     *     $operationResponse = $projectsClient->deleteProject($formattedName);
     *     $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 = $projectsClient->deleteProject($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $projectsClient->resumeOperation($operationName, 'deleteProject');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the Project (for example, `projects/415104041262`).
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @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 deleteProject($name, array $optionalArgs = [])
    {
        $request = new DeleteProjectRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('DeleteProject', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Returns the IAM access control policy for the specified project.
     * Permission is denied if the policy or the resource do not exist.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $resource = 'resource';
     *     $response = $projectsClient->getIamPolicy($resource);
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param string $resource     REQUIRED: The resource for which the policy is being requested.
     *                             See the operation documentation for the appropriate value for this field.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type GetPolicyOptions $options
     *           OPTIONAL: A `GetPolicyOptions` object for specifying options to
     *           `GetIamPolicy`.
     *     @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\Iam\V1\Policy
     *
     * @throws ApiException if the remote call fails
     */
    public function getIamPolicy($resource, array $optionalArgs = [])
    {
        $request = new GetIamPolicyRequest();
        $requestParamHeaders = [];
        $request->setResource($resource);
        $requestParamHeaders['resource'] = $resource;
        if (isset($optionalArgs['options'])) {
            $request->setOptions($optionalArgs['options']);
        }

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

    /**
     * Retrieves the project identified by the specified `name` (for example,
     * `projects/415104041262`).
     *
     * The caller must have `resourcemanager.projects.get` permission
     * for this project.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $formattedName = $projectsClient->projectName('[PROJECT]');
     *     $response = $projectsClient->getProject($formattedName);
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the project (for example, `projects/415104041262`).
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @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\ResourceManager\V3\Project
     *
     * @throws ApiException if the remote call fails
     */
    public function getProject($name, array $optionalArgs = [])
    {
        $request = new GetProjectRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('GetProject', Project::class, $optionalArgs, $request)->wait();
    }

    /**
     * Lists projects that are direct children of the specified folder or
     * organization resource. `list()` provides a strongly consistent view of the
     * projects underneath the specified parent resource. `list()` returns
     * projects sorted based upon the (ascending) lexical ordering of their
     * `display_name`. The caller must have `resourcemanager.projects.list`
     * permission on the identified parent.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $parent = 'parent';
     *     // Iterate over pages of elements
     *     $pagedResponse = $projectsClient->listProjects($parent);
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $projectsClient->listProjects($parent);
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The name of the parent resource to list projects under.
     *
     *                             For example, setting this field to 'folders/1234' would list all projects
     *                             directly under that folder.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @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 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 bool $showDeleted
     *           Optional. Indicate that projects in the `DELETE_REQUESTED` state should also be
     *           returned. Normally only `ACTIVE` projects are returned.
     *     @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 listProjects($parent, array $optionalArgs = [])
    {
        $request = new ListProjectsRequest();
        $request->setParent($parent);
        if (isset($optionalArgs['pageToken'])) {
            $request->setPageToken($optionalArgs['pageToken']);
        }

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

        if (isset($optionalArgs['showDeleted'])) {
            $request->setShowDeleted($optionalArgs['showDeleted']);
        }

        return $this->getPagedListResponse('ListProjects', $optionalArgs, ListProjectsResponse::class, $request);
    }

    /**
     * Move a project to another place in your resource hierarchy, under a new
     * resource parent.
     *
     * Returns an operation which can be used to track the process of the project
     * move workflow.
     * Upon success, the `Operation.response` field will be populated with the
     * moved project.
     *
     * The caller must have `resourcemanager.projects.update` permission on the
     * project and have `resourcemanager.projects.move` permission on the
     * project's current and proposed new parent.
     *
     *
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $formattedName = $projectsClient->projectName('[PROJECT]');
     *     $destinationParent = 'destination_parent';
     *     $operationResponse = $projectsClient->moveProject($formattedName, $destinationParent);
     *     $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 = $projectsClient->moveProject($formattedName, $destinationParent);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $projectsClient->resumeOperation($operationName, 'moveProject');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param string $name              Required. The name of the project to move.
     * @param string $destinationParent Required. The new parent to move the Project under.
     * @param array  $optionalArgs      {
     *     Optional.
     *
     *     @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 moveProject($name, $destinationParent, array $optionalArgs = [])
    {
        $request = new MoveProjectRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $request->setDestinationParent($destinationParent);
        $requestParamHeaders['name'] = $name;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('MoveProject', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Search for projects that the caller has both `resourcemanager.projects.get`
     * permission on, and also satisfy the specified query.
     *
     * This method returns projects in an unspecified order.
     *
     * This method is eventually consistent with project mutations; this means
     * that a newly created project may not appear in the results or recent
     * updates to an existing project may not be reflected in the results. To
     * retrieve the latest state of a project, use the
     * [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject] method.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     // Iterate over pages of elements
     *     $pagedResponse = $projectsClient->searchProjects();
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $projectsClient->searchProjects();
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $query
     *           Optional. A query string for searching for projects that the caller has
     *           `resourcemanager.projects.get` permission to. If multiple fields are
     *           included in the query, the it will return results that match any of the
     *           fields. Some eligible fields are:
     *
     *           ```
     *           | Field                   | Description                                  |
     *           |-------------------------|----------------------------------------------|
     *           | displayName, name       | Filters by displayName.                      |
     *           | parent                  | Project's parent. (for example: folders/123,
     *           organizations/*) Prefer parent field over parent.type and parent.id. |
     *           | parent.type             | Parent's type: `folder` or `organization`.   |
     *           | parent.id               | Parent's id number (for example: 123)        |
     *           | id, projectId           | Filters by projectId.                        |
     *           | state, lifecycleState   | Filters by state.                            |
     *           | labels                  | Filters by label name or value.              |
     *           | labels.<key> (where *key* is the name of a label) | Filters by label
     *           name. |
     *           ```
     *
     *           Search expressions are case insensitive.
     *
     *           Some examples queries:
     *
     *           ```
     *           | Query            | Description                                         |
     *           |------------------|-----------------------------------------------------|
     *           | name:how*        | The project's name starts with "how".               |
     *           | name:Howl        | The project's name is `Howl` or `howl`.             |
     *           | name:HOWL        | Equivalent to above.                                |
     *           | NAME:howl        | Equivalent to above.                                |
     *           | labels.color:*   | The project has the label `color`.                  |
     *           | labels.color:red | The project's label `color` has the value `red`.    |
     *           | labels.color:red&nbsp;labels.size:big | The project's label `color` has
     *           the value `red` and its label `size` has the value `big`.                |
     *           ```
     *
     *           If no query is specified, the call will return projects for which the user
     *           has the `resourcemanager.projects.get` permission.
     *     @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 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 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 searchProjects(array $optionalArgs = [])
    {
        $request = new SearchProjectsRequest();
        if (isset($optionalArgs['query'])) {
            $request->setQuery($optionalArgs['query']);
        }

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

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

        return $this->getPagedListResponse('SearchProjects', $optionalArgs, SearchProjectsResponse::class, $request);
    }

    /**
     * Sets the IAM access control policy for the specified project.
     *
     * CAUTION: This method will replace the existing policy, and cannot be used
     * to append additional IAM settings.
     *
     * Note: Removing service accounts from policies or changing their roles can
     * render services completely inoperable. It is important to understand how
     * the service account is being used before removing or updating its roles.
     *
     * The following constraints apply when using `setIamPolicy()`:
     *
     * + Project does not support `allUsers` and `allAuthenticatedUsers` as
     * `members` in a `Binding` of a `Policy`.
     *
     * + The owner role can be granted to a `user`, `serviceAccount`, or a group
     * that is part of an organization. For example,
     * group&#64;myownpersonaldomain.com could be added as an owner to a project in
     * the myownpersonaldomain.com organization, but not the examplepetstore.com
     * organization.
     *
     * + Service accounts can be made owners of a project directly
     * without any restrictions. However, to be added as an owner, a user must be
     * invited using the Cloud Platform console and must accept the invitation.
     *
     * + A user cannot be granted the owner role using `setIamPolicy()`. The user
     * must be granted the owner role using the Cloud Platform Console and must
     * explicitly accept the invitation.
     *
     * + Invitations to grant the owner role cannot be sent using
     * `setIamPolicy()`;
     * they must be sent only using the Cloud Platform Console.
     *
     * + Membership changes that leave the project without any owners that have
     * accepted the Terms of Service (ToS) will be rejected.
     *
     * + If the project is not part of an organization, there must be at least
     * one owner who has accepted the Terms of Service (ToS) agreement in the
     * policy. Calling `setIamPolicy()` to remove the last ToS-accepted owner
     * from the policy will fail. This restriction also applies to legacy
     * projects that no longer have owners who have accepted the ToS. Edits to
     * IAM policies will be rejected until the lack of a ToS-accepting owner is
     * rectified.
     *
     * + Calling this method requires enabling the App Engine Admin API.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $resource = 'resource';
     *     $policy = new Policy();
     *     $response = $projectsClient->setIamPolicy($resource, $policy);
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param string $resource     REQUIRED: The resource for which the policy is being specified.
     *                             See the operation documentation for the appropriate value for this field.
     * @param Policy $policy       REQUIRED: The complete policy to be applied to the `resource`. The size of
     *                             the policy is limited to a few 10s of KB. An empty policy is a
     *                             valid policy but certain Cloud Platform services (such as Projects)
     *                             might reject them.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type FieldMask $updateMask
     *           OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only
     *           the fields in the mask will be modified. If no mask is provided, the
     *           following default mask is used:
     *
     *           `paths: "bindings, etag"`
     *     @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\Iam\V1\Policy
     *
     * @throws ApiException if the remote call fails
     */
    public function setIamPolicy($resource, $policy, array $optionalArgs = [])
    {
        $request = new SetIamPolicyRequest();
        $requestParamHeaders = [];
        $request->setResource($resource);
        $request->setPolicy($policy);
        $requestParamHeaders['resource'] = $resource;
        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->startCall('SetIamPolicy', Policy::class, $optionalArgs, $request)->wait();
    }

    /**
     * Returns permissions that a caller has on the specified project.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $resource = 'resource';
     *     $permissions = [];
     *     $response = $projectsClient->testIamPermissions($resource, $permissions);
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param string   $resource     REQUIRED: The resource for which the policy detail is being requested.
     *                               See the operation documentation for the appropriate value for this field.
     * @param string[] $permissions  The set of permissions to check for the `resource`. Permissions with
     *                               wildcards (such as '*' or 'storage.*') are not allowed. For more
     *                               information see
     *                               [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions).
     * @param array    $optionalArgs {
     *     Optional.
     *
     *     @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\Iam\V1\TestIamPermissionsResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function testIamPermissions($resource, $permissions, array $optionalArgs = [])
    {
        $request = new TestIamPermissionsRequest();
        $requestParamHeaders = [];
        $request->setResource($resource);
        $request->setPermissions($permissions);
        $requestParamHeaders['resource'] = $resource;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startCall('TestIamPermissions', TestIamPermissionsResponse::class, $optionalArgs, $request)->wait();
    }

    /**
     * Restores the project identified by the specified
     * `name` (for example, `projects/415104041262`).
     * You can only use this method for a project that has a lifecycle state of
     * [DELETE_REQUESTED]
     * [Projects.State.DELETE_REQUESTED].
     * After deletion starts, the project cannot be restored.
     *
     * The caller must have `resourcemanager.projects.undelete` permission for
     * this project.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $formattedName = $projectsClient->projectName('[PROJECT]');
     *     $operationResponse = $projectsClient->undeleteProject($formattedName);
     *     $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 = $projectsClient->undeleteProject($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $projectsClient->resumeOperation($operationName, 'undeleteProject');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the project (for example, `projects/415104041262`).
     *
     *                             Required.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @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 undeleteProject($name, array $optionalArgs = [])
    {
        $request = new UndeleteProjectRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        $requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
        $optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
        return $this->startOperationsCall('UndeleteProject', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }

    /**
     * Updates the `display_name` and labels of the project identified by the
     * specified `name` (for example, `projects/415104041262`). Deleting all
     * labels requires an update mask for labels field.
     *
     * The caller must have `resourcemanager.projects.update` permission for this
     * project.
     *
     * Sample code:
     * ```
     * $projectsClient = new ProjectsClient();
     * try {
     *     $project = new Project();
     *     $operationResponse = $projectsClient->updateProject($project);
     *     $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 = $projectsClient->updateProject($project);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $projectsClient->resumeOperation($operationName, 'updateProject');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $projectsClient->close();
     * }
     * ```
     *
     * @param Project $project      Required. The new definition of the project.
     * @param array   $optionalArgs {
     *     Optional.
     *
     *     @type FieldMask $updateMask
     *           Optional. An update mask to selectively update fields.
     *     @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 updateProject($project, array $optionalArgs = [])
    {
        $request = new UpdateProjectRequest();
        $requestParamHeaders = [];
        $request->setProject($project);
        $requestParamHeaders['project.name'] = $project->getName();
        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('UpdateProject', $optionalArgs, $request, $this->getOperationsClient())->wait();
    }
}
