PHP SDK: Context: Execution, Data, and Progress
The main $ctx object is passed to run. It provides access to the rest of the SDK. The examples below belong in the body of that function.
Methods
http()state()storage()browser()captcha()wildberries()ai()dom()json()text()url()emit()flush()log()progress()metric()param()params()credential()sleep()cancelled()abort()fail()now()
http
http(): HttpClient
Get a client for requests to the site. All requests use the current site's network settings.
$http = $ctx->http();
$response = $http->get($ctx->param('catalog_url'));
Result and notes. Returns an HttpClient. Calling http() alone does not load anything.
state
state(): KeyValue
Get a small store for traversal state, such as the last processed page number.
$state = $ctx->state();
$page = (int) $state->get('page', 1);
Result and notes. Returns a KeyValue. This is run state, not a general product database.
storage
storage(string $code): Storage
Select an S3 file store by connection code. Configure the connection and allow it for the site first.
$storage = $ctx->storage('media');
$exists = $storage->exists('catalog/report.json');
Result and notes. Returns a Storage. media is the connection code, not a bucket address.
browser
browser(): Browser
Get a browser for pages that need JavaScript, clicks, or scrolling.
$browser = $ctx->browser();
$page = $browser->open($ctx->param('catalog_url'));
$page->close();
Result and notes. Returns a Browser. No more than two pages can remain open at once.
wildberries
wildberries(): Wildberries
Get the ready-made product source for a site created with the Wildberries solution. Products and regions come from site settings. See all methods and an example.
$source = $ctx->wildberries();
$regions = $source->regions();
ai
ai(): Ai
Get an assistant to analyze content, transform records, find an element, or suggest a repair for a PHP algorithm. Every AI call consumes the workspace's budget. See methods, limits, and examples.
$result = $ctx->ai()->transform(['cost' => '1,250 RUB'], ['price_rub' => 0]);
yandexMarket
$source = $ctx->yandexMarket();
Get Yandex Market products and search results for the configured scenario. YandexMarket.
$source = $ctx->yandexMarket();
dom
dom(string $html, ?string $baseUrl = null): Dom
Parse HTML already obtained. baseUrl lets relative links become absolute.
$dom = $ctx->dom('<a href="/product/1">Product</a>', 'https://shop.example.invalid/catalog');
$url = $dom->q('a')?->abs();
Result and notes. Returns a Dom. Parsing does not send a request to the website.
json
json(string $text, int $depth = 64): array
Parse JSON text as an array. depth limits nesting depth.
$data = $ctx->json('{"items":[{"sku":"A-1"}]}');
$sku = $data['items'][0]['sku'];
Result and notes. Returns an array. Invalid JSON throws JsonException. The root must be an object or array, not a string or number.
text
text(): TextTools
Get tools for cleaning text, prices, and product codes.
$price = $ctx->text()->money('1 250,50 ₽');
Result and notes. Returns TextTools; in this example $price is 1250.5.
url
url(): UrlTools
Get tools for links, query parameters, and page URL templates.
$url = $ctx->url()->withParam('https://shop.example.invalid/catalog', 'page', 2);
Result and notes. Returns UrlTools. This example adds ?page=2 to the URL.
emit
emit(array $item, ?string $key = null): void
Send one collected record to the system. Its fields must match the site schema. key identifies the product consistently.
$ctx->emit(['sku' => 'A-1', 'name' => 'Belt', 'price' => 1250.5], 'A-1');
Result and notes. Returns nothing. Records are validated and deduplicated; emit does not mean the database write has finished. Keep the key stable between runs.
flush
flush(): void
Send accumulated records without waiting for the automatic flush.
$ctx->emit(['sku' => 'A-1'], 'A-1');
$ctx->flush();
$ctx->log('Batch sent');
Result and notes. Returns nothing. Automatic flushing happens after 100 records or on the next emit after two seconds. Call flush explicitly before a long pause.
log
log(string $message, array $context = [], string $level = 'info'): void
Write a clear message to the run log. Pass extra values in context.
$ctx->log('Page processed', ['page' => 2, 'items' => 24], 'info');
Result and notes. Returns nothing. Use warning for concerns and error for failures. Do not log passwords, keys, or full site responses.
progress
progress(int $done, ?int $total = null, ?string $label = null, ?float $percent = null): void
Report work completed and a user-facing stage name. You may not know total in advance.
$ctx->progress(10, 50, 'Reading products');
// If the total is unknown:
$ctx->progress(3, null, 'Finding categories');
Result and notes. 10 out of 50 means 20%. A fourth argument, percent, can set the overall percentage from 0 to 100 explicitly. Completing a stage does not replace the run's final status.
metric
metric(string $name, float $value = 1): void
Add a numeric execution metric, such as the number of skipped products.
$ctx->metric('products_without_price', 1);
Result and notes. Returns nothing; value defaults to 1. Use log for human-readable messages and progress for a visible stage.
param
param(string $name, mixed $default = null): mixed
Get one run parameter. default is used if the parameter is absent or null.
$maxPages = (int) $ctx->param('max_pages', 20);
Result and notes. Returns a value of any type. Check its type and allowed range before use.
params
params(): array
Get all run parameters.
$params = $ctx->params();
$ctx->log('Settings available', ['count' => count($params)]);
Result and notes. Returns an array. Do not log the whole array if it contains sensitive values.
credential
credential(string $name): string
Get a named secret for the target website. Its name must match a configured key.
$token = $ctx->credential('catalog_api');
$http = $ctx->http()->withHeaders(['Authorization' => 'Bearer ' . $token]);
Result and notes. Returns a string. Do not pass the secret to emit or expose it in an export.
sleep
sleep(int $ms): void
Make a controlled pause. The argument is in milliseconds.
$ctx->sleep(500);
Result and notes. Pauses for half a second. The time counts toward execution; cancellation remains available.
cancelled
cancelled(): bool
Check whether the user requested a stop. Do this in long loops.
if ($ctx->cancelled()) {
return;
}
Result and notes. Returns true or false. On true, stop sending new requests and end the work cleanly.
abort
abort(string $reason): never
Stop execution with an explanation and retain state for a possible resume. The run receives a stopped status. Use fail() if the source returns an error or data is malformed.
if ($ctx->cancelled()) {
$ctx->abort('Collection stopped at user request');
}
Result and notes. Does not continue to the next line. Flushes the emit buffer before stopping. Do not use abort for normal successful completion.
fail
fail(string $reason): never
End a run with an error when the source is unavailable or its response differs from the expected format. Unlike abort(), this stop is recorded as a failure rather than a cancellation.
if (! $response->ok()) {
$ctx->fail('Source returned HTTP '.$response->status);
}
Result and notes. Flushes the emit() buffer before stopping. Records collected before failure remain saved.
now
now(): \DateTimeImmutable
Get the current UTC date and time.
$stamp = $ctx->now()->format('Y-m-d\TH:i:s\Z');
Result and notes. Returns DateTimeImmutable. Apply the relevant time zone separately for display.
sources
$ctx->sources() reads pinned inputs of a daily workflow. The platform rechecks the actor, workspace, site access and input freshness on every read. Manual parameters do not grant access to arbitrary mail.
$catalog = $ctx->sources()->input('catalog');
captcha
captcha(): Captcha
Returns the explicit task API. Catalog and quotation methods do not submit a paid task. Creation, status retrieval and feedback work through the workspace account in the cloud and on an agent.