Last active
          July 11, 2022 21:25 
        
      - 
      
 - 
        
Save Sammyjo20/56928414d4d512f8c3d84bcf097c312d to your computer and use it in GitHub Desktop.  
    Record a Saloon Response to create a fixture
  
        
  
    
      This file contains hidden or 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 | |
| /** | |
| * Record a request and respond with a fixture. | |
| * | |
| * @throws \Sammyjo20\Saloon\Exceptions\SaloonInvalidMockResponseCaptureMethodException | |
| * @throws ReflectionException | |
| * @throws \GuzzleHttp\Exception\GuzzleException | |
| * @throws \Sammyjo20\Saloon\Exceptions\SaloonException | |
| * @throws JsonException | |
| */ | |
| function recordSend(TMDB $sdk, SaloonRequest $request, string $customKey = null): SaloonResponse | |
| { | |
| $fixtureName = $customKey ?? (new ReflectionClass($request))->getShortName(); | |
| $path = __DIR__ . '/Fixtures/' . $fixtureName . '.json'; | |
| try { | |
| $fixture = file_get_contents($path); | |
| } catch (Throwable $ex) { | |
| $fixture = null; | |
| } | |
| // If we have found a fixture, we will attempt to decode it and convert it into a MockResponse. | |
| if (isset($fixture)) { | |
| $fixture = json_decode($fixture, true, 512, JSON_THROW_ON_ERROR); | |
| $mockResponse = unserialize($fixture['mockResponse'], ['allowed_classes' => [MockResponse::class]]); | |
| $mockClient = new MockClient([$mockResponse]); | |
| return $sdk->send($request, $mockClient); | |
| } | |
| // However if the fixture does not exist, we will register a response interceptor which will | |
| // store the fixture if the request is successful, ready for the next request. | |
| $sdk->addResponseInterceptor(function (SaloonRequest $request, TMDBResponse $response) use ($path) { | |
| if ($response->failed()) { | |
| return $response; | |
| } | |
| $mockResponse = new MockResponse($response->body(), $response->status(), $response->headers()); | |
| $data = ['mockResponse' => serialize($mockResponse)]; | |
| file_put_contents($path, json_encode($data)); | |
| return $response; | |
| }); | |
| return $sdk->send($request); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Update: I allow you to pass in a third argument as a custom key, so if you have a test that does something different with a specific request name, you can customise the key here.