PHP code example of translations-com / globallink-connect-api-php

1. Go to this page and download the library: Download translations-com/globallink-connect-api-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

translations-com / globallink-connect-api-php example snippets


$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();



nsPerfect\GlobalLink\GlobalLinkClient;
use TransPerfect\GlobalLink\Request\CreateSubmissionRequest;
use TransPerfect\GlobalLink\Request\UploadSourceFileRequest;
use TransPerfect\GlobalLink\Request\SaveSubmissionRequest;
use TransPerfect\GlobalLink\Request\GetTargetsRequest;
use TransPerfect\GlobalLink\Model\BatchInfo;
use TransPerfect\GlobalLink\Model\CreateSubmissionTargetLanguageInfo;

// Initialize the client
$client = new GlobalLinkClient(
    getenv('GLE_API_URL'),
    getenv('GLE_USERNAME'),
    getenv('GLE_PASSWORD'),
    getenv('GLE_OAUTH_CLIENT'),
    getenv('GLE_OAUTH_SECRET')
);

// List projects
$projects = $client->getProjects();
foreach ($projects as $project) {
    echo "Project: {$project->name} ({$project->shortCode})\n";
}

// Get project details
$projectInfo = $client->getProject($projects[0]->projectId);

// Create a submission
$batch = new BatchInfo(
    name: 'Batch 1',
    targetFormat: 'TXLF',
    targetLanguageInfos: [
        new CreateSubmissionTargetLanguageInfo('de-DE'),
        new CreateSubmissionTargetLanguageInfo('fr-FR'),
    ]
);

$request = new CreateSubmissionRequest(
    name: 'My Translation Job',
    dueDate: strtotime('+7 days') * 1000, // Unix milliseconds
    projectId: $projectInfo->projectId,
    sourceLanguage: 'en-US',
    batchInfos: [$batch],
    claimScope: 'LANGUAGE'
);

$createResponse = $client->createSubmission($request);
$submissionId = $createResponse->submissionId;
echo "Created submission: {$submissionId}\n";

// Upload a source file
$uploadRequest = new UploadSourceFileRequest(
    batchName: 'Batch 1',
    file: '/path/to/source-file.xml',
    fileFormatName: 'Default XML'
);

$client->uploadSubmissionSourceFile($submissionId, $uploadRequest);

// Save and start the submission
$saveRequest = new SaveSubmissionRequest(autoStart: true);
$client->saveSubmission($submissionId, $saveRequest);

// Poll for processed targets
$targetsRequest = new GetTargetsRequest('PROCESSED', submissionIds: [$submissionId]);
$targets = $client->getTargets($targetsRequest);

foreach ($targets as $target) {
    echo "Target {$target->targetId} ({$target->targetLanguage}): {$target->status}\n";
    
    // Download the translated file
    $content = $client->downloadTargetDeliverable($submissionId, $target->targetId);
    file_put_contents("translated_{$target->targetLanguage}.xml", $content);
    
    // Confirm delivery
    $client->confirmTargetDelivery($submissionId, [$target->targetId]);
}

// Check if token is expired
if ($client->isTokenExpired()) {
    echo "Token needs refresh\n";
}

// Check if the GlobalLink instance is healthy (no authentication ho "Instance is healthy: {$health->message}\n";
} else {
    echo "Instance is down!\n";
}

$info = $client->getInstanceInfo();
echo "Version: {$info->version}\n";
echo "Max upload size: {$info->maxUploadSize}\n";
echo "Max documents per submission: {$info->maxDocumentsBeforeNewSubmission}\n";

use TransPerfect\GlobalLink\Request\ListProjectsRequest;

// List all projects
$projects = $client->getProjects();

// List projects with filters
$request = new ListProjectsRequest(
    projectName: 'Marketing',
    pageSize: 50,
    pageNumber: 0
);
$projects = $client->getProjects($request);

// Get project details
$project = $client->getProject($projectId);

// Get project configuration
$fileFormats = $client->getProjectFileFormats($projectId);
$workflows = $client->getProjectWorkflows($projectId);
$customAttributes = $client->getProjectCustomAttributes($projectId);
$languageDirections = $client->getProjectLanguageDirections($projectId);
$users = $client->getProjectOrgUsers($projectId);

// Get MSLA (priority) levels
$mslaLevels = $client->getProjectMslaLevels($projectId);
foreach ($mslaLevels as $level) {
    echo "{$level->name} [{$level->priority}]\n";
}

use TransPerfect\GlobalLink\Request\GetSubmissionsRequest;
use TransPerfect\GlobalLink\Request\UploadReferenceFileRequest;
use TransPerfect\GlobalLink\Model\TechTracking;
use TransPerfect\GlobalLink\Request\CancelSubmissionRequest;

// Create submission
$response = $client->createSubmission($request);

// Get submissions
$submissions = $client->getSubmissions();

// Get submissions with filters
$request = new GetSubmissionsRequest(
    statuses: ['IN_PROCESS', 'PROCESSED'],
    projectName: 'Marketing',
    pageSize: 50,
    pageNumber: 0
);
$submissions = $client->getSubmissions($request);

// Get single submission
$submission = $client->getSubmission($submissionId);

// Get submission wordcount (with leverage breakdown)
$wordcount = $client->getSubmissionWordcount($submissionId);
echo "Total words: {$wordcount->totalWordCount}\n";
echo "100% match: {$wordcount->match100}\n";
echo "No match: {$wordcount->noMatch}\n";

// Update submission (JSON Patch)
$submission = $client->patchSubmission($submissionId, 'replace', '/name', 'New Name');

// Upload source file
$uploadRequest = new UploadSourceFileRequest(
    batchName: 'Batch 1',
    fileContents: file_get_contents('/path/to/source.xml'),
    fileName: 'source.xml'
);
$client->uploadSubmissionSourceFile($submissionId, $uploadRequest);

// Upload reference file (glossaries, style guides, etc.)
// Option 1: From file path
$refRequest = new UploadReferenceFileRequest(
    file: '/path/to/glossary.txt',
    submissionLevel: true
);
$client->uploadSubmissionReferenceFile($submissionId, $refRequest);

// Option 2: From string contents
$refRequest = new UploadReferenceFileRequest(
    fileContents: file_get_contents('/path/to/glossary.txt'),
    fileName: 'glossary.txt',
    submissionLevel: true
);
$client->uploadSubmissionReferenceFile($submissionId, $refRequest);

// Set tech tracking (for analytics)
$techTracking = new TechTracking(
    adaptorName: 'GlobalLink Drupal Adaptor',
    adaptorVersion: '1.0.0',
    clientVersion: '11',
    technologyProduct: 'GLE'
);
$client->putSubmissionTechTracking($submissionId, $techTracking);

// Save submission (optionally auto-start)
$client->saveSubmission($submissionId, new SaveSubmissionRequest(autoStart: true));

// Cancel submission (cancel specific targets or documents)
$client->cancelSubmission($submissionId, new CancelSubmissionRequest(
    targetIds: [123, 456]  // or documentIds: [1, 2]
));

use TransPerfect\GlobalLink\Request\GetTargetsRequest;

// Get targets by status with pagination
// Note: pageSize must be between 20 and 200 (API gets = $client->getTargets($request);

// Get cancelled targets
$cancelledRequest = new GetTargetsRequest(
    targetStatus: 'CANCELLED',
    projectIds: [$projectId]
);
$cancelledTargets = $client->getTargets($cancelledRequest);

// Download single target deliverable
$content = $client->downloadTargetDeliverable($submissionId, $targetId);
file_put_contents('translated.xml', $content);

// Download all deliverables (ZIP)
$zipContent = $client->downloadSubmissionDeliverables($submissionId, $response->failedToDeliverTargets) . "\n";

use TransPerfect\GlobalLink\Exception\GlobalLinkException;
use TransPerfect\GlobalLink\Exception\ApiException;
use TransPerfect\GlobalLink\Exception\AuthenticationException;
use TransPerfect\GlobalLink\Exception\RateLimitException;
use TransPerfect\GlobalLink\Exception\InvalidArgumentException;

try {
    $projects = $client->getProjects();
} catch (AuthenticationException $e) {
    // Handle authentication errors (401/403)
    echo "Authentication failed: " . $e->getMessage();
} catch (RateLimitException $e) {
    // Handle rate limiting (429)
    echo "Rate limited. Retry after: " . $e->getRetryAfter() . " seconds";
} catch (ApiException $e) {
    // Handle other API errors (4xx/5xx)
    echo "API error ({$e->getStatusCode()}): " . $e->getMessage();
} catch (GlobalLinkException $e) {
    // Handle all SDK errors
    echo "Error: " . $e->getMessage();
}

// Access rate limit info after any request
$rateLimitInfo = $client->getRateLimitInfo();
if ($rateLimitInfo !== null) {
    echo "Requests remaining: {$rateLimitInfo['remaining']}/{$rateLimitInfo['limit']}\n";
}

use TransPerfect\GlobalLink\Http\HttpClientInterface;
use TransPerfect\GlobalLink\Http\HttpResponse;

class GuzzleHttpClient implements HttpClientInterface
{
    private \GuzzleHttp\Client $guzzle;

    public function __construct()
    {
        $this->guzzle = new \GuzzleHttp\Client();
    }

    public function send(string $method, string $url, array $headers, ?string $body = null): HttpResponse
    {
        $response = $this->guzzle->request($method, $url, [
            'headers' => $headers,
            'body' => $body,
            'http_errors' => false,
        ]);

        return new HttpResponse(
            $response->getStatusCode(),
            (string) $response->getBody(),
            $response->getHeaders()
        );
    }
}

$client = new GlobalLinkClient(
    // ... credentials ...
    httpClient: new GuzzleHttpClient()
);

$client = new GlobalLinkClient(
    // ... credentials ...
    userAgent: 'MyApp/1.0 (Custom Integration)'
);

use TransPerfect\GlobalLink\Config\RetryConfig;

$client = new GlobalLinkClient(
    // ... credentials ...
    retryConfig: new RetryConfig(
        maxRetries: 3,
        baseDelayMs: 1000,
        retryOnRateLimit: true,
        retryOnServerError: true
    )
);

// Paginate through all targets
$pageNumber = 0;
$allTargets = [];

do {
    $request = new GetTargetsRequest(
        targetStatus: 'PROCESSED',
        projectIds: [$projectId],
        pageSize: 50,
        pageNumber: $pageNumber
    );
    
    $targets = $client->getTargets($request);
    $allTargets = array_merge($allTargets, $targets);
    $pageNumber++;
} while (count($targets) === 50);
bash
git clone https://github.com/transperfect/globallink-connect-php.git
cd globallink-connect-php
composer install
json
{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/transperfect/globallink-connect-php"
        }
    ],
    "
bash
# Set credentials (or load from .env)
export GLE_API_URL="https://your-instance.globallink.com"
export GLE_USERNAME="your-username"
export GLE_PASSWORD="your-password"
export GLE_OAUTH_CLIENT="your-oauth-client-id"
export GLE_OAUTH_SECRET="your-oauth-client-secret"

# Run an example
php examples/01-projects.php
php examples/02-submissions.php
php examples/03-targets.php