Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(php-sdk): add PHP SDK with Laravel support for Firecrawl v2 API
firecrawl-spring[bot]442925e48cd2
diff --git a/apps/php-sdk/.gitignore b/apps/php-sdk/.gitignorenew file mode 100644index 000000000..93bc9f165--- /dev/null+++ b/apps/php-sdk/.gitignore@@ -0,0 +1,7 @@+/vendor/+/node_modules/+composer.lock+.phpunit.result.cache+.php-cs-fixer.cache+phpstan.neon+.envdiff --git a/apps/php-sdk/README.md b/apps/php-sdk/README.mdnew file mode 100644index 000000000..73a91691c--- /dev/null+++ b/apps/php-sdk/README.md@@ -0,0 +1,322 @@+# Firecrawl PHP SDK++PHP SDK for the [Firecrawl](https://firecrawl.dev) v2 API with first-class Laravel support.++## Requirements++- PHP 8.1.0++- Guzzle 7.9+++## Installation++```bash+composer require firecrawl/firecrawl-php+```++## Quick Start++```php+<?php++use Firecrawl\Client\FirecrawlClient;+use Firecrawl\Models\ScrapeOptions;++$client = FirecrawlClient::create(apiKey: 'fc-your-api-key');++// Scrape a single page+$doc = $client->scrape('https://example.com', ScrapeOptions::with(+ formats: ['markdown'],+ onlyMainContent: true,+));++echo $doc->getMarkdown();+```++### Environment Variables++The SDK reads the following environment variables as fallbacks:++| Variable | Description |+|---|---|+| `FIRECRAWL_API_KEY` | API key (required if not passed directly) |+| `FIRECRAWL_API_URL` | API base URL (defaults to `https://api.firecrawl.dev`) |++```php+// Uses FIRECRAWL_API_KEY from environment+$client = FirecrawlClient::fromEnv();+```++## Usage++### Scrape++```php+use Firecrawl\Models\ScrapeOptions;+use Firecrawl\Models\JsonFormat;++// Basic scrape+$doc = $client->scrape('https://example.com');+echo $doc->getMarkdown();++// With options+$doc = $client->scrape('https://example.com', ScrapeOptions::with(+ formats: ['markdown', 'html'],+ onlyMainContent: true,+ timeout: 30000,+ waitFor: 5000,+));++// JSON extraction+$doc = $client->scrape('https://example.com/product', ScrapeOptions::with(+ formats: [JsonFormat::with(+ prompt: 'Extract product name and price',+ schema: [+ 'type' => 'object',+ 'properties' => [+ 'name' => ['type' => 'string'],+ 'price' => ['type' => 'number'],+ ],+ ],+ )],+));++echo $doc->getJson(); // Structured data+```++### Crawl++```php+use Firecrawl\Models\CrawlOptions;+use Firecrawl\Models\ScrapeOptions;++// Crawl with auto-polling (blocks until complete)+$job = $client->crawl('https://example.com', CrawlOptions::with(+ limit: 50,+ maxDiscoveryDepth: 3,+ scrapeOptions: ScrapeOptions::with(formats: ['markdown']),+));++foreach ($job->getData() as $doc) {+ echo $doc->getMetadata()['sourceURL'] . "\n";+}++// Async: start crawl and poll manually+$response = $client->startCrawl('https://example.com', CrawlOptions::with(limit: 10));+$jobId = $response->getId();++// Check status later+$job = $client->getCrawlStatus($jobId);+echo "Completed: {$job->getCompleted()}/{$job->getTotal()}\n";++// Cancel+$client->cancelCrawl($jobId);+```++### Batch Scrape++```php+use Firecrawl\Models\BatchScrapeOptions;+use Firecrawl\Models\ScrapeOptions;++$job = $client->batchScrape(+ ['https://example.com', 'https://example.org'],+ BatchScrapeOptions::with(+ options: ScrapeOptions::with(formats: ['markdown']),+ idempotencyKey: 'my-batch-123',+ ),+);++foreach ($job->getData() as $doc) {+ echo $doc->getMarkdown() . "\n";+}+```++### Map++```php+use Firecrawl\Models\MapOptions;++$result = $client->map('https://example.com', MapOptions::with(+ limit: 100,+ search: 'pricing',+));++foreach ($result->getLinks() as $link) {+ echo $link['url'] . "\n";+}+```++### Search++```php+use Firecrawl\Models\SearchOptions;++$result = $client->search('firecrawl web scraping', SearchOptions::with(+ limit: 5,+));++foreach ($result->getWeb() as $item) {+ echo $item['title'] . ': ' . $item['url'] . "\n";+}+```++### Agent++```php+use Firecrawl\Models\AgentOptions;++// Auto-polling (blocks until complete)+$result = $client->agent(AgentOptions::with(+ prompt: 'Find the pricing plans and compare them',+ maxCredits: 100,+));++echo $result->getData();+```++### Browser Sessions++```php+// Create a session+$session = $client->browser(ttl: 300);+$sessionId = $session->getId();++// Execute code+$result = $client->browserExecute($sessionId, 'agent-browser open https://example.com');+echo $result->getStdout();++// Execute JavaScript+$result = $client->browserExecute(+ $sessionId,+ 'console.log(await page.title());',+ language: 'node',+ timeout: 30,+);++// Cleanup+$client->deleteBrowser($sessionId);++// List sessions+$sessions = $client->listBrowsers(status: 'active');+```++### Scrape-Bound Browser Interaction++```php+$doc = $client->scrape('https://example.com');+$scrapeId = $doc->getMetadata()['scrapeId'];++$result = $client->interact($scrapeId, 'await page.click("button");', language: 'node');+echo $result->getStdout();++$client->stopInteractiveBrowser($scrapeId);+```++### Usage & Metrics++```php+$concurrency = $client->getConcurrency();+echo "Current: {$concurrency->getConcurrency()}/{$concurrency->getMaxConcurrency()}\n";++$credits = $client->getCreditUsage();+echo "Remaining: {$credits->getRemainingCredits()}\n";+```++## Error Handling++```php+use Firecrawl\Exceptions\FirecrawlException;+use Firecrawl\Exceptions\AuthenticationException;+use Firecrawl\Exceptions\RateLimitException;+use Firecrawl\Exceptions\JobTimeoutException;++try {+ $doc = $client->scrape('https://example.com');+} catch (AuthenticationException $e) {+ echo "Invalid API key\n";+} catch (RateLimitException $e) {+ echo "Rate limited, back off\n";+} catch (JobTimeoutException $e) {+ echo "Job {$e->getJobId()} timed out after {$e->getTimeoutSeconds()}s\n";+} catch (FirecrawlException $e) {+ echo "Error ({$e->getStatusCode()}): {$e->getMessage()}\n";+}+```++## Advanced Configuration++```php+use GuzzleHttp\Client as GuzzleClient;++$client = FirecrawlClient::create(+ apiKey: 'fc-your-api-key',+ apiUrl: 'https://custom-api.example.com',+ timeoutSeconds: 120,+ maxRetries: 5,+ backoffFactor: 1.0,+ httpClient: new GuzzleClient([+ 'proxy' => 'http://proxy.example.com:8080',+ ]),+);+```++## Laravel Integration++### Setup++The service provider is auto-discovered. Publish the config file:++```bash+php artisan vendor:publish --tag=firecrawl-config+```++Add your API key to `.env`:++```+FIRECRAWL_API_KEY=fc-your-api-key+```++### Configuration++The published `config/firecrawl.php` supports these environment variables:++| Variable | Default | Description |+|---|---|---|+| `FIRECRAWL_API_KEY` | — | API key (required) |+| `FIRECRAWL_API_URL` | `https://api.firecrawl.dev` | API base URL |+| `FIRECRAWL_TIMEOUT` | `300` | Request timeout in seconds |+| `FIRECRAWL_MAX_RETRIES` | `3` | Max retry attempts |+| `FIRECRAWL_BACKOFF_FACTOR` | `0.5` | Exponential backoff factor |++### Using the Facade++```php+use Firecrawl\Laravel\Facades\Firecrawl;+use Firecrawl\Models\ScrapeOptions;++$doc = Firecrawl::scrape('https://example.com', ScrapeOptions::with(+ formats: ['markdown'],+));+```++### Using Dependency Injection++```php+use Firecrawl\Client\FirecrawlClient;++class MyController+{+ public function __construct(+ private readonly FirecrawlClient $firecrawl,+ ) {}++ public function scrape(string $url)+ {+ return $this->firecrawl->scrape($url);+ }+}+```++## License++MITdiff --git a/apps/php-sdk/composer.json b/apps/php-sdk/composer.jsonnew file mode 100644index 000000000..3c2032765--- /dev/null+++ b/apps/php-sdk/composer.json@@ -0,0 +1,57 @@+{+ "$schema": "https://getcomposer.org/schema.json",+ "name": "firecrawl/firecrawl-php",+ "description": "PHP SDK for the Firecrawl v2 API with Laravel support",+ "license": "MIT",+ "type": "library",+ "keywords": [+ "firecrawl",+ "web-scraping",+ "crawling",+ "api",+ "laravel",+ "php"+ ],+ "require": {+ "php": "^8.1",+ "guzzlehttp/guzzle": "^7.9",+ "psr/http-client": "^1",+ "psr/http-message": "^1|^2"+ },+ "require-dev": {+ "friendsofphp/php-cs-fixer": "^3",+ "orchestra/testbench": "^9|^10",+ "pestphp/pest": "^3",+ "phpstan/phpstan": "^2",+ "phpunit/phpunit": "^11"+ },+ "autoload": {+ "psr-4": {+ "Firecrawl\\": "src/"+ }+ },+ "autoload-dev": {+ "psr-4": {+ "Tests\\": "tests/"+ }+ },+ "config": {+ "allow-plugins": {+ "pestphp/pest-plugin": true+ },+ "preferred-install": "dist",+ "sort-packages": true+ },+ "extra": {+ "laravel": {+ "providers": [+ "Firecrawl\\Laravel\\FirecrawlServiceProvider"+ ],+ "aliases": {+ "Firecrawl": "Firecrawl\\Laravel\\Facades\\Firecrawl"+ }+ }+ },+ "minimum-stability": "stable",+ "prefer-stable": true+}diff --git a/apps/php-sdk/config/firecrawl.php b/apps/php-sdk/config/firecrawl.phpnew file mode 100644index 000000000..da8bf68f0--- /dev/null+++ b/apps/php-sdk/config/firecrawl.php@@ -0,0 +1,59 @@+<?php++declare(strict_types=1);++return [+ /*+ |--------------------------------------------------------------------------+ | Firecrawl API Key+ |--------------------------------------------------------------------------+ |+ | Your Firecrawl API key. Get one at https://firecrawl.dev.+ | Falls back to the FIRECRAWL_API_KEY environment variable.+ |+ */+ 'api_key' => env('FIRECRAWL_API_KEY'),++ /*+ |--------------------------------------------------------------------------+ | Firecrawl API URL+ |--------------------------------------------------------------------------+ |+ | The base URL for the Firecrawl API.+ | Falls back to the FIRECRAWL_API_URL environment variable or the default.+ |+ */+ 'api_url' => env('FIRECRAWL_API_URL', 'https://api.firecrawl.dev'),++ /*+ |--------------------------------------------------------------------------+ | Request Timeout+ |--------------------------------------------------------------------------+ |+ | The timeout in seconds for HTTP requests to the Firecrawl API.+ |+ */+ 'timeout' => (float) env('FIRECRAWL_TIMEOUT', 300),++ /*+ |--------------------------------------------------------------------------+ | Max Retries+ |--------------------------------------------------------------------------+ |+ | The maximum number of times to retry a failed request.+ | Retryable errors: 408, 409, 502, 5xx, and connection failures.+ |+ */+ 'max_retries' => (int) env('FIRECRAWL_MAX_RETRIES', 3),++ /*+ |--------------------------------------------------------------------------+ | Backoff Factor+ |--------------------------------------------------------------------------+ |+ | The exponential backoff factor in seconds for retries.+ | Delay = backoff_factor * 2^(attempt - 1)+ |+ */+ 'backoff_factor' => (float) env('FIRECRAWL_BACKOFF_FACTOR', 0.5),+];diff --git a/apps/php-sdk/src/Client/FirecrawlClient.php b/apps/php-sdk/src/Client/FirecrawlClient.phpnew file mode 100644index 000000000..592908c5d--- /dev/null+++ b/apps/php-sdk/src/Client/FirecrawlClient.php@@ -0,0 +1,534 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Client;++use Firecrawl\Exceptions\FirecrawlException;+use Firecrawl\Exceptions\JobTimeoutException;+use Firecrawl\Models\AgentOptions;+use Firecrawl\Models\AgentResponse;+use Firecrawl\Models\AgentStatusResponse;+use Firecrawl\Models\BatchScrapeJob;+use Firecrawl\Models\BatchScrapeOptions;+use Firecrawl\Models\BatchScrapeResponse;+use Firecrawl\Models\BrowserCreateResponse;+use Firecrawl\Models\BrowserDeleteResponse;+use Firecrawl\Models\BrowserExecuteResponse;+use Firecrawl\Models\BrowserListResponse;+use Firecrawl\Models\ConcurrencyCheck;+use Firecrawl\Models\CrawlJob;+use Firecrawl\Models\CrawlOptions;+use Firecrawl\Models\CrawlResponse;+use Firecrawl\Models\CreditUsage;+use Firecrawl\Models\Document;+use Firecrawl\Models\MapData;+use Firecrawl\Models\MapOptions;+use Firecrawl\Models\ScrapeOptions;+use Firecrawl\Models\SearchData;+use Firecrawl\Models\SearchOptions;+use GuzzleHttp\ClientInterface;++final class FirecrawlClient+{+ private const DEFAULT_API_URL = 'https://api.firecrawl.dev';+ private const DEFAULT_TIMEOUT_SECONDS = 300;+ private const DEFAULT_MAX_RETRIES = 3;+ private const DEFAULT_BACKOFF_FACTOR = 0.5;+ private const DEFAULT_POLL_INTERVAL = 2;+ private const DEFAULT_JOB_TIMEOUT = 300;++ private readonly FirecrawlHttpClient $http;++ private function __construct(FirecrawlHttpClient $http)+ {+ $this->http = $http;+ }++ /**+ * Create a client with named parameters.+ *+ * Uses FIRECRAWL_API_KEY and FIRECRAWL_API_URL environment variables as fallbacks.+ */+ public static function create(+ ?string $apiKey = null,+ ?string $apiUrl = null,+ float $timeoutSeconds = self::DEFAULT_TIMEOUT_SECONDS,+ int $maxRetries = self::DEFAULT_MAX_RETRIES,+ float $backoffFactor = self::DEFAULT_BACKOFF_FACTOR,+ ?ClientInterface $httpClient = null,+ ): self {+ $resolvedKey = $apiKey ?: (getenv('FIRECRAWL_API_KEY') ?: '');+ if ($resolvedKey === '') {+ throw new FirecrawlException(+ 'API key is required. Pass it directly or set the FIRECRAWL_API_KEY environment variable.',+ );+ }++ $resolvedUrl = $apiUrl ?: (getenv('FIRECRAWL_API_URL') ?: self::DEFAULT_API_URL);++ $http = new FirecrawlHttpClient(+ $resolvedKey,+ $resolvedUrl,+ $timeoutSeconds,+ $maxRetries,+ $backoffFactor,+ $httpClient,+ );++ return new self($http);+ }++ /**+ * Create a client from the FIRECRAWL_API_KEY environment variable.+ */+ public static function fromEnv(): self+ {+ return self::create();+ }++ // ================================================================+ // SCRAPE+ // ================================================================++ /**+ * Scrape a single URL and return the document.+ */+ public function scrape(string $url, ?ScrapeOptions $options = null): Document+ {+ $body = ['url' => $url];+ if ($options !== null) {+ $body = array_merge($body, $options->toArray());+ }++ $response = $this->http->post('/v2/scrape', $body);++ return Document::fromArray($response['data'] ?? $response);+ }++ /**+ * Interact with the scrape-bound browser session for a scrape job.+ */+ public function interact(+ string $jobId,+ string $code,+ string $language = 'node',+ ?int $timeout = null,+ ?string $origin = null,+ ): BrowserExecuteResponse {+ $body = [+ 'code' => $code,+ 'language' => $language,+ ];+ if ($timeout !== null) {+ $body['timeout'] = $timeout;+ }+ if ($origin !== null) {+ $body['origin'] = $origin;+ }++ return BrowserExecuteResponse::fromArray(+ $this->http->post("/v2/scrape/{$jobId}/interact", $body),+ );+ }++ /**+ * Stop the interactive browser session for a scrape job.+ */+ public function stopInteractiveBrowser(string $jobId): BrowserDeleteResponse+ {+ return BrowserDeleteResponse::fromArray(+ $this->http->delete("/v2/scrape/{$jobId}/interact"),+ );+ }++ // ================================================================+ // CRAWL+ // ================================================================++ /**+ * Start an async crawl job and return immediately.+ */+ public function startCrawl(string $url, ?CrawlOptions $options = null): CrawlResponse+ {+ $body = ['url' => $url];+ if ($options !== null) {+ $body = array_merge($body, $options->toArray());+ }++ return CrawlResponse::fromArray($this->http->post('/v2/crawl', $body));+ }++ /**+ * Get the status and results of a crawl job.+ */+ public function getCrawlStatus(string $jobId): CrawlJob+ {+ return CrawlJob::fromArray($this->http->get("/v2/crawl/{$jobId}"));+ }++ /**+ * Crawl a website and wait for completion (auto-polling).+ */+ public function crawl(+ string $url,+ ?CrawlOptions $options = null,+ int $pollIntervalSec = self::DEFAULT_POLL_INTERVAL,+ int $timeoutSec = self::DEFAULT_JOB_TIMEOUT,+ ): CrawlJob {+ $start = $this->startCrawl($url, $options);++ return $this->pollCrawl($start->getId(), $pollIntervalSec, $timeoutSec);+ }++ /**+ * Cancel a running crawl job.+ *+ * @return array<string, mixed>+ */+ public function cancelCrawl(string $jobId): array+ {+ return $this->http->delete("/v2/crawl/{$jobId}");+ }++ /**+ * Get errors from a crawl job.+ *+ * @return array<string, mixed>+ */+ public function getCrawlErrors(string $jobId): array+ {+ return $this->http->get("/v2/crawl/{$jobId}/errors");+ }++ // ================================================================+ // BATCH SCRAPE+ // ================================================================++ /**+ * Start an async batch scrape job.+ *+ * @param list<string> $urls+ */+ public function startBatchScrape(array $urls, ?BatchScrapeOptions $options = null): BatchScrapeResponse+ {+ $body = ['urls' => $urls];+ $extraHeaders = [];++ if ($options !== null) {+ $idempotencyKey = $options->getIdempotencyKey();+ if ($idempotencyKey !== null && $idempotencyKey !== '') {+ $extraHeaders['x-idempotency-key'] = $idempotencyKey;+ }++ $body = array_merge($body, $options->toArray());+ }++ return BatchScrapeResponse::fromArray(+ $this->http->post('/v2/batch/scrape', $body, $extraHeaders),+ );+ }++ /**+ * Get the status and results of a batch scrape job.+ */+ public function getBatchScrapeStatus(string $jobId): BatchScrapeJob+ {+ return BatchScrapeJob::fromArray($this->http->get("/v2/batch/scrape/{$jobId}"));+ }++ /**+ * Batch-scrape URLs and wait for completion (auto-polling).+ *+ * @param list<string> $urls+ */+ public function batchScrape(+ array $urls,+ ?BatchScrapeOptions $options = null,+ int $pollIntervalSec = self::DEFAULT_POLL_INTERVAL,+ int $timeoutSec = self::DEFAULT_JOB_TIMEOUT,+ ): BatchScrapeJob {+ $start = $this->startBatchScrape($urls, $options);++ return $this->pollBatchScrape($start->getId(), $pollIntervalSec, $timeoutSec);+ }++ /**+ * Cancel a running batch scrape job.+ *+ * @return array<string, mixed>+ */+ public function cancelBatchScrape(string $jobId): array+ {+ return $this->http->delete("/v2/batch/scrape/{$jobId}");+ }++ // ================================================================+ // MAP+ // ================================================================++ /**+ * Discover URLs on a website.+ */+ public function map(string $url, ?MapOptions $options = null): MapData+ {+ $body = ['url' => $url];+ if ($options !== null) {+ $body = array_merge($body, $options->toArray());+ }++ $response = $this->http->post('/v2/map', $body);++ return MapData::fromArray($response['data'] ?? $response);+ }++ // ================================================================+ // SEARCH+ // ================================================================++ /**+ * Perform a web search.+ */+ public function search(string $query, ?SearchOptions $options = null): SearchData+ {+ $body = ['query' => $query];+ if ($options !== null) {+ $body = array_merge($body, $options->toArray());+ }++ $response = $this->http->post('/v2/search', $body);++ return SearchData::fromArray($response['data'] ?? $response);+ }++ // ================================================================+ // AGENT+ // ================================================================++ /**+ * Start an async agent task.+ */+ public function startAgent(AgentOptions $options): AgentResponse+ {+ return AgentResponse::fromArray(+ $this->http->post('/v2/agent', $options->toArray()),+ );+ }++ /**+ * Get the status of an agent task.+ */+ public function getAgentStatus(string $jobId): AgentStatusResponse+ {+ return AgentStatusResponse::fromArray(+ $this->http->get("/v2/agent/{$jobId}"),+ );+ }++ /**+ * Run an agent task and wait for completion (auto-polling).+ */+ public function agent(+ AgentOptions $options,+ int $pollIntervalSec = self::DEFAULT_POLL_INTERVAL,+ int $timeoutSec = self::DEFAULT_JOB_TIMEOUT,+ ): AgentStatusResponse {+ $start = $this->startAgent($options);++ if ($start->getId() === null) {+ throw new FirecrawlException('Agent start did not return a job ID');+ }++ $deadline = time() + $timeoutSec;+ while (time() < $deadline) {+ $status = $this->getAgentStatus($start->getId());+ if ($status->isDone()) {+ return $status;+ }+ sleep($pollIntervalSec);+ }++ throw new JobTimeoutException($start->getId(), $timeoutSec, 'Agent');+ }++ /**+ * Cancel a running agent task.+ *+ * @return array<string, mixed>+ */+ public function cancelAgent(string $jobId): array+ {+ return $this->http->delete("/v2/agent/{$jobId}");+ }++ // ================================================================+ // BROWSER+ // ================================================================++ /**+ * Create a new browser session.+ */+ public function browser(+ ?int $ttl = null,+ ?int $activityTtl = null,+ ?bool $streamWebView = null,+ ): BrowserCreateResponse {+ $body = [];+ if ($ttl !== null) {+ $body['ttl'] = $ttl;+ }+ if ($activityTtl !== null) {+ $body['activityTtl'] = $activityTtl;+ }+ if ($streamWebView !== null) {+ $body['streamWebView'] = $streamWebView;+ }++ return BrowserCreateResponse::fromArray($this->http->post('/v2/browser', $body));+ }++ /**+ * Execute code in a browser session.+ */+ public function browserExecute(+ string $sessionId,+ string $code,+ string $language = 'bash',+ ?int $timeout = null,+ ): BrowserExecuteResponse {+ $body = [+ 'code' => $code,+ 'language' => $language,+ ];+ if ($timeout !== null) {+ $body['timeout'] = $timeout;+ }++ return BrowserExecuteResponse::fromArray(+ $this->http->post("/v2/browser/{$sessionId}/execute", $body),+ );+ }++ /**+ * Delete a browser session.+ */+ public function deleteBrowser(string $sessionId): BrowserDeleteResponse+ {+ return BrowserDeleteResponse::fromArray(+ $this->http->delete("/v2/browser/{$sessionId}"),+ );+ }++ /**+ * List browser sessions.+ */+ public function listBrowsers(?string $status = null): BrowserListResponse+ {+ $endpoint = '/v2/browser';+ if ($status !== null && $status !== '') {+ $endpoint .= '?status=' . urlencode($status);+ }++ return BrowserListResponse::fromArray($this->http->get($endpoint));+ }++ // ================================================================+ // USAGE & METRICS+ // ================================================================++ /**+ * Get current concurrency usage.+ */+ public function getConcurrency(): ConcurrencyCheck+ {+ return ConcurrencyCheck::fromArray($this->http->get('/v2/concurrency-check'));+ }++ /**+ * Get current credit usage.+ */+ public function getCreditUsage(): CreditUsage+ {+ return CreditUsage::fromArray($this->http->get('/v2/team/credit-usage'));+ }++ // ================================================================+ // INTERNAL POLLING HELPERS+ // ================================================================++ private function pollCrawl(+ ?string $jobId,+ int $pollIntervalSec,+ int $timeoutSec,+ ): CrawlJob {+ if ($jobId === null) {+ throw new FirecrawlException('Crawl start did not return a job ID');+ }++ $deadline = time() + $timeoutSec;+ while (time() < $deadline) {+ $job = $this->getCrawlStatus($jobId);+ if ($job->isDone()) {+ return $this->paginateCrawl($job);+ }+ sleep($pollIntervalSec);+ }++ throw new JobTimeoutException($jobId, $timeoutSec, 'Crawl');+ }++ private function pollBatchScrape(+ ?string $jobId,+ int $pollIntervalSec,+ int $timeoutSec,+ ): BatchScrapeJob {+ if ($jobId === null) {+ throw new FirecrawlException('Batch scrape start did not return a job ID');+ }++ $deadline = time() + $timeoutSec;+ while (time() < $deadline) {+ $job = $this->getBatchScrapeStatus($jobId);+ if ($job->isDone()) {+ return $this->paginateBatchScrape($job);+ }+ sleep($pollIntervalSec);+ }++ throw new JobTimeoutException($jobId, $timeoutSec, 'Batch scrape');+ }++ private function paginateCrawl(CrawlJob $job): CrawlJob+ {+ $current = $job;+ while ($current->getNext() !== null && $current->getNext() !== '') {+ $nextRaw = $this->http->getAbsolute($current->getNext());+ $nextPage = CrawlJob::fromArray($nextRaw);++ foreach ($nextPage->getData() as $doc) {+ $job->appendData($doc);+ }++ $current = $nextPage;+ }++ return $job;+ }++ private function paginateBatchScrape(BatchScrapeJob $job): BatchScrapeJob+ {+ $current = $job;+ while ($current->getNext() !== null && $current->getNext() !== '') {+ $nextRaw = $this->http->getAbsolute($current->getNext());+ $nextPage = BatchScrapeJob::fromArray($nextRaw);++ foreach ($nextPage->getData() as $doc) {+ $job->appendData($doc);+ }++ $current = $nextPage;+ }++ return $job;+ }+}diff --git a/apps/php-sdk/src/Client/FirecrawlHttpClient.php b/apps/php-sdk/src/Client/FirecrawlHttpClient.phpnew file mode 100644index 000000000..9837f79cb--- /dev/null+++ b/apps/php-sdk/src/Client/FirecrawlHttpClient.php@@ -0,0 +1,195 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Client;++use Firecrawl\Exceptions\AuthenticationException;+use Firecrawl\Exceptions\FirecrawlException;+use Firecrawl\Exceptions\RateLimitException;+use GuzzleHttp\Client as GuzzleClient;+use GuzzleHttp\ClientInterface;+use GuzzleHttp\Exception\ConnectException;+use GuzzleHttp\Exception\RequestException;+use GuzzleHttp\RequestOptions;++/**+ * @internal+ */+final class FirecrawlHttpClient+{+ private readonly ClientInterface $httpClient;+ private readonly string $baseUrl;++ public function __construct(+ private readonly string $apiKey,+ string $baseUrl,+ float $timeoutSeconds,+ private readonly int $maxRetries,+ private readonly float $backoffFactor,+ ?ClientInterface $httpClient = null,+ ) {+ $this->baseUrl = rtrim($baseUrl, '/');++ $this->httpClient = $httpClient ?? new GuzzleClient([+ RequestOptions::TIMEOUT => $timeoutSeconds,+ RequestOptions::CONNECT_TIMEOUT => min($timeoutSeconds, 30),+ RequestOptions::HTTP_ERRORS => false,+ ]);+ }++ /**+ * @param array<string, mixed> $body+ * @param array<string, string> $extraHeaders+ * @return array<string, mixed>+ */+ public function post(string $path, array $body, array $extraHeaders = []): array+ {+ return $this->request('POST', $this->baseUrl . $path, $body, $extraHeaders);+ }++ /** @return array<string, mixed> */+ public function get(string $path): array+ {+ return $this->request('GET', $this->baseUrl . $path);+ }++ /** @return array<string, mixed> */+ public function getAbsolute(string $absoluteUrl): array+ {+ return $this->request('GET', $absoluteUrl);+ }++ /** @return array<string, mixed> */+ public function delete(string $path): array+ {+ return $this->request('DELETE', $this->baseUrl . $path);+ }++ /**+ * @param array<string, mixed> $body+ * @param array<string, string> $extraHeaders+ * @return array<string, mixed>+ */+ private function request(+ string $method,+ string $url,+ array $body = [],+ array $extraHeaders = [],+ ): array {+ $headers = array_merge([+ 'Authorization' => 'Bearer ' . $this->apiKey,+ 'Content-Type' => 'application/json',+ 'Accept' => 'application/json',+ ], $extraHeaders);++ $options = [+ RequestOptions::HEADERS => $headers,+ RequestOptions::HTTP_ERRORS => false,+ ];++ if ($method === 'POST' && $body !== []) {+ $options[RequestOptions::JSON] = $body;+ }++ $attempt = 0;++ while (true) {+ try {+ $response = $this->httpClient->request($method, $url, $options);+ $statusCode = $response->getStatusCode();+ $responseBody = (string) $response->getBody();++ if ($statusCode >= 200 && $statusCode < 300) {+ /** @var array<string, mixed> */+ return json_decode($responseBody, true, 512, JSON_THROW_ON_ERROR);+ }++ $errorMessage = $this->extractErrorMessage($responseBody, $statusCode);+ $errorCode = $this->extractErrorCode($responseBody);++ // Non-retryable client errors+ if ($statusCode === 401) {+ throw new AuthenticationException($errorMessage, $errorCode);+ }++ if ($statusCode === 429) {+ throw new RateLimitException($errorMessage, $errorCode);+ }++ if ($statusCode >= 400 && $statusCode < 500 && $statusCode !== 408 && $statusCode !== 409) {+ throw new FirecrawlException($errorMessage, $statusCode, $errorCode);+ }++ // Retryable errors: 408, 409, 502, 5xx+ if ($attempt < $this->maxRetries) {+ $attempt++;+ $this->sleepWithBackoff($attempt);+ continue;+ }++ throw new FirecrawlException($errorMessage, $statusCode, $errorCode);+ } catch (FirecrawlException $e) {+ throw $e;+ } catch (ConnectException $e) {+ if ($attempt < $this->maxRetries) {+ $attempt++;+ $this->sleepWithBackoff($attempt);+ continue;+ }+ throw new FirecrawlException('Connection failed: ' . $e->getMessage(), previous: $e);+ } catch (RequestException $e) {+ if ($attempt < $this->maxRetries) {+ $attempt++;+ $this->sleepWithBackoff($attempt);+ continue;+ }+ throw new FirecrawlException('Request failed: ' . $e->getMessage(), previous: $e);+ } catch (\JsonException $e) {+ throw new FirecrawlException('Failed to parse API response: ' . $e->getMessage(), previous: $e);+ }+ }+ }++ private function extractErrorMessage(string $body, int $statusCode): string+ {+ try {+ /** @var array<string, mixed> $parsed */+ $parsed = json_decode($body, true, 512, JSON_THROW_ON_ERROR);++ if (isset($parsed['error']) && is_string($parsed['error'])) {+ return $parsed['error'];+ }++ if (isset($parsed['message']) && is_string($parsed['message'])) {+ return $parsed['message'];+ }+ } catch (\JsonException) {+ // ignore+ }++ return "HTTP {$statusCode} error";+ }++ private function extractErrorCode(string $body): ?string+ {+ try {+ /** @var array<string, mixed> $parsed */+ $parsed = json_decode($body, true, 512, JSON_THROW_ON_ERROR);++ if (isset($parsed['code'])) {+ return (string) $parsed['code'];+ }+ } catch (\JsonException) {+ // ignore+ }++ return null;+ }++ private function sleepWithBackoff(int $attempt): void+ {+ $delayMs = (int) ($this->backoffFactor * 1000 * pow(2, $attempt - 1));+ usleep($delayMs * 1000);+ }+}diff --git a/apps/php-sdk/src/Exceptions/AuthenticationException.php b/apps/php-sdk/src/Exceptions/AuthenticationException.phpnew file mode 100644index 000000000..d6b3a035d--- /dev/null+++ b/apps/php-sdk/src/Exceptions/AuthenticationException.php@@ -0,0 +1,16 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Exceptions;++class AuthenticationException extends FirecrawlException+{+ public function __construct(+ string $message = 'Authentication failed. Check your API key.',+ ?string $errorCode = null,+ mixed $details = null,+ ) {+ parent::__construct($message, 401, $errorCode, $details);+ }+}diff --git a/apps/php-sdk/src/Exceptions/FirecrawlException.php b/apps/php-sdk/src/Exceptions/FirecrawlException.phpnew file mode 100644index 000000000..ede5cefad--- /dev/null+++ b/apps/php-sdk/src/Exceptions/FirecrawlException.php@@ -0,0 +1,36 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Exceptions;++use RuntimeException;+use Throwable;++class FirecrawlException extends RuntimeException+{+ public function __construct(+ string $message = '',+ private readonly int $statusCode = 0,+ private readonly ?string $errorCode = null,+ private readonly mixed $details = null,+ ?Throwable $previous = null,+ ) {+ parent::__construct($message, $statusCode, $previous);+ }++ public function getStatusCode(): int+ {+ return $this->statusCode;+ }++ public function getErrorCode(): ?string+ {+ return $this->errorCode;+ }++ public function getDetails(): mixed+ {+ return $this->details;+ }+}diff --git a/apps/php-sdk/src/Exceptions/JobTimeoutException.php b/apps/php-sdk/src/Exceptions/JobTimeoutException.phpnew file mode 100644index 000000000..71d3786a9--- /dev/null+++ b/apps/php-sdk/src/Exceptions/JobTimeoutException.php@@ -0,0 +1,29 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Exceptions;++class JobTimeoutException extends FirecrawlException+{+ public function __construct(+ private readonly string $jobId,+ private readonly int $timeoutSeconds,+ string $jobType = 'Job',+ ) {+ parent::__construct(+ "{$jobType} {$jobId} timed out after {$timeoutSeconds} seconds",+ statusCode: 408,+ );+ }++ public function getJobId(): string+ {+ return $this->jobId;+ }++ public function getTimeoutSeconds(): int+ {+ return $this->timeoutSeconds;+ }+}diff --git a/apps/php-sdk/src/Exceptions/RateLimitException.php b/apps/php-sdk/src/Exceptions/RateLimitException.phpnew file mode 100644index 000000000..55093acb5--- /dev/null+++ b/apps/php-sdk/src/Exceptions/RateLimitException.php@@ -0,0 +1,16 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Exceptions;++class RateLimitException extends FirecrawlException+{+ public function __construct(+ string $message = 'Rate limit exceeded.',+ ?string $errorCode = null,+ mixed $details = null,+ ) {+ parent::__construct($message, 429, $errorCode, $details);+ }+}diff --git a/apps/php-sdk/src/Laravel/Facades/Firecrawl.php b/apps/php-sdk/src/Laravel/Facades/Firecrawl.phpnew file mode 100644index 000000000..e6208cd5e--- /dev/null+++ b/apps/php-sdk/src/Laravel/Facades/Firecrawl.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Laravel\Facades;++use Firecrawl\Client\FirecrawlClient;+use Firecrawl\Models\AgentOptions;+use Firecrawl\Models\AgentStatusResponse;+use Firecrawl\Models\BatchScrapeJob;+use Firecrawl\Models\BatchScrapeOptions;+use Firecrawl\Models\BrowserCreateResponse;+use Firecrawl\Models\BrowserDeleteResponse;+use Firecrawl\Models\BrowserExecuteResponse;+use Firecrawl\Models\BrowserListResponse;+use Firecrawl\Models\ConcurrencyCheck;+use Firecrawl\Models\CrawlJob;+use Firecrawl\Models\CrawlOptions;+use Firecrawl\Models\CreditUsage;+use Firecrawl\Models\Document;+use Firecrawl\Models\MapData;+use Firecrawl\Models\MapOptions;+use Firecrawl\Models\ScrapeOptions;+use Firecrawl\Models\SearchData;+use Firecrawl\Models\SearchOptions;+use Illuminate\Support\Facades\Facade;++/**+ * @method static Document scrape(string $url, ?ScrapeOptions $options = null)+ * @method static BrowserExecuteResponse interact(string $jobId, string $code, string $language = 'node', ?int $timeout = null, ?string $origin = null)+ * @method static BrowserDeleteResponse stopInteractiveBrowser(string $jobId)+ * @method static CrawlJob crawl(string $url, ?CrawlOptions $options = null, int $pollIntervalSec = 2, int $timeoutSec = 300)+ * @method static CrawlJob getCrawlStatus(string $jobId)+ * @method static array cancelCrawl(string $jobId)+ * @method static BatchScrapeJob batchScrape(array $urls, ?BatchScrapeOptions $options = null, int $pollIntervalSec = 2, int $timeoutSec = 300)+ * @method static array cancelBatchScrape(string $jobId)+ * @method static MapData map(string $url, ?MapOptions $options = null)+ * @method static SearchData search(string $query, ?SearchOptions $options = null)+ * @method static AgentStatusResponse agent(AgentOptions $options, int $pollIntervalSec = 2, int $timeoutSec = 300)+ * @method static array cancelAgent(string $jobId)+ * @method static BrowserCreateResponse browser(?int $ttl = null, ?int $activityTtl = null, ?bool $streamWebView = null)+ * @method static BrowserExecuteResponse browserExecute(string $sessionId, string $code, string $language = 'bash', ?int $timeout = null)+ * @method static BrowserDeleteResponse deleteBrowser(string $sessionId)+ * @method static BrowserListResponse listBrowsers(?string $status = null)+ * @method static ConcurrencyCheck getConcurrency()+ * @method static CreditUsage getCreditUsage()+ *+ * @see FirecrawlClient+ */+class Firecrawl extends Facade+{+ protected static function getFacadeAccessor(): string+ {+ return FirecrawlClient::class;+ }+}diff --git a/apps/php-sdk/src/Laravel/FirecrawlServiceProvider.php b/apps/php-sdk/src/Laravel/FirecrawlServiceProvider.phpnew file mode 100644index 000000000..7373805ff--- /dev/null+++ b/apps/php-sdk/src/Laravel/FirecrawlServiceProvider.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Laravel;++use Firecrawl\Client\FirecrawlClient;+use Illuminate\Contracts\Support\DeferrableProvider;+use Illuminate\Support\ServiceProvider;++class FirecrawlServiceProvider extends ServiceProvider implements DeferrableProvider+{+ public function register(): void+ {+ $this->mergeConfigFrom(__DIR__ . '/../../config/firecrawl.php', 'firecrawl');++ $this->app->singleton(FirecrawlClient::class, function ($app): FirecrawlClient {+ /** @var array{api_key: string|null, api_url: string|null, timeout: float, max_retries: int, backoff_factor: float} $config */+ $config = $app['config']->get('firecrawl', []);++ return FirecrawlClient::create(+ apiKey: $config['api_key'] ?? null,+ apiUrl: $config['api_url'] ?? null,+ timeoutSeconds: (float) ($config['timeout'] ?? 300),+ maxRetries: (int) ($config['max_retries'] ?? 3),+ backoffFactor: (float) ($config['backoff_factor'] ?? 0.5),+ );+ });++ $this->app->alias(FirecrawlClient::class, 'firecrawl');+ }++ public function boot(): void+ {+ if ($this->app->runningInConsole()) {+ $this->publishes([+ __DIR__ . '/../../config/firecrawl.php' => $this->app->configPath('firecrawl.php'),+ ], 'firecrawl-config');+ }+ }++ /** @return list<string> */+ public function provides(): array+ {+ return [FirecrawlClient::class, 'firecrawl'];+ }+}diff --git a/apps/php-sdk/src/Models/AgentOptions.php b/apps/php-sdk/src/Models/AgentOptions.phpnew file mode 100644index 000000000..bd24edf53--- /dev/null+++ b/apps/php-sdk/src/Models/AgentOptions.php@@ -0,0 +1,56 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class AgentOptions+{+ /**+ * @param list<string>|null $urls+ * @param array<string, mixed>|null $schema+ */+ private function __construct(+ private readonly ?array $urls = null,+ private readonly ?string $prompt = null,+ private readonly ?array $schema = null,+ private readonly ?string $integration = null,+ private readonly ?int $maxCredits = null,+ private readonly ?bool $strictConstrainToURLs = null,+ private readonly ?string $model = null,+ private readonly ?WebhookConfig $webhook = null,+ ) {}++ public static function with(+ ?array $urls = null,+ ?string $prompt = null,+ ?array $schema = null,+ ?string $integration = null,+ ?int $maxCredits = null,+ ?bool $strictConstrainToURLs = null,+ ?string $model = null,+ ?WebhookConfig $webhook = null,+ ): self {+ return new self(+ $urls, $prompt, $schema, $integration,+ $maxCredits, $strictConstrainToURLs, $model, $webhook,+ );+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ $fields = [+ 'urls' => $this->urls,+ 'prompt' => $this->prompt,+ 'schema' => $this->schema,+ 'integration' => $this->integration,+ 'maxCredits' => $this->maxCredits,+ 'strictConstrainToURLs' => $this->strictConstrainToURLs,+ 'model' => $this->model,+ 'webhook' => $this->webhook?->toArray(),+ ];++ return array_filter($fields, fn (mixed $v): bool => $v !== null);+ }+}diff --git a/apps/php-sdk/src/Models/AgentResponse.php b/apps/php-sdk/src/Models/AgentResponse.phpnew file mode 100644index 000000000..865f48bf1--- /dev/null+++ b/apps/php-sdk/src/Models/AgentResponse.php@@ -0,0 +1,39 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class AgentResponse+{+ public function __construct(+ private readonly bool $success = false,+ private readonly ?string $id = null,+ private readonly ?string $error = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ success: (bool) ($data['success'] ?? false),+ id: $data['id'] ?? null,+ error: $data['error'] ?? null,+ );+ }++ public function isSuccess(): bool+ {+ return $this->success;+ }++ public function getId(): ?string+ {+ return $this->id;+ }++ public function getError(): ?string+ {+ return $this->error;+ }+}diff --git a/apps/php-sdk/src/Models/AgentStatusResponse.php b/apps/php-sdk/src/Models/AgentStatusResponse.phpnew file mode 100644index 000000000..bf5850f82--- /dev/null+++ b/apps/php-sdk/src/Models/AgentStatusResponse.php@@ -0,0 +1,72 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class AgentStatusResponse+{+ public function __construct(+ private readonly bool $success = false,+ private readonly ?string $status = null,+ private readonly ?string $error = null,+ private readonly mixed $data = null,+ private readonly ?string $model = null,+ private readonly ?string $expiresAt = null,+ private readonly ?int $creditsUsed = null,+ ) {}++ /** @param array<string, mixed> $raw */+ public static function fromArray(array $raw): self+ {+ return new self(+ success: (bool) ($raw['success'] ?? false),+ status: $raw['status'] ?? null,+ error: $raw['error'] ?? null,+ data: $raw['data'] ?? null,+ model: $raw['model'] ?? null,+ expiresAt: $raw['expiresAt'] ?? null,+ creditsUsed: isset($raw['creditsUsed']) ? (int) $raw['creditsUsed'] : null,+ );+ }++ public function isDone(): bool+ {+ return in_array($this->status, ['completed', 'failed', 'cancelled'], true);+ }++ public function isSuccess(): bool+ {+ return $this->success;+ }++ public function getStatus(): ?string+ {+ return $this->status;+ }++ public function getError(): ?string+ {+ return $this->error;+ }++ public function getData(): mixed+ {+ return $this->data;+ }++ public function getModel(): ?string+ {+ return $this->model;+ }++ public function getExpiresAt(): ?string+ {+ return $this->expiresAt;+ }++ public function getCreditsUsed(): ?int+ {+ return $this->creditsUsed;+ }+}diff --git a/apps/php-sdk/src/Models/BatchScrapeJob.php b/apps/php-sdk/src/Models/BatchScrapeJob.phpnew file mode 100644index 000000000..a10ee89ed--- /dev/null+++ b/apps/php-sdk/src/Models/BatchScrapeJob.php@@ -0,0 +1,109 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class BatchScrapeJob+{+ /** @var list<Document> */+ private array $data;++ /**+ * @param list<Document> $data+ */+ public function __construct(+ private readonly ?string $id = null,+ private readonly ?string $status = null,+ private readonly int $completed = 0,+ private readonly int $total = 0,+ private readonly ?int $creditsUsed = null,+ private readonly ?string $expiresAt = null,+ private ?string $next = null,+ array $data = [],+ ) {+ $this->data = $data;+ }++ /** @param array<string, mixed> $raw */+ public static function fromArray(array $raw): self+ {+ $docs = [];+ foreach (($raw['data'] ?? []) as $item) {+ $docs[] = Document::fromArray($item);+ }++ return new self(+ id: $raw['id'] ?? null,+ status: $raw['status'] ?? null,+ completed: (int) ($raw['completed'] ?? 0),+ total: (int) ($raw['total'] ?? 0),+ creditsUsed: $raw['creditsUsed'] ?? null,+ expiresAt: $raw['expiresAt'] ?? null,+ next: $raw['next'] ?? null,+ data: $docs,+ );+ }++ public function isDone(): bool+ {+ return in_array($this->status, ['completed', 'failed', 'cancelled'], true);+ }++ public function getId(): ?string+ {+ return $this->id;+ }++ public function getStatus(): ?string+ {+ return $this->status;+ }++ public function getCompleted(): int+ {+ return $this->completed;+ }++ public function getTotal(): int+ {+ return $this->total;+ }++ public function getCreditsUsed(): ?int+ {+ return $this->creditsUsed;+ }++ public function getExpiresAt(): ?string+ {+ return $this->expiresAt;+ }++ public function getNext(): ?string+ {+ return $this->next;+ }++ public function setNext(?string $next): void+ {+ $this->next = $next;+ }++ /** @return list<Document> */+ public function getData(): array+ {+ return $this->data;+ }++ /** @param list<Document> $data */+ public function setData(array $data): void+ {+ $this->data = $data;+ }++ public function appendData(Document $document): void+ {+ $this->data[] = $document;+ }+}diff --git a/apps/php-sdk/src/Models/BatchScrapeOptions.php b/apps/php-sdk/src/Models/BatchScrapeOptions.phpnew file mode 100644index 000000000..5d1b14f08--- /dev/null+++ b/apps/php-sdk/src/Models/BatchScrapeOptions.php@@ -0,0 +1,67 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class BatchScrapeOptions+{+ private function __construct(+ private readonly ?ScrapeOptions $options = null,+ private readonly string|WebhookConfig|null $webhook = null,+ private readonly ?string $appendToId = null,+ private readonly ?bool $ignoreInvalidURLs = null,+ private readonly ?int $maxConcurrency = null,+ private readonly ?bool $zeroDataRetention = null,+ private readonly ?string $idempotencyKey = null,+ private readonly ?string $integration = null,+ ) {}++ public static function with(+ ?ScrapeOptions $options = null,+ string|WebhookConfig|null $webhook = null,+ ?string $appendToId = null,+ ?bool $ignoreInvalidURLs = null,+ ?int $maxConcurrency = null,+ ?bool $zeroDataRetention = null,+ ?string $idempotencyKey = null,+ ?string $integration = null,+ ): self {+ return new self(+ $options, $webhook, $appendToId, $ignoreInvalidURLs,+ $maxConcurrency, $zeroDataRetention, $idempotencyKey, $integration,+ );+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ $fields = [+ 'webhook' => $this->webhook instanceof WebhookConfig ? $this->webhook->toArray() : $this->webhook,+ 'appendToId' => $this->appendToId,+ 'ignoreInvalidURLs' => $this->ignoreInvalidURLs,+ 'maxConcurrency' => $this->maxConcurrency,+ 'zeroDataRetention' => $this->zeroDataRetention,+ 'integration' => $this->integration,+ ];++ $data = array_filter($fields, fn (mixed $v): bool => $v !== null);++ // Flatten scrape options into body (API expects top-level, not nested)+ if ($this->options !== null) {+ $data = array_merge($this->options->toArray(), $data);+ }++ return $data;+ }++ public function getIdempotencyKey(): ?string+ {+ return $this->idempotencyKey;+ }++ public function getOptions(): ?ScrapeOptions+ {+ return $this->options;+ }+}diff --git a/apps/php-sdk/src/Models/BatchScrapeResponse.php b/apps/php-sdk/src/Models/BatchScrapeResponse.phpnew file mode 100644index 000000000..a4f4c964d--- /dev/null+++ b/apps/php-sdk/src/Models/BatchScrapeResponse.php@@ -0,0 +1,43 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class BatchScrapeResponse+{+ /**+ * @param list<string>|null $invalidURLs+ */+ public function __construct(+ private readonly ?string $id = null,+ private readonly ?string $url = null,+ private readonly ?array $invalidURLs = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ id: $data['id'] ?? null,+ url: $data['url'] ?? null,+ invalidURLs: $data['invalidURLs'] ?? null,+ );+ }++ public function getId(): ?string+ {+ return $this->id;+ }++ public function getUrl(): ?string+ {+ return $this->url;+ }++ /** @return list<string>|null */+ public function getInvalidURLs(): ?array+ {+ return $this->invalidURLs;+ }+}diff --git a/apps/php-sdk/src/Models/BrowserCreateResponse.php b/apps/php-sdk/src/Models/BrowserCreateResponse.phpnew file mode 100644index 000000000..4a69d4ff7--- /dev/null+++ b/apps/php-sdk/src/Models/BrowserCreateResponse.php@@ -0,0 +1,60 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class BrowserCreateResponse+{+ public function __construct(+ private readonly bool $success = false,+ private readonly ?string $id = null,+ private readonly ?string $cdpUrl = null,+ private readonly ?string $liveViewUrl = null,+ private readonly ?string $expiresAt = null,+ private readonly ?string $error = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ success: (bool) ($data['success'] ?? false),+ id: $data['id'] ?? null,+ cdpUrl: $data['cdpUrl'] ?? null,+ liveViewUrl: $data['liveViewUrl'] ?? null,+ expiresAt: $data['expiresAt'] ?? null,+ error: $data['error'] ?? null,+ );+ }++ public function isSuccess(): bool+ {+ return $this->success;+ }++ public function getId(): ?string+ {+ return $this->id;+ }++ public function getCdpUrl(): ?string+ {+ return $this->cdpUrl;+ }++ public function getLiveViewUrl(): ?string+ {+ return $this->liveViewUrl;+ }++ public function getExpiresAt(): ?string+ {+ return $this->expiresAt;+ }++ public function getError(): ?string+ {+ return $this->error;+ }+}diff --git a/apps/php-sdk/src/Models/BrowserDeleteResponse.php b/apps/php-sdk/src/Models/BrowserDeleteResponse.phpnew file mode 100644index 000000000..d15ad9bff--- /dev/null+++ b/apps/php-sdk/src/Models/BrowserDeleteResponse.php@@ -0,0 +1,46 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class BrowserDeleteResponse+{+ public function __construct(+ private readonly bool $success = false,+ private readonly ?int $sessionDurationMs = null,+ private readonly ?int $creditsBilled = null,+ private readonly ?string $error = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ success: (bool) ($data['success'] ?? false),+ sessionDurationMs: isset($data['sessionDurationMs']) ? (int) $data['sessionDurationMs'] : null,+ creditsBilled: isset($data['creditsBilled']) ? (int) $data['creditsBilled'] : null,+ error: $data['error'] ?? null,+ );+ }++ public function isSuccess(): bool+ {+ return $this->success;+ }++ public function getSessionDurationMs(): ?int+ {+ return $this->sessionDurationMs;+ }++ public function getCreditsBilled(): ?int+ {+ return $this->creditsBilled;+ }++ public function getError(): ?string+ {+ return $this->error;+ }+}diff --git a/apps/php-sdk/src/Models/BrowserExecuteResponse.php b/apps/php-sdk/src/Models/BrowserExecuteResponse.phpnew file mode 100644index 000000000..b56337a0e--- /dev/null+++ b/apps/php-sdk/src/Models/BrowserExecuteResponse.php@@ -0,0 +1,67 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class BrowserExecuteResponse+{+ public function __construct(+ private readonly bool $success = false,+ private readonly ?string $stdout = null,+ private readonly ?string $result = null,+ private readonly ?string $stderr = null,+ private readonly ?int $exitCode = null,+ private readonly ?bool $killed = null,+ private readonly ?string $error = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ success: (bool) ($data['success'] ?? false),+ stdout: $data['stdout'] ?? null,+ result: $data['result'] ?? null,+ stderr: $data['stderr'] ?? null,+ exitCode: isset($data['exitCode']) ? (int) $data['exitCode'] : null,+ killed: $data['killed'] ?? null,+ error: $data['error'] ?? null,+ );+ }++ public function isSuccess(): bool+ {+ return $this->success;+ }++ public function getStdout(): ?string+ {+ return $this->stdout;+ }++ public function getResult(): ?string+ {+ return $this->result;+ }++ public function getStderr(): ?string+ {+ return $this->stderr;+ }++ public function getExitCode(): ?int+ {+ return $this->exitCode;+ }++ public function isKilled(): ?bool+ {+ return $this->killed;+ }++ public function getError(): ?string+ {+ return $this->error;+ }+}diff --git a/apps/php-sdk/src/Models/BrowserListResponse.php b/apps/php-sdk/src/Models/BrowserListResponse.phpnew file mode 100644index 000000000..184a8614c--- /dev/null+++ b/apps/php-sdk/src/Models/BrowserListResponse.php@@ -0,0 +1,48 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class BrowserListResponse+{+ /**+ * @param list<BrowserSession> $sessions+ */+ public function __construct(+ private readonly bool $success = false,+ private readonly array $sessions = [],+ private readonly ?string $error = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ $sessions = [];+ foreach (($data['sessions'] ?? []) as $session) {+ $sessions[] = BrowserSession::fromArray($session);+ }++ return new self(+ success: (bool) ($data['success'] ?? false),+ sessions: $sessions,+ error: $data['error'] ?? null,+ );+ }++ public function isSuccess(): bool+ {+ return $this->success;+ }++ /** @return list<BrowserSession> */+ public function getSessions(): array+ {+ return $this->sessions;+ }++ public function getError(): ?string+ {+ return $this->error;+ }+}diff --git a/apps/php-sdk/src/Models/BrowserSession.php b/apps/php-sdk/src/Models/BrowserSession.phpnew file mode 100644index 000000000..e7e5cd5d2--- /dev/null+++ b/apps/php-sdk/src/Models/BrowserSession.php@@ -0,0 +1,67 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class BrowserSession+{+ public function __construct(+ private readonly ?string $id = null,+ private readonly ?string $status = null,+ private readonly ?string $cdpUrl = null,+ private readonly ?string $liveViewUrl = null,+ private readonly bool $streamWebView = false,+ private readonly ?string $createdAt = null,+ private readonly ?string $lastActivity = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ id: $data['id'] ?? null,+ status: $data['status'] ?? null,+ cdpUrl: $data['cdpUrl'] ?? null,+ liveViewUrl: $data['liveViewUrl'] ?? null,+ streamWebView: (bool) ($data['streamWebView'] ?? false),+ createdAt: $data['createdAt'] ?? null,+ lastActivity: $data['lastActivity'] ?? null,+ );+ }++ public function getId(): ?string+ {+ return $this->id;+ }++ public function getStatus(): ?string+ {+ return $this->status;+ }++ public function getCdpUrl(): ?string+ {+ return $this->cdpUrl;+ }++ public function getLiveViewUrl(): ?string+ {+ return $this->liveViewUrl;+ }++ public function isStreamWebView(): bool+ {+ return $this->streamWebView;+ }++ public function getCreatedAt(): ?string+ {+ return $this->createdAt;+ }++ public function getLastActivity(): ?string+ {+ return $this->lastActivity;+ }+}diff --git a/apps/php-sdk/src/Models/ConcurrencyCheck.php b/apps/php-sdk/src/Models/ConcurrencyCheck.phpnew file mode 100644index 000000000..0988c64a4--- /dev/null+++ b/apps/php-sdk/src/Models/ConcurrencyCheck.php@@ -0,0 +1,32 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class ConcurrencyCheck+{+ public function __construct(+ private readonly int $concurrency = 0,+ private readonly int $maxConcurrency = 0,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ concurrency: (int) ($data['concurrency'] ?? 0),+ maxConcurrency: (int) ($data['maxConcurrency'] ?? 0),+ );+ }++ public function getConcurrency(): int+ {+ return $this->concurrency;+ }++ public function getMaxConcurrency(): int+ {+ return $this->maxConcurrency;+ }+}diff --git a/apps/php-sdk/src/Models/CrawlJob.php b/apps/php-sdk/src/Models/CrawlJob.phpnew file mode 100644index 000000000..99ee8b63a--- /dev/null+++ b/apps/php-sdk/src/Models/CrawlJob.php@@ -0,0 +1,109 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class CrawlJob+{+ /** @var list<Document> */+ private array $data;++ /**+ * @param list<Document> $data+ */+ public function __construct(+ private readonly ?string $id = null,+ private readonly ?string $status = null,+ private readonly int $total = 0,+ private readonly int $completed = 0,+ private readonly ?int $creditsUsed = null,+ private readonly ?string $expiresAt = null,+ private ?string $next = null,+ array $data = [],+ ) {+ $this->data = $data;+ }++ /** @param array<string, mixed> $raw */+ public static function fromArray(array $raw): self+ {+ $docs = [];+ foreach (($raw['data'] ?? []) as $item) {+ $docs[] = Document::fromArray($item);+ }++ return new self(+ id: $raw['id'] ?? null,+ status: $raw['status'] ?? null,+ total: (int) ($raw['total'] ?? 0),+ completed: (int) ($raw['completed'] ?? 0),+ creditsUsed: $raw['creditsUsed'] ?? null,+ expiresAt: $raw['expiresAt'] ?? null,+ next: $raw['next'] ?? null,+ data: $docs,+ );+ }++ public function isDone(): bool+ {+ return in_array($this->status, ['completed', 'failed', 'cancelled'], true);+ }++ public function getId(): ?string+ {+ return $this->id;+ }++ public function getStatus(): ?string+ {+ return $this->status;+ }++ public function getTotal(): int+ {+ return $this->total;+ }++ public function getCompleted(): int+ {+ return $this->completed;+ }++ public function getCreditsUsed(): ?int+ {+ return $this->creditsUsed;+ }++ public function getExpiresAt(): ?string+ {+ return $this->expiresAt;+ }++ public function getNext(): ?string+ {+ return $this->next;+ }++ public function setNext(?string $next): void+ {+ $this->next = $next;+ }++ /** @return list<Document> */+ public function getData(): array+ {+ return $this->data;+ }++ /** @param list<Document> $data */+ public function setData(array $data): void+ {+ $this->data = $data;+ }++ public function appendData(Document $document): void+ {+ $this->data[] = $document;+ }+}diff --git a/apps/php-sdk/src/Models/CrawlOptions.php b/apps/php-sdk/src/Models/CrawlOptions.phpnew file mode 100644index 000000000..fc535e26f--- /dev/null+++ b/apps/php-sdk/src/Models/CrawlOptions.php@@ -0,0 +1,88 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class CrawlOptions+{+ /**+ * @param list<string>|null $excludePaths+ * @param list<string>|null $includePaths+ */+ private function __construct(+ private readonly ?string $prompt = null,+ private readonly ?array $excludePaths = null,+ private readonly ?array $includePaths = null,+ private readonly ?int $maxDiscoveryDepth = null,+ private readonly ?string $sitemap = null,+ private readonly ?bool $ignoreQueryParameters = null,+ private readonly ?bool $deduplicateSimilarURLs = null,+ private readonly ?int $limit = null,+ private readonly ?bool $crawlEntireDomain = null,+ private readonly ?bool $allowExternalLinks = null,+ private readonly ?bool $allowSubdomains = null,+ private readonly ?int $delay = null,+ private readonly ?int $maxConcurrency = null,+ private readonly string|WebhookConfig|null $webhook = null,+ private readonly ?ScrapeOptions $scrapeOptions = null,+ private readonly ?bool $regexOnFullURL = null,+ private readonly ?bool $zeroDataRetention = null,+ private readonly ?string $integration = null,+ ) {}++ public static function with(+ ?string $prompt = null,+ ?array $excludePaths = null,+ ?array $includePaths = null,+ ?int $maxDiscoveryDepth = null,+ ?string $sitemap = null,+ ?bool $ignoreQueryParameters = null,+ ?bool $deduplicateSimilarURLs = null,+ ?int $limit = null,+ ?bool $crawlEntireDomain = null,+ ?bool $allowExternalLinks = null,+ ?bool $allowSubdomains = null,+ ?int $delay = null,+ ?int $maxConcurrency = null,+ string|WebhookConfig|null $webhook = null,+ ?ScrapeOptions $scrapeOptions = null,+ ?bool $regexOnFullURL = null,+ ?bool $zeroDataRetention = null,+ ?string $integration = null,+ ): self {+ return new self(+ $prompt, $excludePaths, $includePaths, $maxDiscoveryDepth, $sitemap,+ $ignoreQueryParameters, $deduplicateSimilarURLs, $limit, $crawlEntireDomain,+ $allowExternalLinks, $allowSubdomains, $delay, $maxConcurrency, $webhook,+ $scrapeOptions, $regexOnFullURL, $zeroDataRetention, $integration,+ );+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ $fields = [+ 'prompt' => $this->prompt,+ 'excludePaths' => $this->excludePaths,+ 'includePaths' => $this->includePaths,+ 'maxDiscoveryDepth' => $this->maxDiscoveryDepth,+ 'sitemap' => $this->sitemap,+ 'ignoreQueryParameters' => $this->ignoreQueryParameters,+ 'deduplicateSimilarURLs' => $this->deduplicateSimilarURLs,+ 'limit' => $this->limit,+ 'crawlEntireDomain' => $this->crawlEntireDomain,+ 'allowExternalLinks' => $this->allowExternalLinks,+ 'allowSubdomains' => $this->allowSubdomains,+ 'delay' => $this->delay,+ 'maxConcurrency' => $this->maxConcurrency,+ 'webhook' => $this->webhook instanceof WebhookConfig ? $this->webhook->toArray() : $this->webhook,+ 'scrapeOptions' => $this->scrapeOptions?->toArray(),+ 'regexOnFullURL' => $this->regexOnFullURL,+ 'zeroDataRetention' => $this->zeroDataRetention,+ 'integration' => $this->integration,+ ];++ return array_filter($fields, fn (mixed $v): bool => $v !== null);+ }+}diff --git a/apps/php-sdk/src/Models/CrawlResponse.php b/apps/php-sdk/src/Models/CrawlResponse.phpnew file mode 100644index 000000000..396e1e649--- /dev/null+++ b/apps/php-sdk/src/Models/CrawlResponse.php@@ -0,0 +1,32 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class CrawlResponse+{+ public function __construct(+ private readonly ?string $id = null,+ private readonly ?string $url = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ id: $data['id'] ?? null,+ url: $data['url'] ?? null,+ );+ }++ public function getId(): ?string+ {+ return $this->id;+ }++ public function getUrl(): ?string+ {+ return $this->url;+ }+}diff --git a/apps/php-sdk/src/Models/CreditUsage.php b/apps/php-sdk/src/Models/CreditUsage.phpnew file mode 100644index 000000000..181319633--- /dev/null+++ b/apps/php-sdk/src/Models/CreditUsage.php@@ -0,0 +1,46 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class CreditUsage+{+ public function __construct(+ private readonly int $remainingCredits = 0,+ private readonly ?int $planCredits = null,+ private readonly ?string $billingPeriodStart = null,+ private readonly ?string $billingPeriodEnd = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ remainingCredits: (int) ($data['remainingCredits'] ?? 0),+ planCredits: isset($data['planCredits']) ? (int) $data['planCredits'] : null,+ billingPeriodStart: $data['billingPeriodStart'] ?? null,+ billingPeriodEnd: $data['billingPeriodEnd'] ?? null,+ );+ }++ public function getRemainingCredits(): int+ {+ return $this->remainingCredits;+ }++ public function getPlanCredits(): ?int+ {+ return $this->planCredits;+ }++ public function getBillingPeriodStart(): ?string+ {+ return $this->billingPeriodStart;+ }++ public function getBillingPeriodEnd(): ?string+ {+ return $this->billingPeriodEnd;+ }+}diff --git a/apps/php-sdk/src/Models/Document.php b/apps/php-sdk/src/Models/Document.phpnew file mode 100644index 000000000..ad9f021b0--- /dev/null+++ b/apps/php-sdk/src/Models/Document.php@@ -0,0 +1,139 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class Document+{+ /**+ * @param array<string, mixed>|null $metadata+ * @param list<string>|null $links+ * @param list<string>|null $images+ * @param list<array<string, mixed>>|null $attributes+ * @param array<string, mixed>|null $actions+ * @param array<string, mixed>|null $changeTracking+ * @param array<string, mixed>|null $branding+ */+ public function __construct(+ private readonly ?string $markdown = null,+ private readonly ?string $html = null,+ private readonly ?string $rawHtml = null,+ private readonly mixed $json = null,+ private readonly ?string $summary = null,+ private readonly ?array $metadata = null,+ private readonly ?array $links = null,+ private readonly ?array $images = null,+ private readonly ?string $screenshot = null,+ private readonly ?string $audio = null,+ private readonly ?array $attributes = null,+ private readonly ?array $actions = null,+ private readonly ?string $warning = null,+ private readonly ?array $changeTracking = null,+ private readonly ?array $branding = null,+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ markdown: $data['markdown'] ?? null,+ html: $data['html'] ?? null,+ rawHtml: $data['rawHtml'] ?? null,+ json: $data['json'] ?? null,+ summary: $data['summary'] ?? null,+ metadata: $data['metadata'] ?? null,+ links: $data['links'] ?? null,+ images: $data['images'] ?? null,+ screenshot: $data['screenshot'] ?? null,+ audio: $data['audio'] ?? null,+ attributes: $data['attributes'] ?? null,+ actions: $data['actions'] ?? null,+ warning: $data['warning'] ?? null,+ changeTracking: $data['changeTracking'] ?? null,+ branding: $data['branding'] ?? null,+ );+ }++ public function getMarkdown(): ?string+ {+ return $this->markdown;+ }++ public function getHtml(): ?string+ {+ return $this->html;+ }++ public function getRawHtml(): ?string+ {+ return $this->rawHtml;+ }++ public function getJson(): mixed+ {+ return $this->json;+ }++ public function getSummary(): ?string+ {+ return $this->summary;+ }++ /** @return array<string, mixed>|null */+ public function getMetadata(): ?array+ {+ return $this->metadata;+ }++ /** @return list<string>|null */+ public function getLinks(): ?array+ {+ return $this->links;+ }++ /** @return list<string>|null */+ public function getImages(): ?array+ {+ return $this->images;+ }++ public function getScreenshot(): ?string+ {+ return $this->screenshot;+ }++ public function getAudio(): ?string+ {+ return $this->audio;+ }++ /** @return list<array<string, mixed>>|null */+ public function getAttributes(): ?array+ {+ return $this->attributes;+ }++ /** @return array<string, mixed>|null */+ public function getActions(): ?array+ {+ return $this->actions;+ }++ public function getWarning(): ?string+ {+ return $this->warning;+ }++ /** @return array<string, mixed>|null */+ public function getChangeTracking(): ?array+ {+ return $this->changeTracking;+ }++ /** @return array<string, mixed>|null */+ public function getBranding(): ?array+ {+ return $this->branding;+ }+}diff --git a/apps/php-sdk/src/Models/JsonFormat.php b/apps/php-sdk/src/Models/JsonFormat.phpnew file mode 100644index 000000000..226574c61--- /dev/null+++ b/apps/php-sdk/src/Models/JsonFormat.php@@ -0,0 +1,42 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class JsonFormat+{+ private function __construct(+ private readonly ?string $prompt = null,+ /** @var array<string, mixed>|null */+ private readonly ?array $schema = null,+ ) {}++ public static function with(+ ?string $prompt = null,+ ?array $schema = null,+ ): self {+ return new self($prompt, $schema);+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ return array_filter([+ 'type' => 'json',+ 'prompt' => $this->prompt,+ 'schema' => $this->schema,+ ], fn (mixed $v): bool => $v !== null);+ }++ public function getPrompt(): ?string+ {+ return $this->prompt;+ }++ /** @return array<string, mixed>|null */+ public function getSchema(): ?array+ {+ return $this->schema;+ }+}diff --git a/apps/php-sdk/src/Models/LocationConfig.php b/apps/php-sdk/src/Models/LocationConfig.phpnew file mode 100644index 000000000..5b8c189b1--- /dev/null+++ b/apps/php-sdk/src/Models/LocationConfig.php@@ -0,0 +1,41 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class LocationConfig+{+ private function __construct(+ private readonly ?string $country = null,+ /** @var list<string>|null */+ private readonly ?array $languages = null,+ ) {}++ public static function with(+ ?string $country = null,+ ?array $languages = null,+ ): self {+ return new self($country, $languages);+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ return array_filter([+ 'country' => $this->country,+ 'languages' => $this->languages,+ ], fn (mixed $v): bool => $v !== null);+ }++ public function getCountry(): ?string+ {+ return $this->country;+ }++ /** @return list<string>|null */+ public function getLanguages(): ?array+ {+ return $this->languages;+ }+}diff --git a/apps/php-sdk/src/Models/MapData.php b/apps/php-sdk/src/Models/MapData.phpnew file mode 100644index 000000000..2c8627628--- /dev/null+++ b/apps/php-sdk/src/Models/MapData.php@@ -0,0 +1,38 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class MapData+{+ /**+ * @param list<array<string, mixed>> $links+ */+ public function __construct(+ private readonly array $links = [],+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ $rawLinks = $data['links'] ?? [];+ $normalized = [];++ foreach ($rawLinks as $link) {+ if (is_string($link)) {+ $normalized[] = ['url' => $link];+ } elseif (is_array($link)) {+ $normalized[] = $link;+ }+ }++ return new self(links: $normalized);+ }++ /** @return list<array<string, mixed>> */+ public function getLinks(): array+ {+ return $this->links;+ }+}diff --git a/apps/php-sdk/src/Models/MapOptions.php b/apps/php-sdk/src/Models/MapOptions.phpnew file mode 100644index 000000000..6eebd94ef--- /dev/null+++ b/apps/php-sdk/src/Models/MapOptions.php@@ -0,0 +1,52 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class MapOptions+{+ private function __construct(+ private readonly ?string $search = null,+ private readonly ?string $sitemap = null,+ private readonly ?bool $includeSubdomains = null,+ private readonly ?bool $ignoreQueryParameters = null,+ private readonly ?int $limit = null,+ private readonly ?int $timeout = null,+ private readonly ?string $integration = null,+ private readonly ?LocationConfig $location = null,+ ) {}++ public static function with(+ ?string $search = null,+ ?string $sitemap = null,+ ?bool $includeSubdomains = null,+ ?bool $ignoreQueryParameters = null,+ ?int $limit = null,+ ?int $timeout = null,+ ?string $integration = null,+ ?LocationConfig $location = null,+ ): self {+ return new self(+ $search, $sitemap, $includeSubdomains, $ignoreQueryParameters,+ $limit, $timeout, $integration, $location,+ );+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ $fields = [+ 'search' => $this->search,+ 'sitemap' => $this->sitemap,+ 'includeSubdomains' => $this->includeSubdomains,+ 'ignoreQueryParameters' => $this->ignoreQueryParameters,+ 'limit' => $this->limit,+ 'timeout' => $this->timeout,+ 'integration' => $this->integration,+ 'location' => $this->location?->toArray(),+ ];++ return array_filter($fields, fn (mixed $v): bool => $v !== null);+ }+}diff --git a/apps/php-sdk/src/Models/ScrapeOptions.php b/apps/php-sdk/src/Models/ScrapeOptions.phpnew file mode 100644index 000000000..f48267dee--- /dev/null+++ b/apps/php-sdk/src/Models/ScrapeOptions.php@@ -0,0 +1,202 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class ScrapeOptions+{+ /**+ * @param list<string|JsonFormat>|null $formats+ * @param array<string, string>|null $headers+ * @param list<string>|null $includeTags+ * @param list<string>|null $excludeTags+ * @param list<mixed>|null $parsers+ * @param list<array<string, mixed>>|null $actions+ */+ private function __construct(+ private readonly ?array $formats = null,+ private readonly ?array $headers = null,+ private readonly ?array $includeTags = null,+ private readonly ?array $excludeTags = null,+ private readonly ?bool $onlyMainContent = null,+ private readonly ?int $timeout = null,+ private readonly ?int $waitFor = null,+ private readonly ?bool $mobile = null,+ private readonly ?array $parsers = null,+ private readonly ?array $actions = null,+ private readonly ?LocationConfig $location = null,+ private readonly ?bool $skipTlsVerification = null,+ private readonly ?bool $removeBase64Images = null,+ private readonly ?bool $blockAds = null,+ private readonly ?string $proxy = null,+ private readonly ?int $maxAge = null,+ private readonly ?bool $storeInCache = null,+ private readonly ?string $integration = null,+ ) {}++ public static function with(+ ?array $formats = null,+ ?array $headers = null,+ ?array $includeTags = null,+ ?array $excludeTags = null,+ ?bool $onlyMainContent = null,+ ?int $timeout = null,+ ?int $waitFor = null,+ ?bool $mobile = null,+ ?array $parsers = null,+ ?array $actions = null,+ ?LocationConfig $location = null,+ ?bool $skipTlsVerification = null,+ ?bool $removeBase64Images = null,+ ?bool $blockAds = null,+ ?string $proxy = null,+ ?int $maxAge = null,+ ?bool $storeInCache = null,+ ?string $integration = null,+ ): self {+ return new self(+ $formats, $headers, $includeTags, $excludeTags, $onlyMainContent,+ $timeout, $waitFor, $mobile, $parsers, $actions, $location,+ $skipTlsVerification, $removeBase64Images, $blockAds, $proxy,+ $maxAge, $storeInCache, $integration,+ );+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ $data = [];++ if ($this->formats !== null) {+ $data['formats'] = array_map(+ fn (string|JsonFormat $f): string|array => $f instanceof JsonFormat ? $f->toArray() : $f,+ $this->formats,+ );+ }++ $fields = [+ 'headers' => $this->headers,+ 'includeTags' => $this->includeTags,+ 'excludeTags' => $this->excludeTags,+ 'onlyMainContent' => $this->onlyMainContent,+ 'timeout' => $this->timeout,+ 'waitFor' => $this->waitFor,+ 'mobile' => $this->mobile,+ 'parsers' => $this->parsers,+ 'actions' => $this->actions,+ 'location' => $this->location?->toArray(),+ 'skipTlsVerification' => $this->skipTlsVerification,+ 'removeBase64Images' => $this->removeBase64Images,+ 'blockAds' => $this->blockAds,+ 'proxy' => $this->proxy,+ 'maxAge' => $this->maxAge,+ 'storeInCache' => $this->storeInCache,+ 'integration' => $this->integration,+ ];++ foreach ($fields as $key => $value) {+ if ($value !== null) {+ $data[$key] = $value;+ }+ }++ return $data;+ }++ /** @return list<string|JsonFormat>|null */+ public function getFormats(): ?array+ {+ return $this->formats;+ }++ /** @return array<string, string>|null */+ public function getHeaders(): ?array+ {+ return $this->headers;+ }++ /** @return list<string>|null */+ public function getIncludeTags(): ?array+ {+ return $this->includeTags;+ }++ /** @return list<string>|null */+ public function getExcludeTags(): ?array+ {+ return $this->excludeTags;+ }++ public function getOnlyMainContent(): ?bool+ {+ return $this->onlyMainContent;+ }++ public function getTimeout(): ?int+ {+ return $this->timeout;+ }++ public function getWaitFor(): ?int+ {+ return $this->waitFor;+ }++ public function getMobile(): ?bool+ {+ return $this->mobile;+ }++ /** @return list<mixed>|null */+ public function getParsers(): ?array+ {+ return $this->parsers;+ }++ /** @return list<array<string, mixed>>|null */+ public function getActions(): ?array+ {+ return $this->actions;+ }++ public function getLocation(): ?LocationConfig+ {+ return $this->location;+ }++ public function getSkipTlsVerification(): ?bool+ {+ return $this->skipTlsVerification;+ }++ public function getRemoveBase64Images(): ?bool+ {+ return $this->removeBase64Images;+ }++ public function getBlockAds(): ?bool+ {+ return $this->blockAds;+ }++ public function getProxy(): ?string+ {+ return $this->proxy;+ }++ public function getMaxAge(): ?int+ {+ return $this->maxAge;+ }++ public function getStoreInCache(): ?bool+ {+ return $this->storeInCache;+ }++ public function getIntegration(): ?string+ {+ return $this->integration;+ }+}diff --git a/apps/php-sdk/src/Models/SearchData.php b/apps/php-sdk/src/Models/SearchData.phpnew file mode 100644index 000000000..9236964ed--- /dev/null+++ b/apps/php-sdk/src/Models/SearchData.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class SearchData+{+ /**+ * @param list<array<string, mixed>> $web+ * @param list<array<string, mixed>> $news+ * @param list<array<string, mixed>> $images+ */+ public function __construct(+ private readonly array $web = [],+ private readonly array $news = [],+ private readonly array $images = [],+ ) {}++ /** @param array<string, mixed> $data */+ public static function fromArray(array $data): self+ {+ return new self(+ web: $data['web'] ?? [],+ news: $data['news'] ?? [],+ images: $data['images'] ?? [],+ );+ }++ /** @return list<array<string, mixed>> */+ public function getWeb(): array+ {+ return $this->web;+ }++ /** @return list<array<string, mixed>> */+ public function getNews(): array+ {+ return $this->news;+ }++ /** @return list<array<string, mixed>> */+ public function getImages(): array+ {+ return $this->images;+ }+}diff --git a/apps/php-sdk/src/Models/SearchOptions.php b/apps/php-sdk/src/Models/SearchOptions.phpnew file mode 100644index 000000000..d5c630806--- /dev/null+++ b/apps/php-sdk/src/Models/SearchOptions.php@@ -0,0 +1,59 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class SearchOptions+{+ /**+ * @param list<mixed>|null $sources+ * @param list<mixed>|null $categories+ */+ private function __construct(+ private readonly ?array $sources = null,+ private readonly ?array $categories = null,+ private readonly ?int $limit = null,+ private readonly ?string $tbs = null,+ private readonly ?string $location = null,+ private readonly ?bool $ignoreInvalidURLs = null,+ private readonly ?int $timeout = null,+ private readonly ?ScrapeOptions $scrapeOptions = null,+ private readonly ?string $integration = null,+ ) {}++ public static function with(+ ?array $sources = null,+ ?array $categories = null,+ ?int $limit = null,+ ?string $tbs = null,+ ?string $location = null,+ ?bool $ignoreInvalidURLs = null,+ ?int $timeout = null,+ ?ScrapeOptions $scrapeOptions = null,+ ?string $integration = null,+ ): self {+ return new self(+ $sources, $categories, $limit, $tbs, $location,+ $ignoreInvalidURLs, $timeout, $scrapeOptions, $integration,+ );+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ $fields = [+ 'sources' => $this->sources,+ 'categories' => $this->categories,+ 'limit' => $this->limit,+ 'tbs' => $this->tbs,+ 'location' => $this->location,+ 'ignoreInvalidURLs' => $this->ignoreInvalidURLs,+ 'timeout' => $this->timeout,+ 'scrapeOptions' => $this->scrapeOptions?->toArray(),+ 'integration' => $this->integration,+ ];++ return array_filter($fields, fn (mixed $v): bool => $v !== null);+ }+}diff --git a/apps/php-sdk/src/Models/WebhookConfig.php b/apps/php-sdk/src/Models/WebhookConfig.phpnew file mode 100644index 000000000..2aaad89ae--- /dev/null+++ b/apps/php-sdk/src/Models/WebhookConfig.php@@ -0,0 +1,61 @@+<?php++declare(strict_types=1);++namespace Firecrawl\Models;++final class WebhookConfig+{+ private function __construct(+ private readonly string $url,+ /** @var array<string, string>|null */+ private readonly ?array $headers = null,+ /** @var array<string, string>|null */+ private readonly ?array $metadata = null,+ /** @var list<string>|null */+ private readonly ?array $events = null,+ ) {}++ public static function with(+ string $url,+ ?array $headers = null,+ ?array $metadata = null,+ ?array $events = null,+ ): self {+ return new self($url, $headers, $metadata, $events);+ }++ /** @return array<string, mixed> */+ public function toArray(): array+ {+ return array_filter([+ 'url' => $this->url,+ 'headers' => $this->headers,+ 'metadata' => $this->metadata,+ 'events' => $this->events,+ ], fn (mixed $v): bool => $v !== null);+ }++ public function getUrl(): string+ {+ return $this->url;+ }++ /** @return array<string, string>|null */+ public function getHeaders(): ?array+ {+ return $this->headers;+ }++ /** @return array<string, string>|null */+ public function getMetadata(): ?array+ {+ return $this->metadata;+ }++ /** @return list<string>|null */+ public function getEvents(): ?array+ {+ return $this->events;+ }+}