Files
oficial/app/src/Controller/API/Provincias.php
2023-11-23 00:53:49 -03:00

40 lines
1.4 KiB
PHP

<?php
namespace Incoviba\Controller\API;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Controller\withRedis;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Provincias
{
use withRedis, withJson;
public function comunas(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Repository\Comuna $comunaRepository, int $provincia_id): ResponseInterface
{
$output = [
'provincia_id' => $provincia_id,
'comunas' => []
];
$redisKey = "comunas:provincia:{$provincia_id}";
try {
$output['comunas'] = $this->fetchRedis($redisService, $redisKey);
} catch (EmptyRedis) {
try {
$comunas = $comunaRepository->fetchByProvincia($provincia_id);
usort($comunas, function(Model\Comuna $a, Model\Comuna $b) {
return strcmp($a->descripcion, $b->descripcion);
});
$output['comunas'] = $comunas;
$this->saveRedis($redisService, $redisKey, $comunas, 60 * 60 * 24 * 30);
} catch (EmptyResult) {}
}
return $this->withJson($response, $output);
}
}