### Install Iminify PHP via Composer Source: https://github.com/mozex/iminify-php/blob/main/docs/introduction.md Install the Iminify PHP client using Composer. Requires PHP 8.2+. ```bash composer require mozex/iminify-php ``` -------------------------------- ### Get Account Information with $client->account()->get() Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/account.md Retrieves the key's account details including plan, limits, and usage. The plan is compared against the Plan::Pro enum, and usage fields track daily allowances with a rolling 24-hour reset. ```php use Mozex\Iminify\Enums\Plan; $account = $client->account()->get(); $account->plan === Plan::Pro; $account->planEndsAt; // when a paid plan or a trial ends, null while it renews $account->limits->imagesPerDay; $account->limits->maxFileSize; $account->usage->images->used; $account->usage->images->remaining; $account->usage->images->resetsAt; // a rolling 24 hours from the first use ``` -------------------------------- ### Install spatie/image-optimizer via Composer Source: https://github.com/mozex/iminify-php/blob/main/docs/integrations/spatie.md Required before using IminifyOptimizer. The package requires spatie/image-optimizer 1.10 or newer, which is not installed automatically. ```bash composer require spatie/image-optimizer ``` -------------------------------- ### Quick Start: Upload, Wait, and Download Image Source: https://github.com/mozex/iminify-php/blob/main/docs/introduction.md Create a client with an API key and timeout, upload an image, wait for the result, and download the optimized file. Outputs the status and saved percentage. ```php use Mozex\Iminify\Iminify; $client = Iminify::factory() ->withApiKey(getenv('IMINIFY_API_KEY')) ->withTimeout(300) ->make(); $image = $client->images()->upload('photos/team.jpg', ['format' => 'webp']); $image = $client->images()->wait($image); if ($image->hasResult()) { $client->images()->download($image)->saveTo('photos/team.webp'); } echo "{$image->status->value}, saved {$image->savedPercent}%"; ``` -------------------------------- ### Install Guzzle HTTP Client for PSR-18 Source: https://github.com/mozex/iminify-php/blob/main/docs/introduction.md Install Guzzle as a PSR-18 HTTP client when the project has no PSR-18 client or PSR-17 factories. ```bash composer require guzzlehttp/guzzle ``` -------------------------------- ### $client->account()->get() Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/account.md Reads the key's account information, including plan, plan limits, and today's usage. Returns an account object with plan, limits, and usage details. ```APIDOC ## $client->account()->get() ### Description Reads the key's account: its plan, what the plan allows, and how much of today's allowance is gone. ### Method GET ### Endpoint `$client->account()->get()` ### Response #### Success Response - **plan** (Plan) - The account's plan (e.g., `Plan::Pro`) - **planEndsAt** (datetime|null) - When a paid plan or trial ends, null while it renews - **limits** (object) - Plan limits - **imagesPerDay** (int|null) - Daily image limit, null if unlimited - **maxFileSize** (int) - Maximum file size allowed - **usage** (object) - Usage details - **images** (Usage) - Image usage - **used** (int) - Used count - **remaining** (int|null) - Remaining count, null if unlimited - **resetsAt** (datetime) - Rolling 24 hours from first use - **scans** (Usage) - Scan usage - **crawls** (Usage) - Crawl usage - **altTexts** (Usage) - Alt text usage - **files** (Usage) - File usage ### Request Example ```php use Mozex\Iminify\Enums\Plan; $account = $client->account()->get(); $account->plan === Plan::Pro; $account->planEndsAt; // when a paid plan or a trial ends, null while it renews $account->limits->imagesPerDay; $account->limits->maxFileSize; $account->usage->images->used; $account->usage->images->remaining; $account->usage->images->resetsAt; // a rolling 24 hours from the first use ``` ``` -------------------------------- ### Use IminifyOptimizer with spatie/image and Browsershot Source: https://github.com/mozex/iminify-php/blob/main/docs/integrations/spatie.md Shows how to pass the chain to Image::optimize() and Browsershot::optimize(). Browsershot requires spatie/image to be installed. Calling optimize() without a chain uses the default command-line tools. ```php use Spatie\Browsershot\Browsershot; use Spatie\Image\Image; Image::load('photos/team.jpg')->width(1200)->optimize($chain)->save('photos/team-1200.jpg'); Browsershot::url('https://example.com')->optimize($chain)->save('shot.png'); ``` -------------------------------- ### Perform various image operations (get, rename, recompress, retry, cancel, alt text, share, delete) Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Covers common image operations: get, rename, renameMany, recompress, retry, cancel, writeAltText, share, unshare, and delete. Note that recompress creates a new image from the same original, cancel only works while the image is queued, and share provides the image's shareUrl. ```php $client->images()->get($id); $client->images()->rename($image, 'team-offsite'); $client->images()->renameMany([$first, $second], 'team-offsite'); $client->images()->recompress($image, ['level' => 'ultra']); // a new image from the same original $client->images()->retry($image); $client->images()->cancel($image); // only while it's queued $client->images()->writeAltText($image, ['alt_text_language' => 'de']); $client->images()->share($image); // its shareUrl $client->images()->unshare($image); $client->images()->delete($image); ``` -------------------------------- ### Send request to new endpoint via transporter Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/configuration.md Use transporter() to access the API directly for endpoints not yet supported. ApiRequest::get() sends a GET request with query parameters. ```php use Mozex\Iminify\Http\ApiRequest; $response = $client->transporter()->send(ApiRequest::get('something-new', ['page' => 2])); $response->json(); ``` -------------------------------- ### fromPages Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/site-crawls.md Starts a site crawl from a list of page URLs on one site. ```APIDOC ## fromPages ### Description Starts a site crawl from a list of page URLs on one site. ### Method POST ### Endpoint `$client->crawls()->fromPages($pages)` ### Parameters #### Request Body - **$pages** (array of strings) - Required - List of page URLs to crawl. ### Response #### Success Response (200) - **crawl** (object) - The created crawl object. ### Request Example ```php $crawl = $client->crawls()->fromPages([ 'https://example.com/', 'https://example.com/pricing', ]); ``` ``` -------------------------------- ### fromSitemap Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/site-crawls.md Starts a site crawl from a sitemap URL. Accepts an XML sitemap, sitemap index, or text file with one address per line. ```APIDOC ## fromSitemap ### Description Starts a site crawl from a sitemap URL. Accepts an XML sitemap, sitemap index, or text file with one address per line. ### Method POST ### Endpoint `$client->crawls()->fromSitemap($sitemapUrl, $options)` ### Parameters #### Path Parameters - **$sitemapUrl** (string) - Required - The URL of the sitemap. #### Request Body - **format** (string) - Optional - Desired image format (e.g., 'webp'). ### Response #### Success Response (200) - **crawl** (object) - The created crawl object. ### Request Example ```php $crawl = $client->crawls()->fromSitemap('https://example.com/sitemap.xml', ['format' => 'webp']); ``` ``` -------------------------------- ### get Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/site-crawls.md Retrieves a single crawl by ID. ```APIDOC ## get ### Description Retrieves a single crawl by ID. ### Method GET ### Endpoint `$client->crawls()->get($id)` ### Parameters #### Path Parameters - **$id** (string) - Required - The crawl ID. ### Response #### Success Response (200) - **crawl** (object) - The crawl object. ### Request Example ```php $client->crawls()->get($id); ``` ``` -------------------------------- ### Download an image with saveTo, writeTo, and contents Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Downloads an image without loading it into memory until requested. `saveTo()` writes the file in one step and returns bytes written; `writeTo()` writes to an open stream; `contents()` returns the full contents. Properties `name`, `mimeType`, and `size` are available. Pass `DownloadType::Original` as the second argument to `download()` to get the original file. `saveTo()` fails rather than saving a short file and accepts a size as its second argument (e.g., `$image->optimized->size`) for responses without a length; its third argument is a closure given the finished temporary file's path before replacement, which throws to keep what's at the path. It follows links, and a replaced file keeps its permissions but belongs to the PHP user. ```php $download = $client->images()->download($image); $download->saveTo('photos/team.webp'); // lands in one step, and returns the bytes written $download->writeTo($openStream); $download->contents(); $download->name; // the name the API offers it under, which comes from outside your app $download->mimeType; $download->size; ``` -------------------------------- ### List, get, update, and delete monitors Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/weekly-checks.md Shows the monitor management methods: `list()` returns every check oldest first and is never paged, `get($id)` fetches one, `update()` can disable emails while keeping it running, and `delete()` removes it. Also shows accessing the last run's saved percent via `lastRun?->savedPercent`. ```php $client->monitors()->list(); // every check, oldest first, never paged $client->monitors()->get($id); $client->monitors()->update($monitor, ['emails' => false]); // keeps it running without the emails $client->monitors()->delete($monitor); $monitor->lastRun?->savedPercent; // the crawl it last ran ``` -------------------------------- ### Create a weekly monitor from a crawl Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/weekly-checks.md Creates a weekly check from an existing crawl. The monitor's next run is a week later; nothing runs or counts until then. The example prints the next run time using the `nextRunAt` property. ```php $monitor = $client->monitors()->create($crawl); echo $monitor->nextRunAt->format('c'); ``` -------------------------------- ### Start a crawl from a sitemap or a list of pages Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/site-crawls.md Creates a site crawl from either a sitemap URL or an array of page URLs. The `fromSitemap` method accepts an optional format option (e.g., 'webp'). Both methods return a crawl object. ```php $crawl = $client->crawls()->fromSitemap('https://example.com/sitemap.xml', ['format' => 'webp']); $crawl = $client->crawls()->fromPages([ 'https://example.com/', 'https://example.com/pricing', ]); ``` -------------------------------- ### download($image, $type = null) Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Downloads an image file. The download is lazy; data is only read when you call contents(), saveTo(), or writeTo(). Optionally pass DownloadType::Original as the second argument to get the original file. ```APIDOC ## download($image, $type = null) ### Description Downloads an image file. The download is lazy; data is only read when you call contents(), saveTo(), or writeTo(). Optionally pass DownloadType::Original as the second argument to get the original file. ### Method PHP method call ### Endpoint `$client->images()->download($image, $type = null)` ### Parameters - **$image** (Image) - Required - The image object to download. - **$type** (DownloadType|null) - Optional - Pass `DownloadType::Original` to get the original file instead of the optimized version. ### Response Returns a Download object with the following properties: - **name** (string) - The name the API offers it under. - **mimeType** (string) - The MIME type of the file. - **size** (int) - The size of the file in bytes. ### Methods on the Download object - **saveTo($path, $expectedSize = null, $onComplete = null)** - Saves the download to a file path. Returns the bytes written. Fails rather than saving a short file. The second argument is the expected size (e.g., `$image->optimized->size`) for responses that don't state their length. The third argument is a closure given the finished temporary file's path before anything is replaced; throwing inside it keeps what's at the path. Follows links and preserves permissions of replaced files. - **writeTo($stream)** - Writes the download to an open stream. - **contents()** - Returns the file contents as a string. ### Request Example ```php $download = $client->images()->download($image); $download->saveTo('photos/team.webp'); ``` ``` -------------------------------- ### Catch ApiException and inspect properties Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/error-handling.md Catches any API refusal via ApiException and shows its properties: status, errorCode, getMessage(), errors, and retryAfter. Branch on errorCode rather than the message, which gets reworded. ```php use Mozex\Iminify\Exceptions\ApiException; try { $image = $client->images()->upload('photos/team.jpg', ['size_limit' => 1]); } catch (ApiException $exception) { $exception->status; // 422 $exception->errorCode; // validation_failed $exception->getMessage(); // words meant for a person $exception->errors; // on a validation failure, each field's messages $exception->retryAfter; // the response's Retry-After, in seconds } ``` -------------------------------- ### Iterate over crawl pages Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/site-crawls.md Each page of a crawl is a page scan. This loop prints the URL, status, and number of images to fix for each page. Use `$client->scans()->get($page->id)` to read a full page scan with its report. ```php foreach ($crawl->pages ?? [] as $page) { echo "{$page->url}: {$page->status->value}, {$page->imagesToFix} to fix\n"; } ``` -------------------------------- ### get Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/page-scans.md Retrieves a scan by its ID. ```APIDOC ## get ### Description Retrieves a scan by its ID. ### Method get ### Endpoint $client->scans()->get() ### Parameters #### Path Parameters - **id** (string) - Required - The scan ID. ### Response #### Success Response - **scan** (object) - The scan object. ### Request Example ```php $client->scans()->get($id); ``` ``` -------------------------------- ### Upload groups: create, send source, wait, and download Source: https://github.com/mozex/iminify-php/blob/main/README.md Create a group with source and output specifications, send the source file, wait for completion, and download the result as a ZIP. The width and height must be as displayed; getimagesize() gives stored dimensions, not displayed ones. ```php use Mozex\Iminify\Enums\GroupFormat; use Mozex\Iminify\Http\Upload; $upload = Upload::fromPath('photos/team.jpg'); $group = $client->groups()->create([ 'source' => ['format' => 'jpg', 'size' => $upload->size(), 'width' => 2560, 'height' => 1707], 'outputs' => [ ['name' => 'full', 'width' => 2560, 'height' => 1707], ['name' => 'medium', 'width' => 300, 'height' => 200], ], 'formats' => [GroupFormat::Original, GroupFormat::Webp], ]); $group = $client->groups()->sendSource($group, $upload); $group = $client->groups()->wait($group); $client->groups()->download($group)->saveTo('photos/team.zip'); ``` -------------------------------- ### get Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/weekly-checks.md Retrieves a specific weekly check by its ID. ```APIDOC ## get ### Description Retrieves a specific weekly check by its ID. ### Method get ### Parameters - **$id** - Required - The ID of the monitor to retrieve. ### Response Returns a monitor object. ### Request Example ```php $client->monitors()->get($id); ``` ``` -------------------------------- ### Create client with factory and API key Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/configuration.md Use Iminify::factory() to build a client with custom settings. withApiKey() is required; withTimeout() sets a timeout on a discovered client. ```php use Mozex\Iminify\Iminify; $client = Iminify::factory() ->withApiKey(getenv('IMINIFY_API_KEY')) ->withTimeout(300) ->make(); ``` -------------------------------- ### groups()->get() Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/upload-groups.md Reads a single upload group by its id. ```APIDOC ## groups()->get() ### Description Reads a single upload group by its id. ### Method get() ### Parameters - **id** - Required - The group id. ### Request Example ```php $group = $client->groups()->get($id); ``` ``` -------------------------------- ### Fixtures::file() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a download response. ```APIDOC ## Fixtures::file() ### Description Returns a fixture for a download response. ### Method file ### Parameters #### Arguments - **contents** (string) - Required - The file contents. ### Returns - **ApiResponse** - The file response. ### Example ```php Fixtures::file('the bytes') ``` ``` -------------------------------- ### update Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/weekly-checks.md Updates a weekly check. For example, you can disable emails while keeping the check running. ```APIDOC ## update ### Description Updates a weekly check. For example, you can disable emails while keeping the check running. ### Method update ### Parameters - **$monitor** - Required - The monitor object to update. - **$data** - Required - An array of fields to update, e.g., `['emails' => false]`. ### Response Returns the updated monitor object. ### Request Example ```php $client->monitors()->update($monitor, ['emails' => false]); ``` ``` -------------------------------- ### Composer test commands Source: https://github.com/mozex/iminify-php/blob/main/CLAUDE.md Run the full test suite, linting, static analysis, type coverage, and unit tests. Use the individual commands to run specific checks or a single test file/filter. ```bash composer test # lint + static analysis + type coverage + tests, the gate before every commit ``` ```bash composer lint # fix code style (Pint) ``` ```bash composer test:lint # check code style without fixing ``` ```bash composer test:types # PHPStan ``` ```bash composer test:type-coverage # Pest type coverage (minimum 100%) ``` ```bash composer test:unit # Pest ``` ```bash vendor/bin/pest tests/SomeTest.php # one file ``` ```bash vendor/bin/pest --filter="test name here" # one test ``` -------------------------------- ### Fixtures::account() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a free account. ```APIDOC ## Fixtures::account() ### Description Returns a fixture for a free account. ### Method account ### Returns - **array** - The account record. ``` -------------------------------- ### Your own tests with FakeClient Source: https://github.com/mozex/iminify-php/blob/main/README.md Use FakeClient with a fixture to simulate API responses. The client answers from a queue through real resources, so your code reads the same objects and catches the same exceptions as for real. ```php use Mozex\Iminify\Testing\FakeClient; use Mozex\Iminify\Testing\Fixtures; $client = new FakeClient([Fixtures::image()]); $image = $client->images()->get('abc'); $client->assertSent('GET', 'images/abc'); ``` -------------------------------- ### images()->get($id) Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Retrieves an image by its ID. This method is part of the Iminify PHP SDK and returns the image object. ```APIDOC ## images()->get($id) ### Description Retrieves an image by its ID. ### Method GET ### Endpoint `$client->images()->get($id)` ### Parameters #### Path Parameters - **$id** (string) - Required - The ID of the image to retrieve. ### Response Returns the image object. ``` -------------------------------- ### Use IminifyOptimizer in an OptimizerChain Source: https://github.com/mozex/iminify-php/blob/main/docs/integrations/spatie.md Builds a chain with IminifyOptimizer, passing an API key from the environment. The chain compresses files via Iminify instead of command-line tools. Avoid OptimizerChainFactory::create with only IminifyOptimizer; it silently falls back to the default chain. Add a built-in optimizer like Svgo or build the chain manually. ```php use Mozex\Iminify\Spatie\IminifyOptimizer; use Spatie\ImageOptimizer\OptimizerChain; $chain = (new OptimizerChain)->addOptimizer(new IminifyOptimizer([ 'api_key' => getenv('IMINIFY_API_KEY'), ])); $chain->optimize('photos/team.jpg'); ``` -------------------------------- ### Extend IminifyOptimizer to provide custom client Source: https://github.com/mozex/iminify-php/blob/main/docs/integrations/spatie.md Override the client() method to supply your own client instance, useful for testing or when the chain is queued. The default client comes from discovery and refuses clients without a settable timeout. This also keeps the api_key out of the job payload when serialized. ```php use Mozex\Iminify\Client; use Mozex\Iminify\Spatie\IminifyOptimizer; class MyOptimizer extends IminifyOptimizer { protected function client(): Client { return MyContainer::get(Client::class); } } ``` -------------------------------- ### List, get, and delete crawls Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/site-crawls.md Provides basic management operations for crawls: listing with pagination, fetching a single crawl by ID, and deleting a crawl. ```php $client->crawls()->list(['per_page' => 50]); $client->crawls()->get($id); $client->crawls()->delete($crawl); ``` -------------------------------- ### Fixtures::page() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for one page of a list. ```APIDOC ## Fixtures::page() ### Description Returns a fixture for one page of a list. ### Method page ### Parameters #### Arguments - **records** (array) - Required - The records for the page. ### Returns - **array** - The page record. ### Example ```php Fixtures::page([...]) ``` ``` -------------------------------- ### List, get, retry, cancel, and delete scans Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/page-scans.md Provides administrative operations on scans: listing with filters, fetching by ID, retrying, canceling, and deleting (which also deletes its images). ```php $client->scans()->list(['status' => 'completed', 'per_page' => 50]); $client->scans()->get($id); $client->scans()->retry($scan); $client->scans()->cancel($scan); $client->scans()->delete($scan); // its images with it ``` -------------------------------- ### Check Usage Limits with isSpent() and isUnlimited() Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/account.md Checks if the daily image usage is spent or unlimited. A null limit means unlimited, not zero, so use these methods instead of comparing numbers. ```php if ($account->usage->images->isSpent()) { // nothing left until resetsAt } $account->usage->images->isUnlimited(); ``` -------------------------------- ### FakeClient constructor Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Creates a fake client that stands in for the real client in tests. Queued responses are returned in order instead of calling the API. ```APIDOC ## FakeClient constructor ### Description Creates a fake client that stands in for the real client in tests. Queued responses are returned in order instead of calling the API. ### Method Constructor ### Parameters #### Constructor Arguments - **answers** (array) - Required - An array of queued responses: record arrays, `ApiResponse` instances, or exceptions. ### Example ```php use Mozex\Iminify\Testing\FakeClient; use Mozex\Iminify\Testing\Fixtures; $client = new FakeClient([ Fixtures::queuedImage(), Fixtures::image(['id' => 'abc', 'saved_percent' => 42.5]), Fixtures::file('the bytes'), ]); ``` ``` -------------------------------- ### Fixtures::newMonitor() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a new weekly check. ```APIDOC ## Fixtures::newMonitor() ### Description Returns a fixture for a new weekly check. ### Method newMonitor ### Returns - **array** - The new monitor record. ``` -------------------------------- ### Configure OptimizerChain with logger and rethrow Source: https://github.com/mozex/iminify-php/blob/main/docs/integrations/spatie.md Use this when you want the optimizer chain to log errors and rethrow them instead of silently failing. The chain catches exceptions by default and logs to an unset logger, leaving files unoptimized. Setting a logger and calling throws() makes failures visible. ```php use Mozex\Iminify\Spatie\IminifyOptimizer; use Spatie\ImageOptimizer\OptimizerChain; $chain = (new OptimizerChain) ->useLogger($logger) ->throws() ->addOptimizer(new IminifyOptimizer(['api_key' => $key])); ``` -------------------------------- ### Fixtures::queuedScan() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a page scan that was just sent. ```APIDOC ## Fixtures::queuedScan() ### Description Returns a fixture for a page scan that was just sent. ### Method queuedScan ### Returns - **array** - The queued scan record. ``` -------------------------------- ### Create an upload group with create() Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/upload-groups.md Opens a group by sending the API parameters. Every limit is checked before the file travels; a group past any limit is refused whole with nothing counted. The source must match the file exactly, and width/height must be as displayed, not as stored. ```php use Mozex\Iminify\Enums\CropAnchor; use Mozex\Iminify\Enums\GroupFormat; use Mozex\Iminify\Http\Upload; $upload = Upload::fromPath('photos/team.jpg'); $group = $client->groups()->create([ 'name' => 'team', 'source' => ['format' => 'jpg', 'size' => $upload->size(), 'width' => 2560, 'height' => 1707], 'outputs' => [ ['name' => 'full', 'width' => 2560, 'height' => 1707], ['name' => 'medium', 'width' => 300, 'height' => 200], ['name' => 'thumbnail', 'width' => 150, 'height' => 150, 'crop' => [CropAnchor::Center, CropAnchor::Center]], ], 'formats' => [GroupFormat::Original, GroupFormat::Webp], 'ephemeral' => true, ]); ``` -------------------------------- ### Fixtures::monitor() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a weekly check that has run. ```APIDOC ## Fixtures::monitor() ### Description Returns a fixture for a weekly check that has run. ### Method monitor ### Returns - **array** - The monitor record. ``` -------------------------------- ### downloadResponsive($image, $width) Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Downloads a single responsive image variant at the specified width. ```APIDOC ## downloadResponsive($image, $width) ### Description Downloads a single responsive image variant at the specified width. ### Method PHP method call ### Endpoint `$client->images()->downloadResponsive($image, $width)` ### Parameters - **$image** (Image) - Required - The image object. - **$width** (int) - Required - The desired width for the responsive variant. ### Response Returns a Download object similar to `download()`. ``` -------------------------------- ### Fixtures::scan() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a finished page scan. ```APIDOC ## Fixtures::scan() ### Description Returns a fixture for a finished page scan. ### Method scan ### Returns - **array** - The scan record. ``` -------------------------------- ### Fixtures::image() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a finished image record. ```APIDOC ## Fixtures::image() ### Description Returns a fixture for a finished image record. ### Method image ### Parameters #### Arguments - **overrides** (array) - Optional - Fields to replace in the fixture. ### Returns - **array** - The image record. ### Example ```php Fixtures::image(['id' => 'abc', 'saved_percent' => 42.5]) ``` ``` -------------------------------- ### Fixtures::maxAccount() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a Max account whose daily images, page scans and files read null. ```APIDOC ## Fixtures::maxAccount() ### Description Returns a fixture for a Max account whose daily images, page scans and files read null. ### Method maxAccount ### Returns - **array** - The Max account record. ``` -------------------------------- ### downloadResponsiveZip($image) Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Downloads all responsive variants of an image as a single ZIP archive. ```APIDOC ## downloadResponsiveZip($image) ### Description Downloads all responsive variants of an image as a single ZIP archive. ### Method PHP method call ### Endpoint `$client->images()->downloadResponsiveZip($image)` ### Parameters - **$image** (Image) - Required - The image object. ### Response Returns a Download object representing the ZIP archive. ``` -------------------------------- ### Handling Rate Limits Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/error-handling.md Demonstrates catching RateLimitedException and DailyLimitReachedException, and using retryAfter to wait before retrying. ```APIDOC ```php use Mozex\Iminify\Exceptions\DailyLimitReachedException; use Mozex\Iminify\Exceptions\RateLimitedException; try { $image = $client->images()->upload('photos/team.jpg'); } catch (RateLimitedException $exception) { sleep($exception->retryAfter ?? 5); $image = $client->images()->upload('photos/team.jpg'); } catch (DailyLimitReachedException $exception) { // Retry-After can be hours away, so tell someone rather than sleeping } ``` ``` -------------------------------- ### images()->upload('photos/team.jpg', ['priority' => Priority::Background]) Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Uploads an image with a background priority, suitable for bulk work that doesn't need immediate processing. ```APIDOC ## images()->upload('photos/team.jpg', ['priority' => Priority::Background]) ### Description Uploads an image with a background priority, suitable for bulk work that doesn't need immediate processing. ### Method POST ### Endpoint `$client->images()->upload($path, $options)` ### Parameters #### Path Parameters - **$path** (string) - Required - The file path to the image. #### Request Body - **priority** (enum) - Optional - The priority level, e.g., `Priority::Background`. ### Response Returns the uploaded image object. ``` -------------------------------- ### Queue answers and assert calls with FakeClient Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Use FakeClient to replace the real client in tests. Queue responses in the constructor; each call reads the next answer, refusals throw, and waiting never sleeps. Assert with assertSent, assertSentTimes, and assertNotSent; a '*' in a path matches one path part. Requires PHPUnit, which Pest or PHPUnit suites already have. ```php use Mozex\Iminify\Http\ApiRequest; use Mozex\Iminify\Testing\FakeClient; use Mozex\Iminify\Testing\Fixtures; $client = new FakeClient([ Fixtures::queuedImage(), Fixtures::image(['id' => 'abc', 'saved_percent' => 42.5]), Fixtures::file('the bytes'), ]); // the code under test, given $client $image = $client->images()->upload('photos/team.jpg', ['format' => 'webp']); $image = $client->images()->wait($image); $client->images()->download($image)->saveTo('photos/team.webp'); $client->assertSent('POST', 'images', fn (ApiRequest $request): bool => $request->fields['format'] === 'webp'); $client->assertSentTimes('GET', 'images/abc/download', 1); $client->assertNotSent('DELETE', 'images/*'); ``` -------------------------------- ### Fixtures::crawl() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a finished site crawl. ```APIDOC ## Fixtures::crawl() ### Description Returns a fixture for a finished site crawl. ### Method crawl ### Returns - **array** - The crawl record. ``` -------------------------------- ### Upload with background priority Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Use Priority::Background for work nobody is waiting on, such as processing a whole library. Background images run after every image sent without it and count against your limits the same way. ```php use Mozex\Iminify\Enums\Priority; $image = $client->images()->upload('photos/team.jpg', ['priority' => Priority::Background]); ``` -------------------------------- ### Fixtures::refusal() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a refusal, ending in the exception the real one would. ```APIDOC ## Fixtures::refusal() ### Description Returns a fixture for a refusal, ending in the exception the real one would. ### Method refusal ### Parameters #### Arguments - **code** (string) - Required - The refusal code. - **status** (int) - Required - The HTTP status code. ### Returns - **ApiResponse** - The refusal response. ### Example ```php Fixtures::refusal('daily_limit_reached', 429) ``` ``` -------------------------------- ### Usage Methods Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/account.md Methods on the Usage object to check if a limit is spent or unlimited. These are used to interpret usage data correctly, especially when limits are null (unlimited). ```APIDOC ## Usage Methods ### Description Methods on the Usage object to check if a limit is spent or unlimited. These are used to interpret usage data correctly, especially when limits are null (unlimited). ### Methods - **isSpent()** - Returns true if the usage limit is reached, false on unlimited plans. - **isUnlimited()** - Returns true if the usage is unlimited (remaining is null). ### Request Example ```php if ($account->usage->images->isSpent()) { // nothing left until resetsAt } $account->usage->images->isUnlimited(); ``` ``` -------------------------------- ### Fixtures::queuedImage() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for an image that was just sent. ```APIDOC ## Fixtures::queuedImage() ### Description Returns a fixture for an image that was just sent. ### Method queuedImage ### Returns - **array** - The queued image record. ### Example ```php Fixtures::queuedImage() ``` ``` -------------------------------- ### Fixtures::answer() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for any JSON response, for the limit headers or a status the others don't give. ```APIDOC ## Fixtures::answer() ### Description Returns a fixture for any JSON response, for the limit headers or a status the others don't give. ### Method answer ### Parameters #### Arguments - **body** (mixed) - Required - The response body. - **status** (int) - Required - The HTTP status code. - **headers** (array) - Optional - The response headers. ### Returns - **ApiResponse** - The JSON response. ``` -------------------------------- ### Fixtures::openGroup() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for an upload group waiting for its image. ```APIDOC ## Fixtures::openGroup() ### Description Returns a fixture for an upload group waiting for its image. ### Method openGroup ### Returns - **array** - The open group record. ``` -------------------------------- ### WebhookVerifier::sign() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Makes the header for a request to your own endpoint. ```APIDOC ## WebhookVerifier::sign() ### Description Makes the header for a request to your own endpoint. ### Method sign ### Returns - **string** - The signature header value. ``` -------------------------------- ### images()->share($image) Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Shares an image, making it accessible via a share URL. ```APIDOC ## images()->share($image) ### Description Shares an image, making it accessible via a share URL. ### Method POST ### Endpoint `$client->images()->share($image)` ### Parameters #### Path Parameters - **$image** (object) - Required - The image object to share. ### Response Returns the image object with a shareUrl property. ``` -------------------------------- ### FakeClient::addAnswers() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Adds more queued responses to the fake client after construction. Responses are returned in the order they were added. ```APIDOC ## FakeClient::addAnswers() ### Description Adds more queued responses to the fake client after construction. Responses are returned in the order they were added. ### Method addAnswers ### Parameters #### Arguments - **answers** (array) - Required - An array of queued responses: record arrays, `ApiResponse` instances, or exceptions. ### Notes - A call with nothing queued throws a `LogicException` naming the call. ``` -------------------------------- ### groups()->download() Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/upload-groups.md Downloads the group's outputs as a zip file. The zip holds every output marked 'replace', with a manifest.csv of every output. ```APIDOC ## groups()->download() ### Description Downloads the group's outputs as a zip file. The zip holds every output marked 'replace', with a manifest.csv of every output. ### Method download() ### Parameters - **group** - Required - The group object. ### Request Example ```php $client->groups()->download($group)->saveTo('photos/team.zip'); ``` ``` -------------------------------- ### Fixtures::noContent() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a delete's response. ```APIDOC ## Fixtures::noContent() ### Description Returns a fixture for a delete's response. ### Method noContent ### Returns - **ApiResponse** - The no-content response. ``` -------------------------------- ### FakeClient::assertNothingSent() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Asserts that no requests were sent to the fake client. ```APIDOC ## FakeClient::assertNothingSent() ### Description Asserts that no requests were sent to the fake client. ### Method assertNothingSent ### Returns - **void** ``` -------------------------------- ### Verify webhook signature and handle event Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/webhooks.md Handles an incoming Iminify webhook by verifying the signature with WebhookVerifier using the IMINIFY_WEBHOOK_SECRET environment variable. Pass the raw request body and the Iminify-Signature header; the verifier rejects requests older than five minutes (configurable via the second constructor argument in seconds). On failure, respond with HTTP 400; on success, check the event type and access the optimized image download URL. ```php use Mozex\Iminify\Enums\WebhookEventType; use Mozex\Iminify\Exceptions\InvalidWebhookSignatureException; use Mozex\Iminify\Webhooks\WebhookVerifier; $verifier = new WebhookVerifier(getenv('IMINIFY_WEBHOOK_SECRET')); try { $event = $verifier->verify(file_get_contents('php://input'), $_SERVER['HTTP_IMINIFY_SIGNATURE'] ?? null); } catch (InvalidWebhookSignatureException) { http_response_code(400); return; } if ($event->type === WebhookEventType::ImageCompleted) { echo $event->image()?->optimized?->downloadUrl; } ``` -------------------------------- ### Fixtures::queuedCrawl() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a site crawl that was just sent. ```APIDOC ## Fixtures::queuedCrawl() ### Description Returns a fixture for a site crawl that was just sent. ### Method queuedCrawl ### Returns - **array** - The queued crawl record. ``` -------------------------------- ### Upload image with options Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Pass options directly to the API's `POST /images` endpoint. Enums are sent as their values, null as nothing. Options include `level`, `format`, `width`, and `alt_text`. ```php use Mozex\Iminify\Enums\CompressionLevel; use Mozex\Iminify\Enums\OutputFormat; $image = $client->images()->upload('photos/team.jpg', [ 'level' => CompressionLevel::Ultra, 'format' => OutputFormat::Webp, 'width' => 1600, 'alt_text' => false, ]); ``` -------------------------------- ### Catching ApiException Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/error-handling.md Shows how to catch an ApiException and access its properties, including status, error code, message, errors, and retryAfter. ```APIDOC ```php use Mozex\Iminify\Exceptions\ApiException; try { $image = $client->images()->upload('photos/team.jpg', ['size_limit' => 1]); } catch (ApiException $exception) { $exception->status; // 422 $exception->errorCode; // validation_failed $exception->getMessage(); // words meant for a person $exception->errors; // on a validation failure, each field's messages $exception->retryAfter; // the response's Retry-After, in seconds } ``` ``` -------------------------------- ### fromUrl Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Uploads an image from a public URL for compression. This is a convenience method that fetches the image from the given address. ```APIDOC ## fromUrl ### Description Uploads an image from a public URL for compression. This is a convenience method that fetches the image from the given address. ### Method POST ### Endpoint /images ### Request Example ```php $image = $client->images()->fromUrl('https://example.com/team.jpg'); ``` ``` -------------------------------- ### Fixtures::groupInProgress() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for an upload group being made. ```APIDOC ## Fixtures::groupInProgress() ### Description Returns a fixture for an upload group being made. ### Method groupInProgress ### Returns - **array** - The in-progress group record. ``` -------------------------------- ### Paginate through image list with nextPage Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Lists images one page at a time. Loop over the page's records and continue while `$nextPage` is not null. `list()` also accepts `source` and `scan` parameters. The page exposes `$items`, `$total`, `$perPage`, `$currentPage`, and `$lastPage`; `toArray()` returns the response as sent. ```php $page = 1; do { $images = $client->images()->list(['status' => 'failed', 'per_page' => 50, 'page' => $page]); foreach ($images as $image) { echo "{$image->name}\n"; } $page = $images->nextPage; } while ($page !== null); ``` -------------------------------- ### images()->download($image)->saveTo('photos/team.jpg') Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Downloads the processed image and saves it to a local file path. ```APIDOC ## images()->download($image)->saveTo('photos/team.jpg') ### Description Downloads the processed image and saves it to a local file path. ### Method GET ### Endpoint `$client->images()->download($image)->saveTo($path)` ### Parameters #### Path Parameters - **$image** (object) - Required - The image object to download. - **$path** (string) - Required - The local file path to save the image to. ### Response Saves the image file to the specified path. ``` -------------------------------- ### FakeClient::requests() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns every call sent to the fake client, oldest first. ```APIDOC ## FakeClient::requests() ### Description Returns every call sent to the fake client, oldest first. ### Method requests ### Returns - **array** - A list of all sent requests. ``` -------------------------------- ### Accessing Rate Limit Headers Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/error-handling.md Shows how to access rate limit information from a record or list page response. ```APIDOC ```php $image->rateLimit->limit; $image->rateLimit->remaining; ``` ``` -------------------------------- ### Fixtures::group() Source: https://github.com/mozex/iminify-php/blob/main/docs/reference/testing.md Returns a fixture for a finished upload group. ```APIDOC ## Fixtures::group() ### Description Returns a fixture for a finished upload group. ### Method group ### Returns - **array** - The group record. ``` -------------------------------- ### downloadMany($images) Source: https://github.com/mozex/iminify-php/blob/main/docs/usage/images.md Downloads the optimized copies of multiple images as a single ZIP archive. ```APIDOC ## downloadMany($images) ### Description Downloads the optimized copies of multiple images as a single ZIP archive. ### Method PHP method call ### Endpoint `$client->images()->downloadMany($images)` ### Parameters - **$images** (array) - Required - An array of image objects. ### Response Returns a Download object representing the ZIP archive. ```