Created
October 20, 2020 07:46
-
-
Save BurningDog/6bc62def035de5021cf4781ef4891b70 to your computer and use it in GitHub Desktop.
Mocking an API in php
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 | |
namespace App\Tests\Mocks; | |
use Exception; | |
class ApiMocks | |
{ | |
protected static $mockResponses = []; | |
/** | |
* Mocks an API call with a JSON response, converted to a PHP array/object. | |
* | |
* @param string $apiUrl | |
* @param string $json | |
* @param bool $persist If true, then always serve a response for this call, otherwise remove | |
* it from the responses after a single serving | |
*/ | |
public static function mockApi($apiUrl, $json, $persist = false) | |
{ | |
$response = json_decode($json, true); | |
self::$mockResponses[$apiUrl][] = [ | |
'response' => $response, | |
'persist' => $persist, | |
]; | |
} | |
public static function resetMocks() | |
{ | |
self::$mockResponses = []; | |
} | |
/** | |
* Returns a mocked API call. | |
* | |
* @return mixed | |
* | |
* @throws Exception | |
*/ | |
public static function getMockApi(string $apiUrl, array $messageData = []): array | |
{ | |
if (array_key_exists($apiUrl, self::$mockResponses) && count(self::$mockResponses[$apiUrl]) > 0) { | |
$mockedResponse = self::$mockResponses[$apiUrl][0]; | |
$response = $mockedResponse['response']; | |
// remove the response from the mocks | |
if (!$mockedResponse['persist']) { | |
array_shift(self::$mockResponses[$apiUrl]); | |
if (0 === count(self::$mockResponses[$apiUrl])) { | |
unset(self::$mockResponses[$apiUrl]); | |
} | |
} | |
return $response; | |
} | |
throw new ApiMockNotFoundException($apiUrl, $messageData); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment