Skip to content

Instantly share code, notes, and snippets.

@ilario-pierbattista
Created December 12, 2024 21:05
Show Gist options
  • Save ilario-pierbattista/3fdd4589752a11c6ce00a80d535c3668 to your computer and use it in GitHub Desktop.
Save ilario-pierbattista/3fdd4589752a11c6ce00a80d535c3668 to your computer and use it in GitHub Desktop.
<?php declare(strict_types=1);
use Eris\Generator;
use Eris\Generators;
use Eris\TestTrait;
use PHPUnit\Framework\TestCase;
class ErisMultiDimExampleTest extends TestCase
{
use TestTrait;
public function test()
{
$this->forAll(
Generators::bind(
Generators::associative(
[
'rows' => Generators::choose(2, 10),
'columns' => Generators::choose(2, 10),
]
),
function ($spec) {
['rows' => $rows, 'columns' => $columns] = $spec;
return Generators::vector(
$rows,
Generators::vector(
$columns,
Generators::oneOf(Generators::float(), Generators::int())
)
);
}
)
)->then(function ($in) {
self::assertDimensionConsistency($in);
});
}
public function test_multidimensional()
{
$this
->forAll(
Generators::bind(
Generators::bind(
Generators::choose(2, 6), // from 2 to 6 dimension
fn(int $maxDim) => Generators::vector($maxDim, Generators::choose(2, 10)) // sizes from 2 to 10
),
function (array $dimensions) {
return self::generateMultiDimMatrix(
$dimensions,
Generators::oneOf(Generators::float(), Generators::int())
);
}
)
)
->then(function ($m) {
self::assertDimensionConsistency($m);
});
}
private static function generateMultiDimMatrix(array $sizes, Generator $valuesGenerator): Generator
{
$head = array_shift($sizes);
if(count($sizes) > 0) {
return Generators::vector(
$head,
self::generateMultiDimMatrix($sizes, $valuesGenerator)
);
}
return Generators::vector($head, $valuesGenerator);
}
private static function assertDimensionConsistency(array $m)
{
$firstRowLen = count($m[0]);
foreach ($m as $item) {
self::assertIsArray($item);
self::assertCount($firstRowLen, $item);
if(is_array($item[0])) {
self::assertDimensionConsistency($item);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment