Cloud Translation V3 Client - Class TranslationServiceClient (1.17.5)

Reference documentation and code samples for the Cloud Translation V3 Client class TranslationServiceClient.

Service Description: Provides natural language translation operations.

This class provides the ability to make remote calls to the backing service through method calls that map to API methods.

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.

Namespace

Google \ Cloud \ Translate \ V3 \ Client

Methods

__construct

Constructor.

Parameters
NameDescription
options array

Optional. Options for configuring the service API wrapper.

↳ apiEndpoint string

The address of the API remote host. May optionally include the port, formatted as "

↳ credentials string|array|FetchAuthTokenInterface|CredentialsWrapper

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 Google\Auth\FetchAuthTokenInterface object or Google\ApiCore\CredentialsWrapper object. Note that when one of these objects are provided, any settings in $credentialsConfig will be ignored.

↳ credentialsConfig array

Options used to configure credentials, including auth token caching, for the client. For a full list of supporting configuration options, see Google\ApiCore\CredentialsWrapper::build() .

↳ disableRetries bool

Determines whether or not retries defined by the client configuration should be disabled. Defaults to false.

↳ clientConfig string|array

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.

↳ transport string|TransportInterface

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 Google\ApiCore\Transport\TransportInterface object. Note that when this object is provided, any settings in $transportConfig, and any $apiEndpoint setting, will be ignored.

↳ transportConfig array

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 Google\ApiCore\Transport\GrpcTransport::build() and Google\ApiCore\Transport\RestTransport::build() methods for the supported options.

↳ clientCertSource callable

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.

adaptiveMtTranslate

Translate text using Adaptive MT.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::adaptiveMtTranslateAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\AdaptiveMtTranslateRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\AdaptiveMtTranslateResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\AdaptiveMtTranslateRequest;
use Google\Cloud\Translate\V3\AdaptiveMtTranslateResponse;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;

/**
 * @param string $formattedParent  Location to make a regional call.
 *
 *                                 Format: `projects/{project-number-or-id}/locations/{location-id}`. Please see
 *                                 {@see TranslationServiceClient::locationName()} for help formatting this field.
 * @param string $formattedDataset The resource name for the dataset to use for adaptive MT.
 *                                 `projects/{project}/locations/{location-id}/adaptiveMtDatasets/{dataset}`
 *                                 Please see {@see TranslationServiceClient::adaptiveMtDatasetName()} for help formatting this field.
 * @param string $contentElement   The content of the input in string format.
 *                                 For now only one sentence per request is supported.
 */
function adaptive_mt_translate_sample(
    string $formattedParent,
    string $formattedDataset,
    string $contentElement
): void {
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $content = [$contentElement,];
    $request = (new AdaptiveMtTranslateRequest())
        ->setParent($formattedParent)
        ->setDataset($formattedDataset)
        ->setContent($content);

    // Call the API and handle any network failures.
    try {
        /** @var AdaptiveMtTranslateResponse $response */
        $response = $translationServiceClient->adaptiveMtTranslate($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');
    $formattedDataset = TranslationServiceClient::adaptiveMtDatasetName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]'
    );
    $contentElement = '[CONTENT]';

    adaptive_mt_translate_sample($formattedParent, $formattedDataset, $contentElement);
}

batchTranslateDocument

Translates a large volume of document in asynchronous batch mode.

This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location.

This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::batchTranslateDocumentAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\BatchTranslateDocumentRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Translate\V3\BatchDocumentInputConfig;
use Google\Cloud\Translate\V3\BatchDocumentOutputConfig;
use Google\Cloud\Translate\V3\BatchTranslateDocumentRequest;
use Google\Cloud\Translate\V3\BatchTranslateDocumentResponse;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Rpc\Status;

/**
 * @param string $formattedParent            Location to make a regional call.
 *
 *                                           Format: `projects/{project-number-or-id}/locations/{location-id}`.
 *
 *                                           The `global` location is not supported for batch translation.
 *
 *                                           Only AutoML Translation models or glossaries within the same region (have
 *                                           the same location-id) can be used, otherwise an INVALID_ARGUMENT (400)
 *                                           error is returned. Please see
 *                                           {@see TranslationServiceClient::locationName()} for help formatting this field.
 * @param string $sourceLanguageCode         The ISO-639 language code of the input document if known, for
 *                                           example, "en-US" or "sr-Latn". Supported language codes are listed in
 *                                           [Language Support](https://cloud.google.com/translate/docs/languages).
 * @param string $targetLanguageCodesElement The ISO-639 language code to use for translation of the input
 *                                           document. Specify up to 10 language codes here.
 */
function batch_translate_document_sample(
    string $formattedParent,
    string $sourceLanguageCode,
    string $targetLanguageCodesElement
): void {
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $targetLanguageCodes = [$targetLanguageCodesElement,];
    $inputConfigs = [new BatchDocumentInputConfig()];
    $outputConfig = new BatchDocumentOutputConfig();
    $request = (new BatchTranslateDocumentRequest())
        ->setParent($formattedParent)
        ->setSourceLanguageCode($sourceLanguageCode)
        ->setTargetLanguageCodes($targetLanguageCodes)
        ->setInputConfigs($inputConfigs)
        ->setOutputConfig($outputConfig);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $translationServiceClient->batchTranslateDocument($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var BatchTranslateDocumentResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');
    $sourceLanguageCode = '[SOURCE_LANGUAGE_CODE]';
    $targetLanguageCodesElement = '[TARGET_LANGUAGE_CODES]';

    batch_translate_document_sample($formattedParent, $sourceLanguageCode, $targetLanguageCodesElement);
}

batchTranslateText

Translates a large volume of text in asynchronous batch mode.

This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location.

This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::batchTranslateTextAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\BatchTranslateTextRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Translate\V3\BatchTranslateResponse;
use Google\Cloud\Translate\V3\BatchTranslateTextRequest;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\InputConfig;
use Google\Cloud\Translate\V3\OutputConfig;
use Google\Rpc\Status;

/**
 * @param string $formattedParent            Location to make a call. Must refer to a caller's project.
 *
 *                                           Format: `projects/{project-number-or-id}/locations/{location-id}`.
 *
 *                                           The `global` location is not supported for batch translation.
 *
 *                                           Only AutoML Translation models or glossaries within the same region (have
 *                                           the same location-id) can be used, otherwise an INVALID_ARGUMENT (400)
 *                                           error is returned. Please see
 *                                           {@see TranslationServiceClient::locationName()} for help formatting this field.
 * @param string $sourceLanguageCode         Source language code.
 * @param string $targetLanguageCodesElement Specify up to 10 language codes here.
 */
function batch_translate_text_sample(
    string $formattedParent,
    string $sourceLanguageCode,
    string $targetLanguageCodesElement
): void {
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $targetLanguageCodes = [$targetLanguageCodesElement,];
    $inputConfigs = [new InputConfig()];
    $outputConfig = new OutputConfig();
    $request = (new BatchTranslateTextRequest())
        ->setParent($formattedParent)
        ->setSourceLanguageCode($sourceLanguageCode)
        ->setTargetLanguageCodes($targetLanguageCodes)
        ->setInputConfigs($inputConfigs)
        ->setOutputConfig($outputConfig);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $translationServiceClient->batchTranslateText($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var BatchTranslateResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');
    $sourceLanguageCode = '[SOURCE_LANGUAGE_CODE]';
    $targetLanguageCodesElement = '[TARGET_LANGUAGE_CODES]';

    batch_translate_text_sample($formattedParent, $sourceLanguageCode, $targetLanguageCodesElement);
}

createAdaptiveMtDataset

Parameters
NameDescription
request Google\Cloud\Translate\V3\CreateAdaptiveMtDatasetRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\AdaptiveMtDataset
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\AdaptiveMtDataset;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\CreateAdaptiveMtDatasetRequest;

/**
 * @param string $formattedParent                Name of the parent project. In form of
 *                                               `projects/{project-number-or-id}/locations/{location-id}`
 *                                               Please see {@see TranslationServiceClient::locationName()} for help formatting this field.
 * @param string $formattedAdaptiveMtDatasetName The resource name of the dataset, in form of
 *                                               `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset_id}`
 *                                               Please see {@see TranslationServiceClient::adaptiveMtDatasetName()} for help formatting this field.
 */
function create_adaptive_mt_dataset_sample(
    string $formattedParent,
    string $formattedAdaptiveMtDatasetName
): void {
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $adaptiveMtDataset = (new AdaptiveMtDataset())
        ->setName($formattedAdaptiveMtDatasetName);
    $request = (new CreateAdaptiveMtDatasetRequest())
        ->setParent($formattedParent)
        ->setAdaptiveMtDataset($adaptiveMtDataset);

    // Call the API and handle any network failures.
    try {
        /** @var AdaptiveMtDataset $response */
        $response = $translationServiceClient->createAdaptiveMtDataset($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');
    $formattedAdaptiveMtDatasetName = TranslationServiceClient::adaptiveMtDatasetName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]'
    );

    create_adaptive_mt_dataset_sample($formattedParent, $formattedAdaptiveMtDatasetName);
}

createGlossary

Creates a glossary and returns the long-running operation. Returns NOT_FOUND, if the project doesn't exist.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::createGlossaryAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\CreateGlossaryRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\CreateGlossaryRequest;
use Google\Cloud\Translate\V3\Glossary;
use Google\Rpc\Status;

/**
 * @param string $formattedParent The project name. Please see
 *                                {@see TranslationServiceClient::locationName()} for help formatting this field.
 * @param string $glossaryName    The resource name of the glossary. Glossary names have the form
 *                                `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`.
 */
function create_glossary_sample(string $formattedParent, string $glossaryName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $glossary = (new Glossary())
        ->setName($glossaryName);
    $request = (new CreateGlossaryRequest())
        ->setParent($formattedParent)
        ->setGlossary($glossary);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $translationServiceClient->createGlossary($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var Glossary $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');
    $glossaryName = '[NAME]';

    create_glossary_sample($formattedParent, $glossaryName);
}

deleteAdaptiveMtDataset

Deletes an Adaptive MT dataset, including all its entries and associated metadata.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::deleteAdaptiveMtDatasetAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\DeleteAdaptiveMtDatasetRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\DeleteAdaptiveMtDatasetRequest;

/**
 * @param string $formattedName Name of the dataset. In the form of
 *                              `projects/{project-number-or-id}/locations/{location-id}/adaptiveMtDatasets/{adaptive-mt-dataset-id}`
 *                              Please see {@see TranslationServiceClient::adaptiveMtDatasetName()} for help formatting this field.
 */
function delete_adaptive_mt_dataset_sample(string $formattedName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new DeleteAdaptiveMtDatasetRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        $translationServiceClient->deleteAdaptiveMtDataset($request);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = TranslationServiceClient::adaptiveMtDatasetName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]'
    );

    delete_adaptive_mt_dataset_sample($formattedName);
}

deleteAdaptiveMtFile

Deletes an AdaptiveMtFile along with its sentences.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::deleteAdaptiveMtFileAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\DeleteAdaptiveMtFileRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\DeleteAdaptiveMtFileRequest;

/**
 * @param string $formattedName The resource name of the file to delete, in form of
 *                              `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}`
 *                              Please see {@see TranslationServiceClient::adaptiveMtFileName()} for help formatting this field.
 */
function delete_adaptive_mt_file_sample(string $formattedName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new DeleteAdaptiveMtFileRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        $translationServiceClient->deleteAdaptiveMtFile($request);
        printf('Call completed successfully.' . PHP_EOL);
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = TranslationServiceClient::adaptiveMtFileName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]',
        '[FILE]'
    );

    delete_adaptive_mt_file_sample($formattedName);
}

deleteGlossary

Deletes a glossary, or cancels glossary construction if the glossary isn't created yet.

Returns NOT_FOUND, if the glossary doesn't exist.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::deleteGlossaryAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\DeleteGlossaryRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\OperationResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\DeleteGlossaryRequest;
use Google\Cloud\Translate\V3\DeleteGlossaryResponse;
use Google\Rpc\Status;

/**
 * @param string $formattedName The name of the glossary to delete. Please see
 *                              {@see TranslationServiceClient::glossaryName()} for help formatting this field.
 */
function delete_glossary_sample(string $formattedName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new DeleteGlossaryRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $translationServiceClient->deleteGlossary($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var DeleteGlossaryResponse $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = TranslationServiceClient::glossaryName('[PROJECT]', '[LOCATION]', '[GLOSSARY]');

    delete_glossary_sample($formattedName);
}

detectLanguage

Detects the language of text within a request.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::detectLanguageAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\DetectLanguageRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\DetectLanguageResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\DetectLanguageRequest;
use Google\Cloud\Translate\V3\DetectLanguageResponse;

/**
 * @param string $formattedParent Project or location to make a call. Must refer to a caller's
 *                                project.
 *
 *                                Format: `projects/{project-number-or-id}/locations/{location-id}` or
 *                                `projects/{project-number-or-id}`.
 *
 *                                For global calls, use `projects/{project-number-or-id}/locations/global` or
 *                                `projects/{project-number-or-id}`.
 *
 *                                Only models within the same region (has same location-id) can be used.
 *                                Otherwise an INVALID_ARGUMENT (400) error is returned. Please see
 *                                {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function detect_language_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new DetectLanguageRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var DetectLanguageResponse $response */
        $response = $translationServiceClient->detectLanguage($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    detect_language_sample($formattedParent);
}

getAdaptiveMtDataset

Parameters
NameDescription
request Google\Cloud\Translate\V3\GetAdaptiveMtDatasetRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\AdaptiveMtDataset
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\AdaptiveMtDataset;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\GetAdaptiveMtDatasetRequest;

/**
 * @param string $formattedName Name of the dataset. In the form of
 *                              `projects/{project-number-or-id}/locations/{location-id}/adaptiveMtDatasets/{adaptive-mt-dataset-id}`
 *                              Please see {@see TranslationServiceClient::adaptiveMtDatasetName()} for help formatting this field.
 */
function get_adaptive_mt_dataset_sample(string $formattedName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new GetAdaptiveMtDatasetRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        /** @var AdaptiveMtDataset $response */
        $response = $translationServiceClient->getAdaptiveMtDataset($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = TranslationServiceClient::adaptiveMtDatasetName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]'
    );

    get_adaptive_mt_dataset_sample($formattedName);
}

getAdaptiveMtFile

Parameters
NameDescription
request Google\Cloud\Translate\V3\GetAdaptiveMtFileRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\AdaptiveMtFile
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\AdaptiveMtFile;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\GetAdaptiveMtFileRequest;

/**
 * @param string $formattedName The resource name of the file, in form of
 *                              `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}`
 *                              Please see {@see TranslationServiceClient::adaptiveMtFileName()} for help formatting this field.
 */
function get_adaptive_mt_file_sample(string $formattedName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new GetAdaptiveMtFileRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        /** @var AdaptiveMtFile $response */
        $response = $translationServiceClient->getAdaptiveMtFile($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = TranslationServiceClient::adaptiveMtFileName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]',
        '[FILE]'
    );

    get_adaptive_mt_file_sample($formattedName);
}

getGlossary

Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::getGlossaryAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\GetGlossaryRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\Glossary
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\GetGlossaryRequest;
use Google\Cloud\Translate\V3\Glossary;

/**
 * @param string $formattedName The name of the glossary to retrieve. Please see
 *                              {@see TranslationServiceClient::glossaryName()} for help formatting this field.
 */
function get_glossary_sample(string $formattedName): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new GetGlossaryRequest())
        ->setName($formattedName);

    // Call the API and handle any network failures.
    try {
        /** @var Glossary $response */
        $response = $translationServiceClient->getGlossary($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedName = TranslationServiceClient::glossaryName('[PROJECT]', '[LOCATION]', '[GLOSSARY]');

    get_glossary_sample($formattedName);
}

getSupportedLanguages

Returns a list of supported languages for translation.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::getSupportedLanguagesAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\GetSupportedLanguagesRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\SupportedLanguages
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\GetSupportedLanguagesRequest;
use Google\Cloud\Translate\V3\SupportedLanguages;

/**
 * @param string $formattedParent Project or location to make a call. Must refer to a caller's
 *                                project.
 *
 *                                Format: `projects/{project-number-or-id}` or
 *                                `projects/{project-number-or-id}/locations/{location-id}`.
 *
 *                                For global calls, use `projects/{project-number-or-id}/locations/global` or
 *                                `projects/{project-number-or-id}`.
 *
 *                                Non-global location is required for AutoML models.
 *
 *                                Only models within the same region (have same location-id) can be used,
 *                                otherwise an INVALID_ARGUMENT (400) error is returned. Please see
 *                                {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function get_supported_languages_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new GetSupportedLanguagesRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var SupportedLanguages $response */
        $response = $translationServiceClient->getSupportedLanguages($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    get_supported_languages_sample($formattedParent);
}

importAdaptiveMtFile

Imports an AdaptiveMtFile and adds all of its sentences into the AdaptiveMtDataset.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::importAdaptiveMtFileAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\ImportAdaptiveMtFileRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\ImportAdaptiveMtFileResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\ImportAdaptiveMtFileRequest;
use Google\Cloud\Translate\V3\ImportAdaptiveMtFileResponse;

/**
 * @param string $formattedParent The resource name of the file, in form of
 *                                `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}`
 *                                Please see {@see TranslationServiceClient::adaptiveMtDatasetName()} for help formatting this field.
 */
function import_adaptive_mt_file_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new ImportAdaptiveMtFileRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var ImportAdaptiveMtFileResponse $response */
        $response = $translationServiceClient->importAdaptiveMtFile($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::adaptiveMtDatasetName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]'
    );

    import_adaptive_mt_file_sample($formattedParent);
}

listAdaptiveMtDatasets

Lists all Adaptive MT datasets for which the caller has read permission.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::listAdaptiveMtDatasetsAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\ListAdaptiveMtDatasetsRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Translate\V3\AdaptiveMtDataset;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\ListAdaptiveMtDatasetsRequest;

/**
 * @param string $formattedParent The resource name of the project from which to list the Adaptive
 *                                MT datasets. `projects/{project-number-or-id}/locations/{location-id}`
 *                                Please see {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function list_adaptive_mt_datasets_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new ListAdaptiveMtDatasetsRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $translationServiceClient->listAdaptiveMtDatasets($request);

        /** @var AdaptiveMtDataset $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    list_adaptive_mt_datasets_sample($formattedParent);
}

listAdaptiveMtFiles

Lists all AdaptiveMtFiles associated to an AdaptiveMtDataset.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::listAdaptiveMtFilesAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\ListAdaptiveMtFilesRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Translate\V3\AdaptiveMtFile;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\ListAdaptiveMtFilesRequest;

/**
 * @param string $formattedParent The resource name of the project from which to list the Adaptive
 *                                MT files.
 *                                `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}`
 *                                Please see {@see TranslationServiceClient::adaptiveMtDatasetName()} for help formatting this field.
 */
function list_adaptive_mt_files_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new ListAdaptiveMtFilesRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $translationServiceClient->listAdaptiveMtFiles($request);

        /** @var AdaptiveMtFile $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::adaptiveMtDatasetName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]'
    );

    list_adaptive_mt_files_sample($formattedParent);
}

listAdaptiveMtSentences

Lists all AdaptiveMtSentences under a given file/dataset.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::listAdaptiveMtSentencesAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\ListAdaptiveMtSentencesRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Translate\V3\AdaptiveMtSentence;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\ListAdaptiveMtSentencesRequest;

/**
 * @param string $formattedParent The resource name of the project from which to list the Adaptive
 *                                MT files. The following format lists all sentences under a file.
 *                                `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}`
 *                                The following format lists all sentences within a dataset.
 *                                `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}`
 *                                Please see {@see TranslationServiceClient::adaptiveMtFileName()} for help formatting this field.
 */
function list_adaptive_mt_sentences_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new ListAdaptiveMtSentencesRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $translationServiceClient->listAdaptiveMtSentences($request);

        /** @var AdaptiveMtSentence $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::adaptiveMtFileName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATASET]',
        '[FILE]'
    );

    list_adaptive_mt_sentences_sample($formattedParent);
}

listGlossaries

Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't exist.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::listGlossariesAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\ListGlossariesRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\Glossary;
use Google\Cloud\Translate\V3\ListGlossariesRequest;

/**
 * @param string $formattedParent The name of the project from which to list all of the glossaries. Please see
 *                                {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function list_glossaries_sample(string $formattedParent): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $request = (new ListGlossariesRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $translationServiceClient->listGlossaries($request);

        /** @var Glossary $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    list_glossaries_sample($formattedParent);
}

translateDocument

Translates documents in synchronous mode.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::translateDocumentAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\TranslateDocumentRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\TranslateDocumentResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\DocumentInputConfig;
use Google\Cloud\Translate\V3\TranslateDocumentRequest;
use Google\Cloud\Translate\V3\TranslateDocumentResponse;

/**
 * @param string $parent             Location to make a regional call.
 *
 *                                   Format: `projects/{project-number-or-id}/locations/{location-id}`.
 *
 *                                   For global calls, use `projects/{project-number-or-id}/locations/global` or
 *                                   `projects/{project-number-or-id}`.
 *
 *                                   Non-global location is required for requests using AutoML models or custom
 *                                   glossaries.
 *
 *                                   Models and glossaries must be within the same region (have the same
 *                                   location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
 * @param string $targetLanguageCode The ISO-639 language code to use for translation of the input
 *                                   document, set to one of the language codes listed in Language Support.
 */
function translate_document_sample(string $parent, string $targetLanguageCode): void
{
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $documentInputConfig = new DocumentInputConfig();
    $request = (new TranslateDocumentRequest())
        ->setParent($parent)
        ->setTargetLanguageCode($targetLanguageCode)
        ->setDocumentInputConfig($documentInputConfig);

    // Call the API and handle any network failures.
    try {
        /** @var TranslateDocumentResponse $response */
        $response = $translationServiceClient->translateDocument($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $parent = '[PARENT]';
    $targetLanguageCode = '[TARGET_LANGUAGE_CODE]';

    translate_document_sample($parent, $targetLanguageCode);
}

translateText

Translates input text and returns translated text.

The async variant is Google\Cloud\Translate\V3\Client\TranslationServiceClient::translateTextAsync() .

Parameters
NameDescription
request Google\Cloud\Translate\V3\TranslateTextRequest

A request to house fields associated with the call.

callOptions array

Optional.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\Cloud\Translate\V3\TranslateTextResponse
Example
use Google\ApiCore\ApiException;
use Google\Cloud\Translate\V3\Client\TranslationServiceClient;
use Google\Cloud\Translate\V3\TranslateTextRequest;
use Google\Cloud\Translate\V3\TranslateTextResponse;

/**
 * @param string $contentsElement    The content of the input in string format.
 *                                   We recommend the total content be less than 30,000 codepoints. The max
 *                                   length of this field is 1024. Use BatchTranslateText for larger text.
 * @param string $targetLanguageCode The ISO-639 language code to use for translation of the input
 *                                   text, set to one of the language codes listed in Language Support.
 * @param string $formattedParent    Project or location to make a call. Must refer to a caller's
 *                                   project.
 *
 *                                   Format: `projects/{project-number-or-id}` or
 *                                   `projects/{project-number-or-id}/locations/{location-id}`.
 *
 *                                   For global calls, use `projects/{project-number-or-id}/locations/global` or
 *                                   `projects/{project-number-or-id}`.
 *
 *                                   Non-global location is required for requests using AutoML models or
 *                                   custom glossaries.
 *
 *                                   Models and glossaries must be within the same region (have same
 *                                   location-id), otherwise an INVALID_ARGUMENT (400) error is returned. Please see
 *                                   {@see TranslationServiceClient::locationName()} for help formatting this field.
 */
function translate_text_sample(
    string $contentsElement,
    string $targetLanguageCode,
    string $formattedParent
): void {
    // Create a client.
    $translationServiceClient = new TranslationServiceClient();

    // Prepare the request message.
    $contents = [$contentsElement,];
    $request = (new TranslateTextRequest())
        ->setContents($contents)
        ->setTargetLanguageCode($targetLanguageCode)
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var TranslateTextResponse $response */
        $response = $translationServiceClient->translateText($request);
        printf('Response data: %s' . PHP_EOL, $response->serializeToJsonString());
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $contentsElement = '[CONTENTS]';
    $targetLanguageCode = '[TARGET_LANGUAGE_CODE]';
    $formattedParent = TranslationServiceClient::locationName('[PROJECT]', '[LOCATION]');

    translate_text_sample($contentsElement, $targetLanguageCode, $formattedParent);
}

adaptiveMtTranslateAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\AdaptiveMtTranslateRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

batchTranslateDocumentAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\BatchTranslateDocumentRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

batchTranslateTextAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\BatchTranslateTextRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

createAdaptiveMtDatasetAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\CreateAdaptiveMtDatasetRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

createGlossaryAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\CreateGlossaryRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

deleteAdaptiveMtDatasetAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\DeleteAdaptiveMtDatasetRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

deleteAdaptiveMtFileAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\DeleteAdaptiveMtFileRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

deleteGlossaryAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\DeleteGlossaryRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

detectLanguageAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\DetectLanguageRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

getAdaptiveMtDatasetAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\GetAdaptiveMtDatasetRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

getAdaptiveMtFileAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\GetAdaptiveMtFileRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

getGlossaryAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\GetGlossaryRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

getSupportedLanguagesAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\GetSupportedLanguagesRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

importAdaptiveMtFileAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\ImportAdaptiveMtFileRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

listAdaptiveMtDatasetsAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\ListAdaptiveMtDatasetsRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

listAdaptiveMtFilesAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\ListAdaptiveMtFilesRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

listAdaptiveMtSentencesAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\ListAdaptiveMtSentencesRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

listGlossariesAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\ListGlossariesRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

translateDocumentAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\TranslateDocumentRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

translateTextAsync

Parameters
NameDescription
request Google\Cloud\Translate\V3\TranslateTextRequest
optionalArgs = [] array
Returns
TypeDescription
GuzzleHttp\Promise\PromiseInterface

getOperationsClient

Return an OperationsClient object with the same endpoint as $this.

Returns
TypeDescription
Google\ApiCore\LongRunning\OperationsClient

resumeOperation

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.

Parameters
NameDescription
operationName string

The name of the long running operation

methodName string

The name of the method used to start the operation

Returns
TypeDescription
Google\ApiCore\OperationResponse

static::adaptiveMtDatasetName

Formats a string containing the fully-qualified path to represent a adaptive_mt_dataset resource.

Parameters
NameDescription
project string
location string
dataset string
Returns
TypeDescription
stringThe formatted adaptive_mt_dataset resource.

static::adaptiveMtFileName

Formats a string containing the fully-qualified path to represent a adaptive_mt_file resource.

Parameters
NameDescription
project string
location string
dataset string
file string
Returns
TypeDescription
stringThe formatted adaptive_mt_file resource.

static::glossaryName

Formats a string containing the fully-qualified path to represent a glossary resource.

Parameters
NameDescription
project string
location string
glossary string
Returns
TypeDescription
stringThe formatted glossary resource.

static::locationName

Formats a string containing the fully-qualified path to represent a location resource.

Parameters
NameDescription
project string
location string
Returns
TypeDescription
stringThe formatted location resource.

static::parseName

Parses a formatted name string and returns an associative array of the components in the name.

The following name formats are supported: Template: Pattern

  • adaptiveMtDataset: projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}
  • adaptiveMtFile: projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}
  • glossary: projects/{project}/locations/{location}/glossaries/{glossary}
  • location: projects/{project}/locations/{location}

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.

Parameters
NameDescription
formattedName string

The formatted name string

template string

Optional name of template to match

Returns
TypeDescription
arrayAn associative array from name component IDs to component values.