### PHP Client: Basic Expectation Source: https://context7.com/mcustiel/phiremock/llms.txt Use the Phiremock PHP client to programmatically define expectations. This example sets up a client connection and creates an expectation for GET /api/users with specific headers and body. ```php reset(); // Create an expectation for GET /api/users $phiremock->createExpectation( A::getRequest() ->andUrl(Is::equalTo('/api/users')) ->andHeader('Accept', Is::equalTo('application/json')), Respond::withStatusCode(200) ->andHeader('Content-Type', 'application/json') ->andBody('[{{\"id\": 1, \"name\": \"John Doe\"}}]') ); ``` -------------------------------- ### Install Phiremock via Composer CLI Source: https://context7.com/mcustiel/phiremock/llms.txt Install Phiremock and Guzzle using the Composer command-line interface. ```bash composer require --dev mcustiel/phiremock:v2.0 guzzlehttp/guzzle:^6.0 ``` -------------------------------- ### Start Server with Expectations Directory Source: https://context7.com/mcustiel/phiremock/llms.txt Launch the Phiremock server and specify a directory containing JSON files from which to load expectations. This is useful for managing expectations externally. ```bash ./vendor/bin/phiremock -e ./expectations ``` -------------------------------- ### Start Phiremock Server Source: https://context7.com/mcustiel/phiremock/llms.txt Launch the Phiremock server to listen for mock configurations and incoming requests. Options include specifying a port, expectations directory, or enabling debug logging. ```bash ./vendor/bin/phiremock ``` ```bash ./vendor/bin/phiremock -p 8080 ``` ```bash ./vendor/bin/phiremock -e /path/to/expectations ``` ```bash ./vendor/bin/phiremock -d ``` -------------------------------- ### Install Phiremock via Composer Source: https://github.com/mcustiel/phiremock/blob/master/README.md Add the Phiremock bundle and Guzzle as development dependencies in your composer.json file. ```json "require-dev": { "mcustiel/phiremock": "v2.0", "guzzlehttp/guzzle": "^6.0" } ``` -------------------------------- ### Simulate Network Latency via REST API Source: https://context7.com/mcustiel/phiremock/llms.txt Configure an expectation for a GET request to /api/slow-endpoint that includes a 3-second delay in the response. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": {"isEqualTo": "/api/slow-endpoint"} }, "response": { "statusCode": 200, "body": "{"status": "completed"}", "delayMillis": 3000 } }' ``` -------------------------------- ### Load Expectations from JSON File Source: https://context7.com/mcustiel/phiremock/llms.txt Define expectations in a JSON file for automatic loading when the Phiremock server starts. This allows for persistent and organized expectation management. ```json // expectations/get-users.json { "request": { "method": "GET", "url": { "isEqualTo": "/api/users" } }, "response": { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": "[{{\"id\": 1, \"name\": \"John\"}, {\"id\": 2, \"name\": \"Jane\"}}]" } } ``` -------------------------------- ### Create Basic Expectation via REST API Source: https://context7.com/mcustiel/phiremock/llms.txt Use curl to create a basic expectation that matches a GET request to /api/users and returns a 200 status code with JSON content. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": { "isEqualTo": "/api/users" } }, "response": { "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": "[{"id": 1, "name": "John Doe"}]" } }' ``` -------------------------------- ### Match Specific Header via REST API Source: https://context7.com/mcustiel/phiremock/llms.txt Create an expectation that matches a GET request to /api/protected only if it includes a specific Authorization header. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": {"isEqualTo": "/api/protected"}, "headers": { "Authorization": { "isEqualTo": "Bearer valid-token" } } }, "response": { "statusCode": 200, "body": "{"data": "protected content"}" } }' ``` -------------------------------- ### Match Header with Regex via REST API Source: https://context7.com/mcustiel/phiremock/llms.txt Create an expectation for a GET request to /api/data that matches the Accept header using a regular expression to allow either 'application/json' or 'application/xml'. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": {"isEqualTo": "/api/data"}, "headers": { "Accept": { "matches": "application/(json|xml)" } } }, "response": { "statusCode": 200, "body": "{"result": "ok"}" } }' ``` -------------------------------- ### Match URL with Regex via REST API Source: https://context7.com/mcustiel/phiremock/llms.txt Create an expectation that matches GET requests to URLs following the pattern /api/users/[digits] using a regular expression. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": { "matches": "/api/users/[0-9]+" } }, "response": { "statusCode": 200, "body": "{"id": 123, "name": "Test User"}" } }' ``` -------------------------------- ### Create Catch-All Expectation (Low Priority) Source: https://context7.com/mcustiel/phiremock/llms.txt Use this to define a default response for requests that do not match any specific expectations. Set a lower priority number for lower precedence. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": {"matches": "/api/.*"} }, "response": { "statusCode": 404, "body": "{\"error\": \"Not found\"}" }, "priority": 10 }' ``` -------------------------------- ### Integrate Phiremock with Codeception Source: https://context7.com/mcustiel/phiremock/llms.txt Configure the Phiremock extension and module in Codeception to enable mock server control during acceptance tests. ```yaml # codeception.yml extensions: enabled: - Mcustiel\Phiremock\Codeception\Extension: listen: 127.0.0.1:8086 expectationsPath: tests/_expectations modules: enabled: - Mcustiel\Phiremock\Codeception\Module ``` ```php expectARequestToRemoteServiceWithAResponse( \Mcustiel\Phiremock\Client\Utils\A::getRequest() ->andUrl(\Mcustiel\Phiremock\Client\Utils\Is::equalTo('/api/users')), \Mcustiel\Phiremock\Client\Utils\Respond::withStatusCode(200) ->andBody('[{"id": 1, "name": "Test User"}]') ); $I->sendGet('/users'); $I->seeResponseCodeIs(200); $I->seeResponseContains('Test User'); } } ``` -------------------------------- ### Configure Stateful Mock Scenarios Source: https://context7.com/mcustiel/phiremock/llms.txt Define stateful behavior by sending JSON payloads to the Phiremock expectations endpoint, allowing transitions between scenario states. ```bash # Initial state: return empty cart curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "scenarioName": "shopping-cart", "scenarioStateIs": "Started", "request": { "method": "GET", "url": {"isEqualTo": "/api/cart"} }, "response": { "statusCode": 200, "body": "{\"items\": []}" } }' # When item is added, transition to "HasItems" state curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "scenarioName": "shopping-cart", "scenarioStateIs": "Started", "newScenarioState": "HasItems", "request": { "method": "POST", "url": {"isEqualTo": "/api/cart/items"} }, "response": { "statusCode": 201, "body": "{\"added\": true}" } }' # After adding item: return cart with items curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "scenarioName": "shopping-cart", "scenarioStateIs": "HasItems", "request": { "method": "GET", "url": {"isEqualTo": "/api/cart"} }, "response": { "statusCode": 200, "body": "{\"items\": [{\"id\": 1, \"name\": \"Product\", \"qty\": 1}]}" } }' ``` -------------------------------- ### Reset All Expectations Source: https://context7.com/mcustiel/phiremock/llms.txt Clears all configured expectations. Use this to ensure a clean state before running new test suites. ```bash curl -X DELETE http://localhost:8086/__phiremock/expectations ``` -------------------------------- ### Create Specific Expectation (High Priority) Source: https://context7.com/mcustiel/phiremock/llms.txt Define a precise response for a specific URL. A lower priority number indicates higher precedence, ensuring this expectation is matched before lower-priority ones. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": {"isEqualTo": "/api/users"} }, "response": { "statusCode": 200, "body": "[{{\"id\": 1}}]" }, "priority": 1 }' ``` -------------------------------- ### Reset Everything Source: https://context7.com/mcustiel/phiremock/llms.txt Clears both all configured expectations and all recorded request history. This provides a complete reset of the Phiremock server state. ```bash curl -X DELETE http://localhost:8086/__phiremock/reset ``` -------------------------------- ### PHP Client: POST Expectation with Body Matching Source: https://context7.com/mcustiel/phiremock/llms.txt Create an expectation for a POST request that matches a specific URL and contains certain text within the request body. This is useful for verifying data sent in the request. ```php $phiremock->createExpectation( A::postRequest() ->andUrl(Is::equalTo('/api/users')) ->andBody(Is::containing('"email":')), Respond::withStatusCode(201) ->andBody('{{\"id\": 2, \"created\": true}}') ); ``` -------------------------------- ### Verify HTTP Requests in PHPUnit Source: https://context7.com/mcustiel/phiremock/llms.txt Use the Phiremock client to define expectations and verify request execution counts within PHPUnit test cases. ```php phiremock = new Phiremock('localhost', 8086); $this->phiremock->reset(); } public function testUserServiceCallsApi(): void { // Setup expectation $this->phiremock->createExpectation( A::getRequest()->andUrl(Is::equalTo('/api/users')), Respond::withStatusCode(200)->andBody('[]') ); // Execute your code that should make the HTTP request $userService = new UserService('http://localhost:8086'); $userService->fetchUsers(); // Verify the request was made exactly once $count = $this->phiremock->countExecutions( A::getRequest()->andUrl(Is::equalTo('/api/users')) ); $this->assertEquals(1, $count); } public function testUserServiceCallsApiMultipleTimes(): void { $this->phiremock->createExpectation( A::getRequest()->andUrl(Is::matching('/api/users/[0-9]+')), Respond::withStatusCode(200)->andBody('{"id": 1}') ); $userService = new UserService('http://localhost:8086'); $userService->fetchUser(1); $userService->fetchUser(2); $userService->fetchUser(3); // Verify at least 3 requests were made matching the pattern $count = $this->phiremock->countExecutions( A::getRequest()->andUrl(Is::matching('/api/users/[0-9]+')) ); $this->assertGreaterThanOrEqual(3, $count); } protected function tearDown(): void { $this->phiremock->reset(); } } ``` -------------------------------- ### Proxy Requests to Real Backend Source: https://context7.com/mcustiel/phiremock/llms.txt Configure Phiremock to forward requests matching a pattern to a specified external URL. This allows for recording or modifying requests to a live service. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": {"matches": "/api/external/.*"} }, "proxyTo": "https://api.example.com" }' ``` -------------------------------- ### Match Request Body with Regex via REST API Source: https://context7.com/mcustiel/phiremock/llms.txt Create an expectation for a POST request to /api/login where the request body contains a username pattern matched by a regular expression. ```bash curl -X POST http://localhost:8086/__phiremock/expectations \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "POST", "url": {"isEqualTo": "/api/login"}, "body": { "matches": ".*"username":"[a-z]+".*" } }, "response": { "statusCode": 200, "body": "{"token": "abc123"}" } }' ``` -------------------------------- ### PHP Client: Regex URL Matching Source: https://context7.com/mcustiel/phiremock/llms.txt Define an expectation that matches a URL pattern using regular expressions. This is useful for handling dynamic URL segments. ```php $phiremock->createExpectation( A::getRequest() ->andUrl(Is::matching('/api/users/[0-9]+')), Respond::withStatusCode(200) ->andBody('{{\"id\": 1, \"name\": \"User\"}}') ); ``` -------------------------------- ### PHP Client: Add Delay to Response Source: https://context7.com/mcustiel/phiremock/llms.txt Simulate network latency by adding a delay to the response. This is useful for testing how your application handles slow API responses. ```php $phiremock->createExpectation( A::getRequest()->andUrl(Is::equalTo('/api/slow')), Respond::withStatusCode(200) ->andBody('{{\"status\": \"done\"}}') ->andDelayInMillis(2000) ); ``` -------------------------------- ### Verify Request Count Source: https://context7.com/mcustiel/phiremock/llms.txt Check how many times a specific request has been made. This is useful for verifying that certain API calls were executed during tests. ```bash curl -X POST http://localhost:8086/__phiremock/executions \ -H "Content-Type: application/json" \ -d '{ "request": { "method": "GET", "url": {"isEqualTo": "/api/users"} } }' ``` -------------------------------- ### Reset Execution History Source: https://context7.com/mcustiel/phiremock/llms.txt Clears all recorded request counts. This is useful for resetting the verification counts between test runs. ```bash curl -X DELETE http://localhost:8086/__phiremock/executions ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.