68 lines
1.9 KiB
PHP
68 lines
1.9 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 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);
|
|
}
|
|
}
|