Skip to content

Instantly share code, notes, and snippets.

@reinink
Created July 8, 2022 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reinink/0e319d10e12ce38d67913788a4e1ec31 to your computer and use it in GitHub Desktop.
Save reinink/0e319d10e12ce38d67913788a4e1ec31 to your computer and use it in GitHub Desktop.
<?php
TestResponse::macro('inertiaSnapshot', function (...$keys) {
$convertPlainValueToCode = function ($value) {
if ($value === null) {
return 'null';
} elseif (is_bool($value)) {
return $value ? 'true' : 'false';
} elseif (is_string($value)) {
return "'".addslashes($value)."'";
} else {
return $value;
}
};
$convertValueToCode = function ($value, $key = null, $depth = 0) use (&$convertValueToCode, $convertPlainValueToCode) {
$indent = str_repeat(' ', $depth * 4);
if (is_array($value)) {
if (count($value) === 0 || (! is_array(array_values($value)[0]) && array_keys($value)[0] === 0)) {
$code = $indent."->where('$key', [";
$code .= collect($value)->map(fn ($value) => $convertPlainValueToCode($value))->implode(', ');
$code .= "])\n";
return $code;
}
$code = collect($value)->map(fn ($value, $key) => $convertValueToCode($value, $key, $depth + 1))->join('');
if ($key !== null) {
$wrappedKey = is_string($key) ? "'$key'" : $key;
$wrapped = $indent."->has($wrappedKey, fn (\$prop) => \$prop\n";
$wrapped .= $code;
$wrapped .= $indent.")\n";
return $wrapped;
}
return $code;
} else {
return $indent."->where('$key', ".$convertPlainValueToCode($value).")\n";
}
};
$testFilePath = collect(debug_backtrace())
->filter(fn ($item) => Str::endsWith($item['file'], 'Test.php'))
->pluck('file')
->first();
$contents = file_get_contents($testFilePath);
$line = collect(explode("\n", $contents))->filter(fn ($line) => str_contains($line, 'inertiaSnapshot'))->first();
$indentation = (strlen($line) - strlen(ltrim($line))) / 4;
$assertion = "assertInertia(fn (\$page) => \$page\n";
$assertion .= str_repeat(' ', ($indentation + 1) * 4)."->component('".$this->viewData('page')['component']."')\n";
$assertion .= $convertValueToCode(collect($this->viewData('page')['props'])->only($keys)->toArray(), null, $indentation);
$assertion .= str_repeat(' ', $indentation * 4).')';
file_put_contents($testFilePath, preg_replace('/inertiaSnapshot\(.+\)/i', $assertion, $contents));
dd('Snapshot updated, please run test again.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment