Files
oficial/app/src/Controller/API/Direcciones.php

81 lines
3.5 KiB
PHP

<?php
namespace Incoviba\Controller\API;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Common\Implement\Exception\EmptyRedis;
use Incoviba\Controller\withRedis;
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service;
class Direcciones
{
use withRedis, withJson;
public function comunas(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Repository\Region $regionRepository, Repository\Comuna $comunaRepository,
int $region_id) : ResponseInterface
{
$output = ['total' => 0, 'comunas' => []];
$redisKey = "comunas:region:{$region_id}";
try {
$output['comunas'] = $this->fetchRedis($redisService, $redisKey);
$output['total'] = count($output['comunas']);
} catch (EmptyRedis) {
$regionKey = "regiones:{$region_id}";
try {
$region = $this->fetchRedis($redisService, $regionKey);
} catch (EmptyRedis) {
$region = $regionRepository->fetchById($region_id);
$this->saveRedis($redisService, $regionKey, $region, 60 * 60 * 24 * 30);
}
$comunas = $comunaRepository->fetchByRegion($region->id);
usort($comunas, function(Model\Comuna $a, Model\Comuna $b) {
return strcoll($a->descripcion, $b->descripcion);
});
$output = ['comunas' => $comunas, 'total' => count($comunas)];
$this->saveRedis($redisService, $redisKey, $comunas, 60 * 60 * 24 * 30);
/*$provinciaKey = 'provincias';
try {
$temp_provincias = $this->fetchRedis($redisService, $provinciaKey);
} catch (EmptyRedis) {
$temp_provincias = $provinciaRepository->fetchByRegion($region_id);
$this->saveRedis($redisService, $provinciaKey, $temp_provincias, 60 * 60 * 24 * 30);
}
$comunas = [];
foreach($temp_provincias as $provincia) {
$temp_comunas = $comunaRepository->fetchByProvincia($provincia->id);
$comunas = array_merge($comunas, $temp_comunas);
}
usort($comunas, function(Model\Comuna $a, Model\Comuna $b) {
return strcoll($a->descripcion, $b->descripcion);
});
$output = ['comunas' => $comunas, 'total' => count($comunas)];
$this->saveRedis($redisService, $redisKey, $comunas, 60 * 60 * 24 * 30);*/
}
return $this->withJson($response, $output);
}
public function findComunas(ServerRequestInterface $request, ResponseInterface $response, Service\Redis $redisService,
Repository\Comuna $comunaRepository): ResponseInterface
{
$body = $request->getBody();
$json = json_decode($body->getContents());
$output = ['input' => $json, 'total' => 0, 'comunas' => []];
$redisKey = "comunas:direccion:{$json->direccion}";
try {
$output['comunas'] = $this->fetchRedis($redisService, $redisKey);
} catch (EmptyRedis) {
try {
$comunas = $comunaRepository->fetchByDireccion($json->direccion);
$output['comunas'] = $comunas;
$output['total'] = count($comunas);
$this->saveRedis($redisService, $redisKey, $comunas);
} catch (EmptyResult) {}
}
return $this->withJson($response, $output);
}
}