Update
This commit is contained in:
86
app/common/Controller/Update.php
Normal file
86
app/common/Controller/Update.php
Normal file
@ -0,0 +1,86 @@
|
||||
<?php
|
||||
namespace ProVM\Money\Common\Controller;
|
||||
|
||||
use Psr\Container\ContainerInterface as Container;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use GuzzleHttp\ClientInterface as Client;
|
||||
use Carbon\Carbon;
|
||||
use ProVM\Common\Define\Controller\Json;
|
||||
use ProVM\Common\Factory\Model as ModelFactory;
|
||||
use ProVM\Money\Currency;
|
||||
use ProVM\Money\Source;
|
||||
use ProVM\Money\Value;
|
||||
|
||||
class Update {
|
||||
use Json;
|
||||
|
||||
protected function get(Client $client, string $url, bool $exception = true) {
|
||||
$res = $client->get($url);
|
||||
if ($res->getStatusCode() < 200 or $res->getStatusCode() >= 300) {
|
||||
if ($exception) {
|
||||
throw new \Exception('Url ' . $url . ' not connected.');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return json_decode($res->getBody());
|
||||
}
|
||||
|
||||
protected function baseMap($unit) {
|
||||
$map = [
|
||||
'Dólar' => 'US Dollar',
|
||||
'Pesos' => 'Peso Chileno'
|
||||
];
|
||||
return $map[$unit] ?? $unit;
|
||||
}
|
||||
|
||||
public function __invoke(Request $request, Response $response, Client $client, ModelFactory $factory, Container $container): Response {
|
||||
ini_set('max_execution_time', 300);
|
||||
|
||||
$sources = $factory->find(Source::class)->many();
|
||||
$date = Carbon::now();
|
||||
$output = ['count' => 0, 'values' => []];
|
||||
foreach ($sources as $source) {
|
||||
$url = str_replace([
|
||||
'{year}',
|
||||
'{month}',
|
||||
'{day}',
|
||||
'{hour}',
|
||||
'{minute}',
|
||||
'{second}'
|
||||
], [
|
||||
$date->year,
|
||||
$date->month,
|
||||
$date->day,
|
||||
$date->hour,
|
||||
$date->minute,
|
||||
$date->second
|
||||
], $source->url);
|
||||
$b = $this->get($client, $url, false);
|
||||
if ($b === false) {
|
||||
continue;
|
||||
}
|
||||
$base = $factory->find(Currency::class)->where([
|
||||
['name', '%' . $this->baseMap($b->unidad_medida) . '%', 'like']
|
||||
])->one();
|
||||
if (!$base) {
|
||||
continue;
|
||||
}
|
||||
foreach ($b->serie as $info) {
|
||||
$f = Carbon::parse($info->fecha);
|
||||
$data = [
|
||||
'currency_id' => $source->currency()->id,
|
||||
'date_time' => $f->format('Y-m-d H:i:s'),
|
||||
'value' => $info->valor,
|
||||
'base_id' => $base->id
|
||||
];
|
||||
$result = Value::add($factory, $data);
|
||||
$output['values'] []= $result;
|
||||
if ($result->created === true) {
|
||||
$output['count'] ++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->withJson($response, $output);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user