<?php
/*
 * Copyright 2022 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/speech/v2/cloud_speech.proto
 * Updates to the above are reflected here through a refresh process.
 */

namespace Google\Cloud\Speech\V2\Gapic;

use Google\ApiCore\ApiException;
use Google\ApiCore\Call;
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\Location\GetLocationRequest;
use Google\Cloud\Location\ListLocationsRequest;
use Google\Cloud\Location\ListLocationsResponse;
use Google\Cloud\Location\Location;
use Google\Cloud\Speech\V2\BatchRecognizeFileMetadata;
use Google\Cloud\Speech\V2\BatchRecognizeRequest;
use Google\Cloud\Speech\V2\Config;
use Google\Cloud\Speech\V2\CreateCustomClassRequest;
use Google\Cloud\Speech\V2\CreatePhraseSetRequest;
use Google\Cloud\Speech\V2\CreateRecognizerRequest;
use Google\Cloud\Speech\V2\CustomClass;
use Google\Cloud\Speech\V2\DeleteCustomClassRequest;
use Google\Cloud\Speech\V2\DeletePhraseSetRequest;
use Google\Cloud\Speech\V2\DeleteRecognizerRequest;
use Google\Cloud\Speech\V2\GetConfigRequest;
use Google\Cloud\Speech\V2\GetCustomClassRequest;
use Google\Cloud\Speech\V2\GetPhraseSetRequest;
use Google\Cloud\Speech\V2\GetRecognizerRequest;
use Google\Cloud\Speech\V2\ListCustomClassesRequest;
use Google\Cloud\Speech\V2\ListCustomClassesResponse;
use Google\Cloud\Speech\V2\ListPhraseSetsRequest;
use Google\Cloud\Speech\V2\ListPhraseSetsResponse;
use Google\Cloud\Speech\V2\ListRecognizersRequest;
use Google\Cloud\Speech\V2\ListRecognizersResponse;
use Google\Cloud\Speech\V2\PhraseSet;
use Google\Cloud\Speech\V2\RecognitionConfig;
use Google\Cloud\Speech\V2\RecognitionOutputConfig;
use Google\Cloud\Speech\V2\RecognizeRequest;
use Google\Cloud\Speech\V2\RecognizeResponse;
use Google\Cloud\Speech\V2\Recognizer;
use Google\Cloud\Speech\V2\StreamingRecognizeRequest;
use Google\Cloud\Speech\V2\StreamingRecognizeResponse;
use Google\Cloud\Speech\V2\UndeleteCustomClassRequest;
use Google\Cloud\Speech\V2\UndeletePhraseSetRequest;
use Google\Cloud\Speech\V2\UndeleteRecognizerRequest;
use Google\Cloud\Speech\V2\UpdateConfigRequest;
use Google\Cloud\Speech\V2\UpdateCustomClassRequest;
use Google\Cloud\Speech\V2\UpdatePhraseSetRequest;
use Google\Cloud\Speech\V2\UpdateRecognizerRequest;
use Google\LongRunning\Operation;
use Google\Protobuf\FieldMask;

/**
 * Service Description: Enables speech transcription and resource management.
 *
 * 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:
 *
 * ```
 * $speechClient = new SpeechClient();
 * try {
 *     $formattedRecognizer = $speechClient->recognizerName('[PROJECT]', '[LOCATION]', '[RECOGNIZER]');
 *     $operationResponse = $speechClient->batchRecognize($formattedRecognizer);
 *     $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 = $speechClient->batchRecognize($formattedRecognizer);
 *     $operationName = $operationResponse->getName();
 *     // ... do other work
 *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'batchRecognize');
 *     while (!$newOperationResponse->isDone()) {
 *         // ... do other work
 *         $newOperationResponse->reload();
 *     }
 *     if ($newOperationResponse->operationSucceeded()) {
 *         $result = $newOperationResponse->getResult();
 *     // doSomethingWith($result)
 *     } else {
 *         $error = $newOperationResponse->getError();
 *         // handleError($error)
 *     }
 * } finally {
 *     $speechClient->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.
 *
 * This service has a new (beta) implementation. See {@see
 * \Google\Cloud\Speech\V2\Client\SpeechClient} to use the new surface.
 */
class SpeechGapicClient
{
    use GapicClientTrait;

    /** The name of the service. */
    const SERVICE_NAME = 'google.cloud.speech.v2.Speech';

    /** The default address of the service. */
    const SERVICE_ADDRESS = 'speech.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 static $configNameTemplate;

    private static $cryptoKeyNameTemplate;

    private static $cryptoKeyVersionNameTemplate;

    private static $customClassNameTemplate;

    private static $locationNameTemplate;

    private static $phraseSetNameTemplate;

    private static $recognizerNameTemplate;

    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/speech_client_config.json',
            'descriptorsConfigPath' => __DIR__ . '/../resources/speech_descriptor_config.php',
            'gcpApiConfigPath' => __DIR__ . '/../resources/speech_grpc_config.json',
            'credentialsConfig' => [
                'defaultScopes' => self::$serviceScopes,
            ],
            'transportConfig' => [
                'rest' => [
                    'restClientConfigPath' => __DIR__ . '/../resources/speech_rest_client_config.php',
                ],
            ],
        ];
    }

    private static function getConfigNameTemplate()
    {
        if (self::$configNameTemplate == null) {
            self::$configNameTemplate = new PathTemplate('projects/{project}/locations/{location}/config');
        }

        return self::$configNameTemplate;
    }

    private static function getCryptoKeyNameTemplate()
    {
        if (self::$cryptoKeyNameTemplate == null) {
            self::$cryptoKeyNameTemplate = new PathTemplate('projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}');
        }

        return self::$cryptoKeyNameTemplate;
    }

    private static function getCryptoKeyVersionNameTemplate()
    {
        if (self::$cryptoKeyVersionNameTemplate == null) {
            self::$cryptoKeyVersionNameTemplate = new PathTemplate('projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}');
        }

        return self::$cryptoKeyVersionNameTemplate;
    }

    private static function getCustomClassNameTemplate()
    {
        if (self::$customClassNameTemplate == null) {
            self::$customClassNameTemplate = new PathTemplate('projects/{project}/locations/{location}/customClasses/{custom_class}');
        }

        return self::$customClassNameTemplate;
    }

    private static function getLocationNameTemplate()
    {
        if (self::$locationNameTemplate == null) {
            self::$locationNameTemplate = new PathTemplate('projects/{project}/locations/{location}');
        }

        return self::$locationNameTemplate;
    }

    private static function getPhraseSetNameTemplate()
    {
        if (self::$phraseSetNameTemplate == null) {
            self::$phraseSetNameTemplate = new PathTemplate('projects/{project}/locations/{location}/phraseSets/{phrase_set}');
        }

        return self::$phraseSetNameTemplate;
    }

    private static function getRecognizerNameTemplate()
    {
        if (self::$recognizerNameTemplate == null) {
            self::$recognizerNameTemplate = new PathTemplate('projects/{project}/locations/{location}/recognizers/{recognizer}');
        }

        return self::$recognizerNameTemplate;
    }

    private static function getPathTemplateMap()
    {
        if (self::$pathTemplateMap == null) {
            self::$pathTemplateMap = [
                'config' => self::getConfigNameTemplate(),
                'cryptoKey' => self::getCryptoKeyNameTemplate(),
                'cryptoKeyVersion' => self::getCryptoKeyVersionNameTemplate(),
                'customClass' => self::getCustomClassNameTemplate(),
                'location' => self::getLocationNameTemplate(),
                'phraseSet' => self::getPhraseSetNameTemplate(),
                'recognizer' => self::getRecognizerNameTemplate(),
            ];
        }

        return self::$pathTemplateMap;
    }

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

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

    /**
     * Formats a string containing the fully-qualified path to represent a
     * crypto_key_version resource.
     *
     * @param string $project
     * @param string $location
     * @param string $keyRing
     * @param string $cryptoKey
     * @param string $cryptoKeyVersion
     *
     * @return string The formatted crypto_key_version resource.
     */
    public static function cryptoKeyVersionName($project, $location, $keyRing, $cryptoKey, $cryptoKeyVersion)
    {
        return self::getCryptoKeyVersionNameTemplate()->render([
            'project' => $project,
            'location' => $location,
            'key_ring' => $keyRing,
            'crypto_key' => $cryptoKey,
            'crypto_key_version' => $cryptoKeyVersion,
        ]);
    }

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

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

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

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

    /**
     * Parses a formatted name string and returns an associative array of the components in the name.
     * The following name formats are supported:
     * Template: Pattern
     * - config: projects/{project}/locations/{location}/config
     * - cryptoKey: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}
     * - cryptoKeyVersion: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}
     * - customClass: projects/{project}/locations/{location}/customClasses/{custom_class}
     * - location: projects/{project}/locations/{location}
     * - phraseSet: projects/{project}/locations/{location}/phraseSets/{phrase_set}
     * - recognizer: projects/{project}/locations/{location}/recognizers/{recognizer}
     *
     * 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 $apiEndpoint
     *           The address of the API remote host. May optionally include the port, formatted
     *           as "<uri>:<port>". Default 'speech.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);
    }

    /**
     * Performs batch asynchronous speech recognition: send a request with N
     * audio files and receive a long running operation that can be polled to see
     * when the transcriptions are finished.
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedRecognizer = $speechClient->recognizerName('[PROJECT]', '[LOCATION]', '[RECOGNIZER]');
     *     $operationResponse = $speechClient->batchRecognize($formattedRecognizer);
     *     $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 = $speechClient->batchRecognize($formattedRecognizer);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'batchRecognize');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $recognizer   Required. The name of the Recognizer to use during recognition. The
     *                             expected format is
     *                             `projects/{project}/locations/{location}/recognizers/{recognizer}`. The
     *                             {recognizer} segment may be set to `_` to use an empty implicit Recognizer.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RecognitionConfig $config
     *           Features and audio metadata to use for the Automatic Speech Recognition.
     *           This field in combination with the
     *           [config_mask][google.cloud.speech.v2.BatchRecognizeRequest.config_mask]
     *           field can be used to override parts of the
     *           [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config]
     *           of the Recognizer resource.
     *     @type FieldMask $configMask
     *           The list of fields in
     *           [config][google.cloud.speech.v2.BatchRecognizeRequest.config] that override
     *           the values in the
     *           [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config]
     *           of the recognizer during this recognition request. If no mask is provided,
     *           all given fields in
     *           [config][google.cloud.speech.v2.BatchRecognizeRequest.config] override the
     *           values in the recognizer for this recognition request. If a mask is
     *           provided, only the fields listed in the mask override the config in the
     *           recognizer for this recognition request. If a wildcard (`*`) is provided,
     *           [config][google.cloud.speech.v2.BatchRecognizeRequest.config] completely
     *           overrides and replaces the config in the recognizer for this recognition
     *           request.
     *     @type BatchRecognizeFileMetadata[] $files
     *           Audio files with file metadata for ASR.
     *           The maximum number of files allowed to be specified is 5.
     *     @type RecognitionOutputConfig $recognitionOutputConfig
     *           Configuration options for where to output the transcripts of each file.
     *     @type int $processingStrategy
     *           Processing strategy to use for this request.
     *           For allowed values, use constants defined on {@see \Google\Cloud\Speech\V2\BatchRecognizeRequest\ProcessingStrategy}
     *     @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 batchRecognize($recognizer, array $optionalArgs = [])
    {
        $request = new BatchRecognizeRequest();
        $requestParamHeaders = [];
        $request->setRecognizer($recognizer);
        $requestParamHeaders['recognizer'] = $recognizer;
        if (isset($optionalArgs['config'])) {
            $request->setConfig($optionalArgs['config']);
        }

        if (isset($optionalArgs['configMask'])) {
            $request->setConfigMask($optionalArgs['configMask']);
        }

        if (isset($optionalArgs['files'])) {
            $request->setFiles($optionalArgs['files']);
        }

        if (isset($optionalArgs['recognitionOutputConfig'])) {
            $request->setRecognitionOutputConfig($optionalArgs['recognitionOutputConfig']);
        }

        if (isset($optionalArgs['processingStrategy'])) {
            $request->setProcessingStrategy($optionalArgs['processingStrategy']);
        }

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

    /**
     * Creates a [CustomClass][google.cloud.speech.v2.CustomClass].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $customClass = new CustomClass();
     *     $formattedParent = $speechClient->locationName('[PROJECT]', '[LOCATION]');
     *     $operationResponse = $speechClient->createCustomClass($customClass, $formattedParent);
     *     $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 = $speechClient->createCustomClass($customClass, $formattedParent);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'createCustomClass');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param CustomClass $customClass  Required. The CustomClass to create.
     * @param string      $parent       Required. The project and location where this CustomClass will be created.
     *                                  The expected format is `projects/{project}/locations/{location}`.
     * @param array       $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the CustomClass, but do not
     *           actually create it.
     *     @type string $customClassId
     *           The ID to use for the CustomClass, which will become the final component of
     *           the CustomClass's resource name.
     *
     *           This value should be 4-63 characters, and valid characters
     *           are /[a-z][0-9]-/.
     *     @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 createCustomClass($customClass, $parent, array $optionalArgs = [])
    {
        $request = new CreateCustomClassRequest();
        $requestParamHeaders = [];
        $request->setCustomClass($customClass);
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['customClassId'])) {
            $request->setCustomClassId($optionalArgs['customClassId']);
        }

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

    /**
     * Creates a [PhraseSet][google.cloud.speech.v2.PhraseSet].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $phraseSet = new PhraseSet();
     *     $formattedParent = $speechClient->locationName('[PROJECT]', '[LOCATION]');
     *     $operationResponse = $speechClient->createPhraseSet($phraseSet, $formattedParent);
     *     $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 = $speechClient->createPhraseSet($phraseSet, $formattedParent);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'createPhraseSet');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param PhraseSet $phraseSet    Required. The PhraseSet to create.
     * @param string    $parent       Required. The project and location where this PhraseSet will be created.
     *                                The expected format is `projects/{project}/locations/{location}`.
     * @param array     $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the PhraseSet, but do not
     *           actually create it.
     *     @type string $phraseSetId
     *           The ID to use for the PhraseSet, which will become the final component of
     *           the PhraseSet's resource name.
     *
     *           This value should be 4-63 characters, and valid characters
     *           are /[a-z][0-9]-/.
     *     @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 createPhraseSet($phraseSet, $parent, array $optionalArgs = [])
    {
        $request = new CreatePhraseSetRequest();
        $requestParamHeaders = [];
        $request->setPhraseSet($phraseSet);
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['phraseSetId'])) {
            $request->setPhraseSetId($optionalArgs['phraseSetId']);
        }

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

    /**
     * Creates a [Recognizer][google.cloud.speech.v2.Recognizer].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $recognizer = new Recognizer();
     *     $formattedParent = $speechClient->locationName('[PROJECT]', '[LOCATION]');
     *     $operationResponse = $speechClient->createRecognizer($recognizer, $formattedParent);
     *     $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 = $speechClient->createRecognizer($recognizer, $formattedParent);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'createRecognizer');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param Recognizer $recognizer   Required. The Recognizer to create.
     * @param string     $parent       Required. The project and location where this Recognizer will be created.
     *                                 The expected format is `projects/{project}/locations/{location}`.
     * @param array      $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the Recognizer, but do not
     *           actually create it.
     *     @type string $recognizerId
     *           The ID to use for the Recognizer, which will become the final component of
     *           the Recognizer's resource name.
     *
     *           This value should be 4-63 characters, and valid characters
     *           are /[a-z][0-9]-/.
     *     @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 createRecognizer($recognizer, $parent, array $optionalArgs = [])
    {
        $request = new CreateRecognizerRequest();
        $requestParamHeaders = [];
        $request->setRecognizer($recognizer);
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['recognizerId'])) {
            $request->setRecognizerId($optionalArgs['recognizerId']);
        }

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

    /**
     * Deletes the [CustomClass][google.cloud.speech.v2.CustomClass].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->customClassName('[PROJECT]', '[LOCATION]', '[CUSTOM_CLASS]');
     *     $operationResponse = $speechClient->deleteCustomClass($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 = $speechClient->deleteCustomClass($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'deleteCustomClass');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the CustomClass to delete.
     *                             Format:
     *                             `projects/{project}/locations/{location}/customClasses/{custom_class}`
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the deleted CustomClass, but do
     *           not actually delete it.
     *     @type bool $allowMissing
     *           If set to true, and the CustomClass is not found, the request will succeed
     *           and  be a no-op (no Operation is recorded in this case).
     *     @type string $etag
     *           This checksum is computed by the server based on the value of other
     *           fields. This may be sent on update, undelete, and delete requests to ensure
     *           the client has an up-to-date value before proceeding.
     *     @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 deleteCustomClass($name, array $optionalArgs = [])
    {
        $request = new DeleteCustomClassRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

        if (isset($optionalArgs['etag'])) {
            $request->setEtag($optionalArgs['etag']);
        }

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

    /**
     * Deletes the [PhraseSet][google.cloud.speech.v2.PhraseSet].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->phraseSetName('[PROJECT]', '[LOCATION]', '[PHRASE_SET]');
     *     $operationResponse = $speechClient->deletePhraseSet($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 = $speechClient->deletePhraseSet($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'deletePhraseSet');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the PhraseSet to delete.
     *                             Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the deleted PhraseSet, but do not
     *           actually delete it.
     *     @type bool $allowMissing
     *           If set to true, and the PhraseSet is not found, the request will succeed
     *           and  be a no-op (no Operation is recorded in this case).
     *     @type string $etag
     *           This checksum is computed by the server based on the value of other
     *           fields. This may be sent on update, undelete, and delete requests to ensure
     *           the client has an up-to-date value before proceeding.
     *     @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 deletePhraseSet($name, array $optionalArgs = [])
    {
        $request = new DeletePhraseSetRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

        if (isset($optionalArgs['etag'])) {
            $request->setEtag($optionalArgs['etag']);
        }

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

    /**
     * Deletes the [Recognizer][google.cloud.speech.v2.Recognizer].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->recognizerName('[PROJECT]', '[LOCATION]', '[RECOGNIZER]');
     *     $operationResponse = $speechClient->deleteRecognizer($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 = $speechClient->deleteRecognizer($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'deleteRecognizer');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the Recognizer to delete.
     *                             Format: `projects/{project}/locations/{location}/recognizers/{recognizer}`
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the deleted Recognizer, but do not
     *           actually delete it.
     *     @type bool $allowMissing
     *           If set to true, and the Recognizer is not found, the request will succeed
     *           and  be a no-op (no Operation is recorded in this case).
     *     @type string $etag
     *           This checksum is computed by the server based on the value of other
     *           fields. This may be sent on update, undelete, and delete requests to ensure
     *           the client has an up-to-date value before proceeding.
     *     @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 deleteRecognizer($name, array $optionalArgs = [])
    {
        $request = new DeleteRecognizerRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['allowMissing'])) {
            $request->setAllowMissing($optionalArgs['allowMissing']);
        }

        if (isset($optionalArgs['etag'])) {
            $request->setEtag($optionalArgs['etag']);
        }

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

    /**
     * Returns the requested [Config][google.cloud.speech.v2.Config].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->configName('[PROJECT]', '[LOCATION]');
     *     $response = $speechClient->getConfig($formattedName);
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the config to retrieve. There is exactly one config
     *                             resource per project per location. The expected format is
     *                             `projects/{project}/locations/{location}/config`.
     * @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\Speech\V2\Config
     *
     * @throws ApiException if the remote call fails
     */
    public function getConfig($name, array $optionalArgs = [])
    {
        $request = new GetConfigRequest();
        $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('GetConfig', Config::class, $optionalArgs, $request)->wait();
    }

    /**
     * Returns the requested
     * [CustomClass][google.cloud.speech.v2.CustomClass].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->customClassName('[PROJECT]', '[LOCATION]', '[CUSTOM_CLASS]');
     *     $response = $speechClient->getCustomClass($formattedName);
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the CustomClass to retrieve. The expected format is
     *                             `projects/{project}/locations/{location}/customClasses/{custom_class}`.
     * @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\Speech\V2\CustomClass
     *
     * @throws ApiException if the remote call fails
     */
    public function getCustomClass($name, array $optionalArgs = [])
    {
        $request = new GetCustomClassRequest();
        $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('GetCustomClass', CustomClass::class, $optionalArgs, $request)->wait();
    }

    /**
     * Returns the requested
     * [PhraseSet][google.cloud.speech.v2.PhraseSet].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->phraseSetName('[PROJECT]', '[LOCATION]', '[PHRASE_SET]');
     *     $response = $speechClient->getPhraseSet($formattedName);
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the PhraseSet to retrieve. The expected format is
     *                             `projects/{project}/locations/{location}/phraseSets/{phrase_set}`.
     * @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\Speech\V2\PhraseSet
     *
     * @throws ApiException if the remote call fails
     */
    public function getPhraseSet($name, array $optionalArgs = [])
    {
        $request = new GetPhraseSetRequest();
        $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('GetPhraseSet', PhraseSet::class, $optionalArgs, $request)->wait();
    }

    /**
     * Returns the requested
     * [Recognizer][google.cloud.speech.v2.Recognizer]. Fails with
     * [NOT_FOUND][google.rpc.Code.NOT_FOUND] if the requested Recognizer doesn't
     * exist.
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->recognizerName('[PROJECT]', '[LOCATION]', '[RECOGNIZER]');
     *     $response = $speechClient->getRecognizer($formattedName);
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the Recognizer to retrieve. The expected format is
     *                             `projects/{project}/locations/{location}/recognizers/{recognizer}`.
     * @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\Speech\V2\Recognizer
     *
     * @throws ApiException if the remote call fails
     */
    public function getRecognizer($name, array $optionalArgs = [])
    {
        $request = new GetRecognizerRequest();
        $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('GetRecognizer', Recognizer::class, $optionalArgs, $request)->wait();
    }

    /**
     * Lists CustomClasses.
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedParent = $speechClient->locationName('[PROJECT]', '[LOCATION]');
     *     // Iterate over pages of elements
     *     $pagedResponse = $speechClient->listCustomClasses($formattedParent);
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $speechClient->listCustomClasses($formattedParent);
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The project and location of CustomClass resources to list. The
     *                             expected format is `projects/{project}/locations/{location}`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @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 bool $showDeleted
     *           Whether, or not, to show resources that have been deleted.
     *     @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 listCustomClasses($parent, array $optionalArgs = [])
    {
        $request = new ListCustomClassesRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['pageSize'])) {
            $request->setPageSize($optionalArgs['pageSize']);
        }

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

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

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

    /**
     * Lists PhraseSets.
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedParent = $speechClient->locationName('[PROJECT]', '[LOCATION]');
     *     // Iterate over pages of elements
     *     $pagedResponse = $speechClient->listPhraseSets($formattedParent);
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $speechClient->listPhraseSets($formattedParent);
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The project and location of PhraseSet resources to list. The
     *                             expected format is `projects/{project}/locations/{location}`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @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 bool $showDeleted
     *           Whether, or not, to show resources that have been deleted.
     *     @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 listPhraseSets($parent, array $optionalArgs = [])
    {
        $request = new ListPhraseSetsRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['pageSize'])) {
            $request->setPageSize($optionalArgs['pageSize']);
        }

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

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

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

    /**
     * Lists Recognizers.
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedParent = $speechClient->locationName('[PROJECT]', '[LOCATION]');
     *     // Iterate over pages of elements
     *     $pagedResponse = $speechClient->listRecognizers($formattedParent);
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $speechClient->listRecognizers($formattedParent);
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $parent       Required. The project and location of Recognizers to list. The expected
     *                             format is `projects/{project}/locations/{location}`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @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 bool $showDeleted
     *           Whether, or not, to show resources that have been deleted.
     *     @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 listRecognizers($parent, array $optionalArgs = [])
    {
        $request = new ListRecognizersRequest();
        $requestParamHeaders = [];
        $request->setParent($parent);
        $requestParamHeaders['parent'] = $parent;
        if (isset($optionalArgs['pageSize'])) {
            $request->setPageSize($optionalArgs['pageSize']);
        }

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

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

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

    /**
     * Performs synchronous Speech recognition: receive results after all audio
     * has been sent and processed.
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedRecognizer = $speechClient->recognizerName('[PROJECT]', '[LOCATION]', '[RECOGNIZER]');
     *     $response = $speechClient->recognize($formattedRecognizer);
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $recognizer   Required. The name of the Recognizer to use during recognition. The
     *                             expected format is
     *                             `projects/{project}/locations/{location}/recognizers/{recognizer}`. The
     *                             {recognizer} segment may be set to `_` to use an empty implicit Recognizer.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type RecognitionConfig $config
     *           Features and audio metadata to use for the Automatic Speech Recognition.
     *           This field in combination with the
     *           [config_mask][google.cloud.speech.v2.RecognizeRequest.config_mask] field
     *           can be used to override parts of the
     *           [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config]
     *           of the Recognizer resource.
     *     @type FieldMask $configMask
     *           The list of fields in
     *           [config][google.cloud.speech.v2.RecognizeRequest.config] that override the
     *           values in the
     *           [default_recognition_config][google.cloud.speech.v2.Recognizer.default_recognition_config]
     *           of the recognizer during this recognition request. If no mask is provided,
     *           all non-default valued fields in
     *           [config][google.cloud.speech.v2.RecognizeRequest.config] override the
     *           values in the recognizer for this recognition request. If a mask is
     *           provided, only the fields listed in the mask override the config in the
     *           recognizer for this recognition request. If a wildcard (`*`) is provided,
     *           [config][google.cloud.speech.v2.RecognizeRequest.config] completely
     *           overrides and replaces the config in the recognizer for this recognition
     *           request.
     *     @type string $content
     *           The audio data bytes encoded as specified in
     *           [RecognitionConfig][google.cloud.speech.v2.RecognitionConfig]. As
     *           with all bytes fields, proto buffers use a pure binary representation,
     *           whereas JSON representations use base64.
     *     @type string $uri
     *           URI that points to a file that contains audio data bytes as specified in
     *           [RecognitionConfig][google.cloud.speech.v2.RecognitionConfig]. The file
     *           must not be compressed (for example, gzip). Currently, only Google Cloud
     *           Storage URIs are supported, which must be specified in the following
     *           format: `gs://bucket_name/object_name` (other URI formats return
     *           [INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more
     *           information, see [Request
     *           URIs](https://cloud.google.com/storage/docs/reference-uris).
     *     @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\Speech\V2\RecognizeResponse
     *
     * @throws ApiException if the remote call fails
     */
    public function recognize($recognizer, array $optionalArgs = [])
    {
        $request = new RecognizeRequest();
        $requestParamHeaders = [];
        $request->setRecognizer($recognizer);
        $requestParamHeaders['recognizer'] = $recognizer;
        if (isset($optionalArgs['config'])) {
            $request->setConfig($optionalArgs['config']);
        }

        if (isset($optionalArgs['configMask'])) {
            $request->setConfigMask($optionalArgs['configMask']);
        }

        if (isset($optionalArgs['content'])) {
            $request->setContent($optionalArgs['content']);
        }

        if (isset($optionalArgs['uri'])) {
            $request->setUri($optionalArgs['uri']);
        }

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

    /**
     * Performs bidirectional streaming speech recognition: receive results while
     * sending audio. This method is only available via the gRPC API (not REST).
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $recognizer = 'recognizer';
     *     $request = new StreamingRecognizeRequest();
     *     $request->setRecognizer($recognizer);
     *     // Write all requests to the server, then read all responses until the
     *     // stream is complete
     *     $requests = [
     *         $request,
     *     ];
     *     $stream = $speechClient->streamingRecognize();
     *     $stream->writeAll($requests);
     *     foreach ($stream->closeWriteAndReadAll() as $element) {
     *         // doSomethingWith($element);
     *     }
     *     // Alternatively:
     *     // Write requests individually, making read() calls if
     *     // required. Call closeWrite() once writes are complete, and read the
     *     // remaining responses from the server.
     *     $requests = [
     *         $request,
     *     ];
     *     $stream = $speechClient->streamingRecognize();
     *     foreach ($requests as $request) {
     *         $stream->write($request);
     *         // if required, read a single response from the stream
     *         $element = $stream->read();
     *         // doSomethingWith($element)
     *     }
     *     $stream->closeWrite();
     *     $element = $stream->read();
     *     while (!is_null($element)) {
     *         // doSomethingWith($element)
     *         $element = $stream->read();
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type int $timeoutMillis
     *           Timeout to use for this call.
     * }
     *
     * @return \Google\ApiCore\BidiStream
     *
     * @throws ApiException if the remote call fails
     */
    public function streamingRecognize(array $optionalArgs = [])
    {
        return $this->startCall('StreamingRecognize', StreamingRecognizeResponse::class, $optionalArgs, null, Call::BIDI_STREAMING_CALL);
    }

    /**
     * Undeletes the [CustomClass][google.cloud.speech.v2.CustomClass].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->customClassName('[PROJECT]', '[LOCATION]', '[CUSTOM_CLASS]');
     *     $operationResponse = $speechClient->undeleteCustomClass($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 = $speechClient->undeleteCustomClass($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'undeleteCustomClass');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the CustomClass to undelete.
     *                             Format:
     *                             `projects/{project}/locations/{location}/customClasses/{custom_class}`
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the undeleted CustomClass, but do
     *           not actually undelete it.
     *     @type string $etag
     *           This checksum is computed by the server based on the value of other
     *           fields. This may be sent on update, undelete, and delete requests to ensure
     *           the client has an up-to-date value before proceeding.
     *     @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 undeleteCustomClass($name, array $optionalArgs = [])
    {
        $request = new UndeleteCustomClassRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['etag'])) {
            $request->setEtag($optionalArgs['etag']);
        }

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

    /**
     * Undeletes the [PhraseSet][google.cloud.speech.v2.PhraseSet].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->phraseSetName('[PROJECT]', '[LOCATION]', '[PHRASE_SET]');
     *     $operationResponse = $speechClient->undeletePhraseSet($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 = $speechClient->undeletePhraseSet($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'undeletePhraseSet');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the PhraseSet to undelete.
     *                             Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the undeleted PhraseSet, but do
     *           not actually undelete it.
     *     @type string $etag
     *           This checksum is computed by the server based on the value of other
     *           fields. This may be sent on update, undelete, and delete requests to ensure
     *           the client has an up-to-date value before proceeding.
     *     @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 undeletePhraseSet($name, array $optionalArgs = [])
    {
        $request = new UndeletePhraseSetRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['etag'])) {
            $request->setEtag($optionalArgs['etag']);
        }

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

    /**
     * Undeletes the [Recognizer][google.cloud.speech.v2.Recognizer].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $formattedName = $speechClient->recognizerName('[PROJECT]', '[LOCATION]', '[RECOGNIZER]');
     *     $operationResponse = $speechClient->undeleteRecognizer($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 = $speechClient->undeleteRecognizer($formattedName);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'undeleteRecognizer');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param string $name         Required. The name of the Recognizer to undelete.
     *                             Format: `projects/{project}/locations/{location}/recognizers/{recognizer}`
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type bool $validateOnly
     *           If set, validate the request and preview the undeleted Recognizer, but do
     *           not actually undelete it.
     *     @type string $etag
     *           This checksum is computed by the server based on the value of other
     *           fields. This may be sent on update, undelete, and delete requests to ensure
     *           the client has an up-to-date value before proceeding.
     *     @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 undeleteRecognizer($name, array $optionalArgs = [])
    {
        $request = new UndeleteRecognizerRequest();
        $requestParamHeaders = [];
        $request->setName($name);
        $requestParamHeaders['name'] = $name;
        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

        if (isset($optionalArgs['etag'])) {
            $request->setEtag($optionalArgs['etag']);
        }

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

    /**
     * Updates the [Config][google.cloud.speech.v2.Config].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $config = new Config();
     *     $response = $speechClient->updateConfig($config);
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param Config $config       Required. The config to update.
     *
     *                             The config's `name` field is used to identify the config to be updated.
     *                             The expected format is `projects/{project}/locations/{location}/config`.
     * @param array  $optionalArgs {
     *     Optional.
     *
     *     @type FieldMask $updateMask
     *           The list of fields to be updated.
     *     @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\Speech\V2\Config
     *
     * @throws ApiException if the remote call fails
     */
    public function updateConfig($config, array $optionalArgs = [])
    {
        $request = new UpdateConfigRequest();
        $requestParamHeaders = [];
        $request->setConfig($config);
        $requestParamHeaders['config.name'] = $config->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->startCall('UpdateConfig', Config::class, $optionalArgs, $request)->wait();
    }

    /**
     * Updates the [CustomClass][google.cloud.speech.v2.CustomClass].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $customClass = new CustomClass();
     *     $operationResponse = $speechClient->updateCustomClass($customClass);
     *     $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 = $speechClient->updateCustomClass($customClass);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'updateCustomClass');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param CustomClass $customClass  Required. The CustomClass to update.
     *
     *                                  The CustomClass's `name` field is used to identify the CustomClass to
     *                                  update. Format:
     *                                  `projects/{project}/locations/{location}/customClasses/{custom_class}`.
     * @param array       $optionalArgs {
     *     Optional.
     *
     *     @type FieldMask $updateMask
     *           The list of fields to be updated. If empty, all fields are considered for
     *           update.
     *     @type bool $validateOnly
     *           If set, validate the request and preview the updated CustomClass, but do
     *           not actually update it.
     *     @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 updateCustomClass($customClass, array $optionalArgs = [])
    {
        $request = new UpdateCustomClassRequest();
        $requestParamHeaders = [];
        $request->setCustomClass($customClass);
        $requestParamHeaders['custom_class.name'] = $customClass->getName();
        if (isset($optionalArgs['updateMask'])) {
            $request->setUpdateMask($optionalArgs['updateMask']);
        }

        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

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

    /**
     * Updates the [PhraseSet][google.cloud.speech.v2.PhraseSet].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $phraseSet = new PhraseSet();
     *     $operationResponse = $speechClient->updatePhraseSet($phraseSet);
     *     $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 = $speechClient->updatePhraseSet($phraseSet);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'updatePhraseSet');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param PhraseSet $phraseSet    Required. The PhraseSet to update.
     *
     *                                The PhraseSet's `name` field is used to identify the PhraseSet to update.
     *                                Format: `projects/{project}/locations/{location}/phraseSets/{phrase_set}`.
     * @param array     $optionalArgs {
     *     Optional.
     *
     *     @type FieldMask $updateMask
     *           The list of fields to update. If empty, all non-default valued fields are
     *           considered for update. Use `*` to update the entire PhraseSet resource.
     *     @type bool $validateOnly
     *           If set, validate the request and preview the updated PhraseSet, but do not
     *           actually update it.
     *     @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 updatePhraseSet($phraseSet, array $optionalArgs = [])
    {
        $request = new UpdatePhraseSetRequest();
        $requestParamHeaders = [];
        $request->setPhraseSet($phraseSet);
        $requestParamHeaders['phrase_set.name'] = $phraseSet->getName();
        if (isset($optionalArgs['updateMask'])) {
            $request->setUpdateMask($optionalArgs['updateMask']);
        }

        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

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

    /**
     * Updates the [Recognizer][google.cloud.speech.v2.Recognizer].
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $recognizer = new Recognizer();
     *     $operationResponse = $speechClient->updateRecognizer($recognizer);
     *     $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 = $speechClient->updateRecognizer($recognizer);
     *     $operationName = $operationResponse->getName();
     *     // ... do other work
     *     $newOperationResponse = $speechClient->resumeOperation($operationName, 'updateRecognizer');
     *     while (!$newOperationResponse->isDone()) {
     *         // ... do other work
     *         $newOperationResponse->reload();
     *     }
     *     if ($newOperationResponse->operationSucceeded()) {
     *         $result = $newOperationResponse->getResult();
     *     // doSomethingWith($result)
     *     } else {
     *         $error = $newOperationResponse->getError();
     *         // handleError($error)
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param Recognizer $recognizer   Required. The Recognizer to update.
     *
     *                                 The Recognizer's `name` field is used to identify the Recognizer to update.
     *                                 Format: `projects/{project}/locations/{location}/recognizers/{recognizer}`.
     * @param array      $optionalArgs {
     *     Optional.
     *
     *     @type FieldMask $updateMask
     *           The list of fields to update. If empty, all non-default valued fields are
     *           considered for update. Use `*` to update the entire Recognizer resource.
     *     @type bool $validateOnly
     *           If set, validate the request and preview the updated Recognizer, but do not
     *           actually update it.
     *     @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 updateRecognizer($recognizer, array $optionalArgs = [])
    {
        $request = new UpdateRecognizerRequest();
        $requestParamHeaders = [];
        $request->setRecognizer($recognizer);
        $requestParamHeaders['recognizer.name'] = $recognizer->getName();
        if (isset($optionalArgs['updateMask'])) {
            $request->setUpdateMask($optionalArgs['updateMask']);
        }

        if (isset($optionalArgs['validateOnly'])) {
            $request->setValidateOnly($optionalArgs['validateOnly']);
        }

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

    /**
     * Gets information about a location.
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     $response = $speechClient->getLocation();
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $name
     *           Resource name for the location.
     *     @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\Location\Location
     *
     * @throws ApiException if the remote call fails
     */
    public function getLocation(array $optionalArgs = [])
    {
        $request = new GetLocationRequest();
        $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('GetLocation', Location::class, $optionalArgs, $request, Call::UNARY_CALL, 'google.cloud.location.Locations')->wait();
    }

    /**
     * Lists information about the supported locations for this service.
     *
     * Sample code:
     * ```
     * $speechClient = new SpeechClient();
     * try {
     *     // Iterate over pages of elements
     *     $pagedResponse = $speechClient->listLocations();
     *     foreach ($pagedResponse->iteratePages() as $page) {
     *         foreach ($page as $element) {
     *             // doSomethingWith($element);
     *         }
     *     }
     *     // Alternatively:
     *     // Iterate through all elements
     *     $pagedResponse = $speechClient->listLocations();
     *     foreach ($pagedResponse->iterateAllElements() as $element) {
     *         // doSomethingWith($element);
     *     }
     * } finally {
     *     $speechClient->close();
     * }
     * ```
     *
     * @param array $optionalArgs {
     *     Optional.
     *
     *     @type string $name
     *           The resource that owns the locations collection, if applicable.
     *     @type string $filter
     *           The standard list filter.
     *     @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 listLocations(array $optionalArgs = [])
    {
        $request = new ListLocationsRequest();
        $requestParamHeaders = [];
        if (isset($optionalArgs['name'])) {
            $request->setName($optionalArgs['name']);
            $requestParamHeaders['name'] = $optionalArgs['name'];
        }

        if (isset($optionalArgs['filter'])) {
            $request->setFilter($optionalArgs['filter']);
        }

        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('ListLocations', $optionalArgs, ListLocationsResponse::class, $request, 'google.cloud.location.Locations');
    }
}
