test: strengthen battlefield boundary coverage
This commit is contained in:
+23
-11
@@ -13,7 +13,7 @@ final readonly class Battlefield
|
||||
private array $terrain;
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $terrain
|
||||
* @param array<string, Terrain> $terrain
|
||||
*/
|
||||
public function __construct(
|
||||
public int $width,
|
||||
@@ -27,19 +27,11 @@ final readonly class Battlefield
|
||||
$validatedTerrain = [];
|
||||
|
||||
foreach ($terrain as $key => $terrainType) {
|
||||
if (!$terrainType instanceof Terrain) {
|
||||
if (!self::isTerrain($terrainType)) {
|
||||
throw new InvalidArgumentException("Invalid terrain value at coordinate {$key}.");
|
||||
}
|
||||
|
||||
if (!is_string($key) || preg_match('/^(\d+):(\d+)$/', $key, $matches) !== 1) {
|
||||
throw new InvalidArgumentException("Invalid terrain coordinate: {$key}.");
|
||||
}
|
||||
|
||||
$position = new Position((int) $matches[1], (int) $matches[2]);
|
||||
|
||||
if ($key !== $position->key()) {
|
||||
throw new InvalidArgumentException("Invalid terrain coordinate: {$key}.");
|
||||
}
|
||||
$position = self::positionFromTerrainKey($key);
|
||||
|
||||
if (!$this->contains($position)) {
|
||||
throw new InvalidArgumentException("Terrain coordinate {$key} is outside the battlefield.");
|
||||
@@ -51,6 +43,26 @@ final readonly class Battlefield
|
||||
$this->terrain = $validatedTerrain;
|
||||
}
|
||||
|
||||
private static function isTerrain(mixed $terrain): bool
|
||||
{
|
||||
return $terrain instanceof Terrain;
|
||||
}
|
||||
|
||||
private static function positionFromTerrainKey(mixed $key): Position
|
||||
{
|
||||
if (!is_string($key) || preg_match('/^(\d+):(\d+)$/', $key, $matches) !== 1) {
|
||||
throw new InvalidArgumentException("Invalid terrain coordinate: {$key}.");
|
||||
}
|
||||
|
||||
$position = new Position((int) $matches[1], (int) $matches[2]);
|
||||
|
||||
if ($key !== $position->key()) {
|
||||
throw new InvalidArgumentException("Invalid terrain coordinate: {$key}.");
|
||||
}
|
||||
|
||||
return $position;
|
||||
}
|
||||
|
||||
public function contains(Position $position): bool
|
||||
{
|
||||
return $position->x >= 0
|
||||
|
||||
Reference in New Issue
Block a user