mapguesser/src/Repository/PlaceRepository.php
Pőcze Bence edd8c0f8a4
All checks were successful
default-pipeline default-pipeline #21
MAPG-203 select places at the beginning of the game
2021-03-17 22:47:11 +01:00

83 lines
2.2 KiB
PHP

<?php namespace MapGuesser\Repository;
use Generator;
use MapGuesser\Database\Query\Select;
use MapGuesser\PersistentData\Model\Map;
use MapGuesser\PersistentData\Model\Place;
use MapGuesser\PersistentData\PersistentDataManager;
class PlaceRepository
{
private PersistentDataManager $pdm;
public function __construct()
{
$this->pdm = new PersistentDataManager();
}
public function getById(int $placeId): ?Place
{
return $this->pdm->selectFromDbById($placeId, Place::class);
}
public function getAllForMap(Map $map): Generator
{
$select = new Select(\Container::$dbConnection);
$select->where('map_id', '=', $map->getId());
yield from $this->pdm->selectMultipleFromDb($select, Place::class);
}
//TODO: use Map instead of id
public function getRandomNForMapWithValidPano(int $mapId, int $n, array $exclude = []): array
{
$places = [];
for ($i = 1; $i <= $n; ++$i) {
$place = $this->getRandomForMapWithValidPano($mapId, $exclude);
$places[] = $place;
$exclude[] = $place->getId();
}
return $places;
}
//TODO: use Map instead of id
public function getRandomForMapWithValidPano(int $mapId, array $exclude = []): Place
{
do {
$place = $this->selectRandomFromDbForMap($mapId, $exclude);
$panoId = $place->getFreshPanoId();
if ($panoId === null) {
$exclude[] = $place->getId();
}
} while ($panoId === null);
return $place;
}
private function selectRandomFromDbForMap(int $mapId, array $exclude): Place
{
//TODO: omit table name here
$select = new Select(\Container::$dbConnection, 'places');
$select->where('id', 'NOT IN', $exclude);
$select->where('map_id', '=', $mapId);
$numberOfPlaces = $select->count();
//TODO: prevent this
if ($numberOfPlaces === 0) {
throw new \Exception('There is no selectable place (count was 0).');
}
$randomOffset = random_int(0, $numberOfPlaces - 1);
$select->orderBy('id');
$select->limit(1, $randomOffset);
return $this->pdm->selectFromDb($select, Place::class);
}
}