Skip to main content

getTaskStatus()

Get current task status:
<?php
require_once(__DIR__ . '/vendor/autoload.php');

use OpenAPI\Client\Configuration;
use OpenAPI\Client\Api\TaskManagementApi;

// Configure API client
$config = Configuration::getDefaultConfiguration();
$config->setApiKey('x-api-key', getenv('LEGNEXT_API_KEY'));
$config->setHost('https://api.legnext.ai');

$taskApi = new TaskManagementApi(null, $config);

try {
    $jobId = 'job-123';
    $task = $taskApi->getTaskStatus($jobId);

    echo "Status: " . $task->getStatus() . "\n";
    echo "Progress: " . $task->getProgress() . "%\n";

    if ($task->getStatus() === 'completed') {
        echo "Result: " . print_r($task->getOutput(), true) . "\n";
    }

} catch (\OpenAPI\Client\ApiException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Polling for Completion

Wait for task completion with polling:
<?php
function waitForCompletion($taskApi, $jobId, $timeoutSeconds = 300, $pollIntervalSeconds = 3) {
    $startTime = time();
    $timeout = $timeoutSeconds;

    while (true) {
        $task = $taskApi->getTaskStatus($jobId);

        echo "Current status: " . $task->getStatus() . "\n";

        if ($task->getStatus() === 'completed') {
            echo "Task completed successfully!\n";
            echo "Output: " . print_r($task->getOutput(), true) . "\n";
            return $task;
        } elseif ($task->getStatus() === 'failed') {
            throw new Exception("Task failed: " . $task->getError());
        }

        // Check timeout
        $elapsed = time() - $startTime;
        if ($elapsed > $timeout) {
            throw new Exception("Task timeout after {$timeoutSeconds} seconds");
        }

        // Wait before next poll
        sleep($pollIntervalSeconds);
    }
}
?>
Usage:
<?php
$taskApi = new TaskManagementApi(null, $config);
$jobId = 'job-123';

try {
    $result = waitForCompletion($taskApi, $jobId, 300, 3);
    echo "Final result: " . print_r($result, true) . "\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
?>

Complete Example with Error Handling

<?php
require_once(__DIR__ . '/vendor/autoload.php');

use OpenAPI\Client\Configuration;
use OpenAPI\Client\Api\ImageGenerationApi;
use OpenAPI\Client\Api\TaskManagementApi;
use OpenAPI\Client\Model\DiffusionRequest;

// Configure API client
$config = Configuration::getDefaultConfiguration();
$config->setApiKey('x-api-key', getenv('LEGNEXT_API_KEY'));
$config->setHost('https://api.legnext.ai');

function waitForCompletion($taskApi, $jobId, $timeoutSeconds = 300, $pollIntervalSeconds = 3) {
    $startTime = time();

    while (true) {
        $task = $taskApi->getTaskStatus($jobId);

        if ($task->getStatus() === 'completed') {
            return $task;
        } elseif ($task->getStatus() === 'failed') {
            throw new Exception("Task failed: " . $task->getError());
        }

        $elapsed = time() - $startTime;
        if ($elapsed > $timeoutSeconds) {
            throw new Exception("Task timeout after {$timeoutSeconds} seconds");
        }

        sleep($pollIntervalSeconds);
    }
}

function handleApiError($e) {
    $statusCode = $e->getCode();
    $errorBody = $e->getResponseBody();

    switch ($statusCode) {
        case 400:
            echo "Validation error: {$errorBody}\n";
            break;
        case 401:
            echo "Authentication error: Invalid API key\n";
            break;
        case 404:
            echo "Resource not found: {$errorBody}\n";
            break;
        case 429:
            echo "Rate limit exceeded. Please retry later.\n";
            break;
        case 500:
        case 502:
        case 503:
            echo "Server error: {$errorBody}\n";
            break;
        default:
            echo "API error ({$statusCode}): {$errorBody}\n";
    }
}

function generateImageWithPolling() {
    global $config;

    $imageApi = new ImageGenerationApi(null, $config);
    $taskApi = new TaskManagementApi(null, $config);

    try {
        // Step 1: Start generation
        $request = new DiffusionRequest();
        $request->setText('a beautiful sunset over mountains');

        $response = $imageApi->generateImage($request);
        $jobId = $response->getJobId();

        echo "Job started: {$jobId}\n";

        // Step 2: Poll for completion
        $result = waitForCompletion($taskApi, $jobId, 600, 3);

        // Step 3: Get final result
        $output = $result->getOutput();
        if ($output !== null && $output->getImageUrls() !== null) {
            echo "Image URLs: " . print_r($output->getImageUrls(), true) . "\n";
        }

    } catch (\OpenAPI\Client\ApiException $e) {
        handleApiError($e);
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

generateImageWithPolling();
?>

Error Handling

HTTP Error Handling:
<?php
try {
    $task = $taskApi->getTaskStatus($jobId);

} catch (\OpenAPI\Client\ApiException $e) {
    $statusCode = $e->getCode();
    $errorBody = $e->getResponseBody();

    switch ($statusCode) {
        case 400:
            echo "Validation error: Check request parameters\n";
            break;
        case 401:
            echo "Authentication error: Invalid API key\n";
            break;
        case 404:
            echo "Resource not found: Check job ID exists\n";
            break;
        case 429:
            echo "Rate limit exceeded. Please retry later.\n";
            break;
        case 500:
        case 502:
        case 503:
            echo "Server error. Please retry with backoff.\n";
            break;
        default:
            echo "API error ({$statusCode}): {$errorBody}\n";
    }
}
?>
Common HTTP Status Codes:
Status CodeDescriptionAction
400Invalid request parametersCheck request body format
401Invalid API keyVerify API key is correct
404Resource not foundCheck job ID exists
429Rate limit exceededWait and retry with backoff
500/502/503Server errorRetry with exponential backoff
Retry Logic with Exponential Backoff:
<?php
function callWithRetry($imageApi, $request, $maxRetries = 3) {
    $retries = 0;

    while ($retries < $maxRetries) {
        try {
            return $imageApi->generateImage($request);

        } catch (\OpenAPI\Client\ApiException $e) {
            if ($e->getCode() === 429) {
                // Rate limited - wait and retry
                $retries++;
                sleep(5);
                continue;
            } elseif ($e->getCode() >= 500) {
                // Server error - exponential backoff
                $retries++;
                $delay = pow(2, $retries);
                sleep($delay);
                if ($retries >= $maxRetries) {
                    throw $e;
                }
                continue;
            } else {
                // Other errors - don't retry
                throw $e;
            }
        }
    }

    throw new Exception("Max retries exceeded");
}

// Usage
$request = new DiffusionRequest();
$request->setText('a beautiful landscape');

try {
    $response = callWithRetry($imageApi, $request, 3);
    echo "Job ID: " . $response->getJobId() . "\n";
} catch (Exception $e) {
    echo "Failed after retries: " . $e->getMessage() . "\n";
}
?>

Processing Multiple Tasks

For processing multiple tasks sequentially:
<?php
function generateMultipleImages($imageApi, $taskApi, $prompts) {
    $results = [];

    foreach ($prompts as $prompt) {
        try {
            // Start generation
            $request = new DiffusionRequest();
            $request->setText($prompt);

            $response = $imageApi->generateImage($request);
            $jobId = $response->getJobId();

            echo "Started job for '{$prompt}': {$jobId}\n";

            // Wait for completion
            $result = waitForCompletion($taskApi, $jobId, 600, 3);

            $output = $result->getOutput();
            if ($output !== null && $output->getImageUrls() !== null && count($output->getImageUrls()) > 0) {
                $results[] = [
                    'prompt' => $prompt,
                    'url' => $output->getImageUrls()[0]
                ];
            }

        } catch (Exception $e) {
            $results[] = [
                'prompt' => $prompt,
                'error' => $e->getMessage()
            ];
        }
    }

    return $results;
}

// Usage
$prompts = ['sunset', 'mountains', 'ocean'];
$results = generateMultipleImages($imageApi, $taskApi, $prompts);

foreach ($results as $result) {
    if (isset($result['error'])) {
        echo "Error for '{$result['prompt']}': {$result['error']}\n";
    } else {
        echo "Image '{$result['prompt']}': {$result['url']}\n";
    }
}
?>

Progress Callbacks

<?php
function waitForCompletionWithProgress($taskApi, $jobId, $onProgress, $timeoutSeconds = 300, $pollIntervalSeconds = 3) {
    $startTime = time();

    while (true) {
        $task = $taskApi->getTaskStatus($jobId);

        // Call progress callback
        if ($onProgress !== null) {
            $progress = $task->getProgress() ?? 0;
            $status = $task->getStatus() ?? 'unknown';
            call_user_func($onProgress, $progress, $status);
        }

        if ($task->getStatus() === 'completed') {
            return $task;
        } elseif ($task->getStatus() === 'failed') {
            throw new Exception("Task failed: " . $task->getError());
        }

        $elapsed = time() - $startTime;
        if ($elapsed > $timeoutSeconds) {
            throw new Exception("Task timeout after {$timeoutSeconds} seconds");
        }

        sleep($pollIntervalSeconds);
    }
}

// Usage
$result = waitForCompletionWithProgress(
    $taskApi,
    $jobId,
    function($progress, $status) {
        echo "Progress: {$progress}% - Status: {$status}\n";
    },
    600,
    3
);
?>

Laravel Integration

For Laravel applications, create a service class:
<?php
namespace App\Services;

use OpenAPI\Client\Configuration;
use OpenAPI\Client\Api\ImageGenerationApi;
use OpenAPI\Client\Api\TaskManagementApi;
use OpenAPI\Client\Model\DiffusionRequest;

class LegnextService
{
    protected $imageApi;
    protected $taskApi;

    public function __construct()
    {
        $config = Configuration::getDefaultConfiguration();
        $config->setApiKey('x-api-key', config('legnext.api_key'));
        $config->setHost(config('legnext.host'));

        $this->imageApi = new ImageGenerationApi(null, $config);
        $this->taskApi = new TaskManagementApi(null, $config);
    }

    public function generateImage($text, $callback = null)
    {
        $request = new DiffusionRequest();
        $request->setText($text);
        if ($callback !== null) {
            $request->setCallback($callback);
        }

        return $this->imageApi->generateImage($request);
    }

    public function getTaskStatus($jobId)
    {
        return $this->taskApi->getTaskStatus($jobId);
    }

    public function waitForCompletion($jobId, $timeoutSeconds = 300, $pollIntervalSeconds = 3)
    {
        $startTime = time();

        while (true) {
            $task = $this->getTaskStatus($jobId);

            if ($task->getStatus() === 'completed') {
                return $task;
            } elseif ($task->getStatus() === 'failed') {
                throw new \Exception("Task failed: " . $task->getError());
            }

            $elapsed = time() - $startTime;
            if ($elapsed > $timeoutSeconds) {
                throw new \Exception("Task timeout after {$timeoutSeconds} seconds");
            }

            sleep($pollIntervalSeconds);
        }
    }
}
?>
Usage in Controller:
<?php
namespace App\Http\Controllers;

use App\Services\LegnextService;
use Illuminate\Http\Request;

class ImageController extends Controller
{
    protected $legnext;

    public function __construct(LegnextService $legnext)
    {
        $this->legnext = $legnext;
    }

    public function generate(Request $request)
    {
        try {
            $text = $request->input('text');
            $response = $this->legnext->generateImage($text);

            return response()->json([
                'job_id' => $response->getJobId(),
                'status' => $response->getStatus()
            ]);

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    public function status($jobId)
    {
        try {
            $task = $this->legnext->getTaskStatus($jobId);

            return response()->json([
                'status' => $task->getStatus(),
                'progress' => $task->getProgress(),
                'output' => $task->getOutput()
            ]);

        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
?>

Learn More