Skip to content

Instantly share code, notes, and snippets.

@azehintense
Forked from oleg-andreyev/WithConsecutive.php
Last active November 17, 2023 16:40
Show Gist options
  • Save azehintense/d2fbe8239757ad920f4314f1ad5e651b to your computer and use it in GitHub Desktop.
Save azehintense/d2fbe8239757ad920f4314f1ad5e651b to your computer and use it in GitHub Desktop.
<?php
/** Author: oleg-andreyev
* https://gist.github.com/oleg-andreyev/85c74dbf022237b03825c7e9f4439303
* had to fork this because my composer integration can't work with uppercase letters
**/
/**
Usage: ->with(...WithConsecutive::create(...$withCodes))
*/
declare(strict_types=1);
namespace App\Tests;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\IsEqual;
use RuntimeException;
class WithConsecutive
{
/**
* @param array<mixed> $parameterGroups
*
* @return array<int, Callback<mixed>>
*/
public static function create(...$parameterGroups): array
{
$result = [];
$parametersCount = null;
$groups = [];
$values = [];
foreach ($parameterGroups as $index => $parameters) {
// initial
$parametersCount ??= count($parameters);
// compare
if ($parametersCount !== count($parameters)) {
throw new RuntimeException('Parameters count max much in all groups');
}
// prepare parameters
foreach ($parameters as $parameter) {
if (!$parameter instanceof Constraint) {
$parameter = new IsEqual($parameter);
}
$groups[$index][] = $parameter;
}
}
// collect values
foreach ($groups as $parameters) {
foreach ($parameters as $index => $parameter) {
$values[$index][] = $parameter;
}
}
// build callback
for ($index = 0; $index < $parametersCount; ++$index) {
$result[$index] = Assert::callback(static function ($value) use ($values, $index) {
static $map = null;
$map ??= $values[$index];
$expectedArg = array_shift($map);
if ($expectedArg === null) {
throw new RuntimeException('No more expected calls');
}
$expectedArg->evaluate($value);
return true;
});
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment