/** * @param string $string * * @return Grid * * @throws \Exception */ public static function fromString($string) { $letters = str_split($string, count(static::numbers())); $grid = new self(); foreach ($letters as $y => $letter) { $numbers = str_split($letter); foreach ($numbers as $x => $number) { $number = (int) $number; if ($number === 0) { continue; } $ship = ShipFactory::build($number); $direction = isset($numbers[$x + 1]) && $numbers[$x + 1] === $numbers[$x] ? Position::fromHorizontal() : Position::fromVertical(); try { $grid = $grid->placeShip($ship, new Hole(Hole::numberToLetter($y + 1), $x + 1), $direction); } catch (\Exception $e) { } } } if (!$grid->areAllShipsPlaced()) { throw new \InvalidArgumentException('Invalid format: All ships are not placed'); } if ($string !== $grid->render()) { throw new \InvalidArgumentException('Invalid format'); } return $grid; }