Created
May 22, 2023 11:23
-
-
Save filippotoso/82b3f4992eade2cf79c152e7361c73b0 to your computer and use it in GitHub Desktop.
[Laravel] Http::fakeRequest() macro to easily fake POST/PATH/DELETE requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Support\Facades\Http; | |
use Illuminate\Http\Client\Request; | |
use Illuminate\Support\Arr; | |
Http::macro('fakeRequest', function ($method, $url, $payload = [], $response = null) { | |
Http::fake(function (Request $request) use ($method, $url, $payload, $response) { | |
if ($request->url() != $url) { | |
return; | |
} | |
if (strtoupper($request->method()) != strtoupper(trim($method))) { | |
return; | |
} | |
$match = collect(Arr::dot($payload)) | |
->reduce(function ($carry, $value, $dot) use ($request) { | |
return $carry && (Arr::get($request->data(), $dot) == $value); | |
}, true); | |
if ($match) { | |
return is_array($response) ? Http::response($response) : $response; | |
} | |
}); | |
}); | |
// Usage | |
Http::fakeRequest('post', 'https://www.example.com', ['test' => 1], ['done' => 1]); | |
dump(Http::post('https://www.example.com', ['test' => 1])->json()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment