fix: validate battlefield reachability inputs

This commit is contained in:
Keith Solomon
2026-07-04 15:15:08 -05:00
parent 189be5bc64
commit b789f1b61f
2 changed files with 88 additions and 10 deletions
+33 -4
View File
@@ -9,29 +9,46 @@ use SplQueue;
final readonly class Battlefield
{
/** @var array<string, Terrain> */
private array $terrain;
/**
* @param array<string, Terrain> $terrain
* @param array<array-key, mixed> $terrain
*/
public function __construct(
public int $width,
public int $height,
private array $terrain = [],
array $terrain = [],
) {
if ($width < 8 || $width > 16 || $height < 8 || $height > 16) {
throw new InvalidArgumentException('Battlefield dimensions must each be between 8 and 16.');
}
foreach (array_keys($terrain) as $key) {
if (preg_match('/^(\d+):(\d+)$/', $key, $matches) !== 1) {
$validatedTerrain = [];
foreach ($terrain as $key => $terrainType) {
if (!$terrainType instanceof Terrain) {
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}.");
}
if (!$this->contains($position)) {
throw new InvalidArgumentException("Terrain coordinate {$key} is outside the battlefield.");
}
$validatedTerrain[$key] = $terrainType;
}
$this->terrain = $validatedTerrain;
}
public function contains(Position $position): bool
@@ -53,9 +70,21 @@ final readonly class Battlefield
*/
public function reachable(Position $start, int $budget, array $occupied): array
{
if (!$this->contains($start)) {
throw new InvalidArgumentException('Reachability start position is outside the battlefield.');
}
if ($budget < 0) {
throw new InvalidArgumentException('Reachability budget cannot be negative.');
}
$occupiedKeys = [];
foreach ($occupied as $position) {
if (!$this->contains($position)) {
throw new InvalidArgumentException('Occupied position is outside the battlefield.');
}
$occupiedKeys[$position->key()] = true;
}