Skip to content

Commit

Permalink
Fix wiring of object manager. Move maps asset path to env var. Write …
Browse files Browse the repository at this point in the history
…first integration test. Add phpunit.xml.dist so tests can execute.
  • Loading branch information
johnvandeweghe committed Oct 1, 2018
1 parent 099aed3 commit dd40988
Show file tree
Hide file tree
Showing 12 changed files with 123 additions and 69 deletions.
6 changes: 5 additions & 1 deletion .env.dist
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ APP_SECRET=eb106562e67ed9f80b2c2ed8e2d9a5dd
# Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
# Configure your db driver and server_version in config/packages/doctrine.yaml
DATABASE_URL=mysql://db_user:db_password@127.0.0.1:3306/db_name
DATABASE_URL=sqlite:////tmp/data.db
###< doctrine/doctrine-bundle ###

###> pusher/pusher-php-server ###
Expand All @@ -22,3 +22,7 @@ PUSHER_KEY=
PUSHER_SECRET=
PUSHER_APP_CLUSTER=us2
###< pusher/pusher-php-server ###

### CUSTOM VARS ###
MAP_ASSETS_DIR=%kernel.project_dir%/assets/maps/
### END CUSTOM VARS
14 changes: 6 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,7 @@ composer install
```

Then for development set the config in .env.
Example .env:
```ini
APP_ENV=dev
APP_SECRET=eb106562e67ed9f80b2c2ed8e2d9a5dd
DATABASE_URL=sqlite:////tmp/db_name
PUSHER_APP_ID=
PUSHER_KEY=
PUSHER_SECRET=
You can use .env.dist as a starter file.
```
Then you can setup your database by running the migrations with the following:
Expand All @@ -66,6 +59,11 @@ Simply execute the following to run all unit tests:
```
Note: Test server does not need to be running to run the tests.

To run the integration tests:
```bash
./bin/phpunit --testsuite integration
```

## Deployment

Setup is similar to development, but .env should instead be set as environment variables with production values.
Expand Down
13 changes: 8 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
{
"type": "project",
"license": "proprietary",
"license": "mit",
"require": {
"php": "^7.1.3",
"php": "^7.2.0",
"ext-ctype": "*",
"ext-iconv": "*",
"ext-json": "*",
"nelmio/cors-bundle": "^1.5",
"pusher/pusher-php-server": "^3.2",
"symfony/console": "*",
"symfony/flex": "^1.1",
"symfony/framework-bundle": "*",
"symfony/orm-pack": "^1.0",
"symfony/serializer": "*",
"symfony/yaml": "*",
"ext-json": "*"
"symfony/yaml": "*"
},
"require-dev": {
"symfony/browser-kit": "*",
"symfony/dotenv": "*",
"symfony/maker-bundle": "^1.7",
"symfony/phpunit-bridge": "*",
"symfony/test-pack": "^1.0"
},
"config": {
Expand All @@ -33,7 +35,8 @@
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
"App\\UnitTests\\": "tests_unit/",
"App\\IntegrationTests\\": "tests_integration"
}
},
"replace": {
Expand Down
4 changes: 2 additions & 2 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion config/packages/doctrine_migrations.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
doctrine_migrations:
dir_name: '%kernel.project_dir%/src/Migrations'
dir_name: '%kernel.project_dir%/Migrations'
# namespace is arbitrary but should be different from App\Migrations
# as migrations classes should NOT be autoloaded
namespace: DoctrineMigrations
3 changes: 3 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,6 @@ services:
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones

App\Game\MapData\MapDataRetriever:
arguments:
$mapAssetsDir: '%env(MAP_ASSETS_DIR)%'
31 changes: 31 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.5/phpunit.xsd"
bootstrap="tests_unit/autoload.php"
forceCoversAnnotation="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTodoAnnotatedTests="true"
defaultTestSuite="unit"
verbose="true">
<testsuite name="unit">
<directory suffix="Test.php">tests_unit</directory>
</testsuite>
<testsuite name="integration">
<directory suffix="Test.php">tests_integration</directory>
</testsuite>

<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>

<php>
<ini name="error_reporting" value="-1" />
<env name="KERNEL_CLASS" value="App\Kernel" />
<env name="APP_ENV" value="test" />
<env name="APP_DEBUG" value="1" />
<env name="SHELL_VERBOSITY" value="-1" />
</php>
</phpunit>
2 changes: 1 addition & 1 deletion src/Api/Formatter/GameFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function format(Game $game): string
"owner" => $tile->getPlayerOwner(),
"type" => $tile->getType(),
];
}, $mapData->getTiles()),
}, $mapData->getTiles()),
"width" => $mapData->getWidth()
]
]);
Expand Down
65 changes: 18 additions & 47 deletions src/Game/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@
use App\Orm\Repository\PlayerRepository;
use App\Orm\Repository\TurnRepository;
use App\Orm\Repository\UnitRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMException;
use Doctrine\Common\Persistence\ObjectManager;
use Psr\Log\LoggerInterface;
use Pusher\Pusher;
use Pusher\PusherException;
Expand All @@ -30,7 +29,7 @@ class Manager implements ManagerInterface
public const UNIT_ACTION_MOVE = 'move';
public const UNIT_ACTION_ATTACK = 'attack';
/**
* @var EntityManager
* @var ObjectManager
*/
private $entityManager;
/**
Expand Down Expand Up @@ -68,7 +67,7 @@ class Manager implements ManagerInterface

/**
* Manager constructor.
* @param EntityManager $entityManager
* @param ObjectManager $objectManager
* @param MapRepository $mapRepository
* @param GameRepository $gameRepository
* @param TurnRepository $turnRepository
Expand All @@ -79,7 +78,7 @@ class Manager implements ManagerInterface
* @param LoggerInterface $logger
*/
public function __construct(
EntityManager $entityManager,
ObjectManager $objectManager,
MapRepository $mapRepository,
GameRepository $gameRepository,
TurnRepository $turnRepository,
Expand All @@ -90,7 +89,7 @@ public function __construct(
LoggerInterface $logger
)
{
$this->entityManager = $entityManager;
$this->entityManager = $objectManager;
$this->mapRepository = $mapRepository;
$this->gameRepository = $gameRepository;
$this->turnRepository = $turnRepository;
Expand All @@ -110,14 +109,10 @@ public function startGame(int $numberOfPlayers): Game
$map = $this->mapRepository->chooseRandomMap(2);
$game = new Game($map);

try {
$this->entityManager->persist($game);
$this->entityManager->flush();
$this->entityManager->persist($game);
$this->entityManager->flush();

return $game;
} catch (ORMException $e) {
throw new \RuntimeException("Unable to communicate with DB: " . $e->getMessage(), $e->getCode(), $e);
}
return $game;
}

/**
Expand Down Expand Up @@ -151,19 +146,11 @@ public function joinGame(Game $game): Player
$player->setGame($game);
$player->setPlayerNumber(count($game->getPlayers()) + 1);

try {
$this->entityManager->persist($player);
} catch (ORMException $e) {
throw new UnableToJoinGameException("DB error: " . $e->getMessage(), $e->getCode(), $e);
}
$this->entityManager->persist($player);

$this->initializeUnits($mapData, $player);

try {
$this->entityManager->flush();
} catch (ORMException $e) {
throw new UnableToJoinGameException("DB error: " . $e->getMessage(), $e->getCode(), $e);
}
$this->entityManager->flush();

if($player->getPlayerNumber() == $game->getMap()->getPlayerCount()) {
$this->triggerTurnStartEvent($game);
Expand All @@ -175,19 +162,14 @@ public function joinGame(Game $game): Player
/**
* @param $mapData
* @param $player
* @throws UnableToJoinGameException
*/
private function initializeUnits($mapData, $player): void
{
$unitInitializer = new UnitInitializer($mapData);
$units = $unitInitializer->getUnitsForPlayer($player);

foreach ($units as $unit) {
try {
$this->entityManager->persist($unit);
} catch (ORMException $e) {
throw new UnableToJoinGameException("DB error: " . $e->getMessage(), $e->getCode(), $e);
}
$this->entityManager->persist($unit);
}
}
/**
Expand Down Expand Up @@ -215,14 +197,10 @@ public function startTurn(Player $player): Turn
$turn->setStartTimestamp(new \DateTime());
$turn->setStatus(Turn::STATUS_IN_PROGRESS);

try {
$this->entityManager->persist($turn);
$this->entityManager->flush();
$this->entityManager->persist($turn);
$this->entityManager->flush();

return $turn;
} catch (ORMException $e) {
throw new \RuntimeException("Unable to communicate with DB: " . $e->getMessage(), $e->getCode(), $e);
}
return $turn;
}

/**
Expand Down Expand Up @@ -250,11 +228,7 @@ public function endTurn(Turn $turn): void

$turn->setStatus(Turn::STATUS_COMPLETED);

try {
$this->entityManager->flush();
} catch (ORMException $e) {
throw new \RuntimeException("Unable to communicate with DB: " . $e->getMessage(), $e->getCode(), $e);
}
$this->entityManager->flush();

$game = $turn->getPlayer()->getGame();

Expand Down Expand Up @@ -314,11 +288,7 @@ private function triggerTurnStartEvent(Game $game): void
$unit->regenerateActionPoints();
}

try {
$this->entityManager->flush();
} catch (ORMException $e) {
throw new \RuntimeException("Unable to save units: " . $e->getMessage(), $e->getCode(), $e);
}
$this->entityManager->flush();
}

try {
Expand Down Expand Up @@ -380,7 +350,8 @@ public function moveUnit(Turn $turn, Unit $unit, array $path): void
$unit->setXPosition($path['x']);
$unit->setYPosition($path['y']);
} else {

//TODO:
throw new InsufficientActionPointsException("TODO");
}
}
}
8 changes: 4 additions & 4 deletions src/Game/MapData/MapDataRetriever.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ class MapDataRetriever implements MapDataRetrieverInterface

/**
* MapDataRetriever constructor.
* @param string $mapAssetsDir
* @param LoggerInterface $logger
* @param null|Finder $finder
*/
const ASSETS_MAPS_DIR = "../../assets/maps/";

public function __construct(LoggerInterface $logger, ?Finder $finder = null)
public function __construct(string $mapAssetsDir, LoggerInterface $logger, ?Finder $finder = null)
{
if ($finder) {
$this->finder = $finder;
} else {
$this->finder = Finder::create();
$this->finder->in(self::ASSETS_MAPS_DIR)->files();
$this->finder->in($mapAssetsDir)->files();
}
$this->logger = $logger;
}
Expand Down
32 changes: 32 additions & 0 deletions tests_integration/Api/Controller/LobbyControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php
namespace App\IntegrationTests\Api\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class LobbyControllerTest extends WebTestCase
{
public function testGameCreation()
{
$client = self::createClient();

$client->request("POST", "/game");

$gameData = json_decode($client->getResponse()->getContent(), true);

$this->assertArrayIsValidGame($gameData);
}

private function assertArrayIsValidGame(array $gameData): void
{
$this->assertArrayHasKey("id", $gameData);
$this->assertArrayHasKey("playerNumber", $gameData);
$this->assertArrayHasKey("turnNumber", $gameData);
$this->assertArrayHasKey("map", $gameData);
$this->assertArrayHasKey("tiles", $gameData["map"] ?? []);
$this->assertArrayHasKey("width", $gameData["map"] ?? []);
$this->assertGreaterThanOrEqual($gameData["map"]["width"] ?? PHP_INT_MAX, count($gameData["map"]["tiles"] ?? []));
$this->assertArrayHasKey(0, $gameData["map"]["tiles"] ?? []);
$this->assertArrayHasKey("type", $gameData["map"]["tiles"][0] ?? []);
$this->assertArrayHasKey("owner", $gameData["map"]["tiles"][0] ?? []);
}
}
12 changes: 12 additions & 0 deletions tests_unit/autoload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

use Symfony\Component\Dotenv\Dotenv;

require __DIR__.'/../vendor/autoload.php';

if (!isset($_SERVER['APP_ENV'])) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.');
}
(new Dotenv())->load(__DIR__.'/../.env');
}

0 comments on commit dd40988

Please sign in to comment.