Skip to content

Instantly share code, notes, and snippets.

@inxilpro
Created November 10, 2023 18:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inxilpro/93b127822026d0698ee25e96a557b6f0 to your computer and use it in GitHub Desktop.
Save inxilpro/93b127822026d0698ee25e96a557b6f0 to your computer and use it in GitHub Desktop.
<?php
use Stripe\ApiRequestor;
use Stripe\HttpClient\ClientInterface;
use Stripe\HttpClient\CurlClient;
use Stripe\Stripe;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
trait TestsWithStripeMock
{
protected static int $stripe_mock_http_port = 12111;
protected static int $stripe_mock_https_port = 12112;
protected static ?string $stripe_mock_original_api_base = null;
protected static ?Process $stripe_mock_process = null;
/** @beforeClass */
public static function setUpStripeMock(): void
{
static::$stripe_mock_process ??= static::startStripeMock();
static::$stripe_mock_original_api_base = Stripe::$apiBase;
Stripe::$apiBase = 'http://127.0.0.1:'.static::$stripe_mock_http_port;
}
/** @afterClass */
public static function tearDownStripeMock(): void
{
if (static::$stripe_mock_process && static::$stripe_mock_process->isRunning()) {
static::$stripe_mock_process->stop();
}
if (static::$stripe_mock_original_api_base) {
Stripe::$apiBase = static::$stripe_mock_original_api_base;
static::$stripe_mock_original_api_base = null;
}
}
protected static function startStripeMock(): Process
{
$process = new Process([
static::findStripeMockExecutable(),
'-http-port',
static::$stripe_mock_http_port,
'-https-port',
static::$stripe_mock_https_port,
]);
$process->disableOutput();
$process->start();
return $process;
}
protected static function findStripeMockExecutable(): ?string
{
$finder = new ExecutableFinder();
return $finder->find('stripe-mock', '/usr/local/bin/stripe-mock');
}
protected function spyOnStripeMockResponses(): static
{
ApiRequestor::setHttpClient(new class() implements ClientInterface {
public function request($method, $absUrl, $headers, $params, $hasFile)
{
$response = CurlClient::instance()->request($method, $absUrl, $headers, $params, $hasFile);
echo "<-- [{$absUrl}] \n";
dump($response[0]);
return $response;
}
});
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment