Compare commits

...

4 Commits

Author SHA1 Message Date
9fcd8c367c Merge branch 'develop' into master 2021-04-13 21:02:58 -04:00
b6bc007590 Migrate once when loaded 2021-04-13 21:02:23 -04:00
60cd73078c Env data 2021-04-13 21:01:56 -04:00
1dab43ca90 Seeds 2021-04-13 21:01:29 -04:00
11 changed files with 251 additions and 90 deletions

View File

@ -4,83 +4,14 @@ 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;
use ProVM\Money\Common\Service\Update as Updater;
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'] ++;
}
}
}
public function __invoke(Request $request, Response $response, Updater $updater): Response {
$output = $updater->update();
return $this->withJson($response, $output);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace ProVM\Money\Common\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Psr\Http\Message\ResponseInterface as Response;
use Phinx\Wrapper\TextWrapper;
use GuzzleHttp\ClientInterface as Client;
use ProVM\Money\Common\Service\Update as Updater;
class Migrate {
protected $phinx;
protected $updater;
public function __construct(TextWrapper $phinx, Updater $updater) {
$this->phinx = $phinx;
$this->updater = $updater;
}
public function __invoke(Request $request, Handler $handler): Response {
$query = "SHOW TABLES";
$st = \ORM::get_db()->query($query);
$r = $st->fetchAll(\PDO::FETCH_ASSOC);
if (count($r) == 0) {
$this->phinx->getMigrate();
$this->phinx->getSeed();
$this->updater->update();
}
return $handler->handle($request);
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace ProVM\Money\Common\Service;
use GuzzleHttp\ClientInterface as Client;
use Carbon\Carbon;
use ProVM\Common\Factory\Model as ModelFactory;
use ProVM\Money\Currency;
use ProVM\Money\Source;
use ProVM\Money\Value;
class Update {
protected $factory;
protected $client;
public function __construct(ModelFactory $factory, Client $client) {
$this->factory = $factory;
$this->client = $client;
}
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;
}
protected function buildUrl(Source $source) {
$date = Carbon::now();
return str_replace([
'{year}',
'{month}',
'{day}',
'{hour}',
'{minute}',
'{second}'
], [
$date->year,
$date->month,
$date->day,
$date->hour,
$date->minute,
$date->second
], $source->url);
}
public function update() {
ini_set('max_execution_time', 300);
$sources = $this->factory->find(Source::class)->many();
$output = ['count' => 0, 'values' => []];
foreach ($sources as $source) {
$url = $this->buildUrl($source);
$b = $this->get($this->client, $url, false);
if ($b === false) {
continue;
}
$base = $this->factory->find(Currency::class)->where([
['name', '%' . $this->baseMap($b->unidad_medida) . '%', 'like']
])->one();
if ($base === false) {
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($this->factory, $data);
$output['values'] []= $result;
if ($result->created === true) {
$output['count'] ++;
}
}
}
return $output;
}
}

View File

@ -11,6 +11,7 @@
"provm/controller": "dev-master",
"vlucas/phpdotenv": "^5.3",
"guzzlehttp/guzzle": "^7.3",
"robmorgan/phinx": "^0.12.5",
"nesbot/carbon": "^2.46"
},
"license": "MIT",
@ -22,7 +23,6 @@
],
"require-dev": {
"phpunit/phpunit": "^8.5",
"robmorgan/phinx": "^0.12.5",
"odan/phinx-migrations-generator": "^5.4"
},
"autoload": {

View File

@ -12,28 +12,28 @@ return
'default_environment' => 'development',
'production' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'production_db',
'user' => 'root',
'pass' => '',
'host' => $_ENV['DB_HOST'],
'name' => $_ENV['DB_NAME'],
'user' => $_ENV['DB_USER'],
'pass' => $_ENV['DB_PASSWORD'],
'port' => '3306',
'charset' => 'utf8',
],
'development' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'money_dev',
'user' => 'money',
'pass' => 'money_pass',
'port' => '3307',
'host' => $_ENV['DB_HOST'],
'name' => $_ENV['DB_NAME'],
'user' => $_ENV['DB_USER'],
'pass' => $_ENV['DB_PASSWORD'],
'port' => '3306',
'charset' => 'utf8',
],
'testing' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'testing_db',
'user' => 'root',
'pass' => '',
'host' => $_ENV['DB_HOST'],
'name' => $_ENV['DB_NAME'],
'user' => $_ENV['DB_USER'],
'pass' => $_ENV['DB_PASSWORD'],
'port' => '3306',
'charset' => 'utf8',
]

View File

@ -0,0 +1,2 @@
<?php
$app->add($app->getContainer()->get(ProVM\Money\Common\Middleware\Migrate::class));

View File

@ -22,5 +22,11 @@ return [
'routes'
]);
return (object) $arr;
})
}),
'phinx' => function(Container $c) {
return implode(DIRECTORY_SEPARATOR, [
$c->get('locations')->base,
'phinx.php'
]);
}
];

View File

@ -4,5 +4,23 @@ use Psr\Container\ContainerInterface as Container;
return [
GuzzleHttp\ClientInterface::class => function(Container $c) {
return new GuzzleHttp\Client();
},
ProVM\Common\Factory\Model::class => function(Container $c) {
return new ProVM\Common\Factory\Model();
},
ProVM\Money\Common\Service\Update::class => function(Container $c) {
return new ProVM\Money\Common\Service\Update($c->get(ProVM\Common\Factory\Model::class), $c->get(GuzzleHttp\ClientInterface::class));
},
ProVM\Money\Common\Middleware\Migrate::class => function(Container $c) {
return new ProVM\Money\Common\Middleware\Migrate($c->get(Phinx\Wrapper\TextWrapper::class), $c->get(ProVM\Money\Common\Service\Update::class));
},
Phinx\Console\PhinxApplication::class => function(Container $c) {
return new Phinx\Console\PhinxApplication();
},
Phinx\Wrapper\TextWrapper::class => function(Container $c) {
$options = [
'configuration' => $c->get('phinx')
];
return new Phinx\Wrapper\TextWrapper($c->get(Phinx\Console\PhinxApplication::class), $options);
}
];

38
db/seeds/Currencies.php Normal file
View File

@ -0,0 +1,38 @@
<?php
use Phinx\Seed\AbstractSeed;
class Currencies extends AbstractSeed
{
/**
* Run Method.
*
* Write your database seeder using this method.
*
* More information on writing seeders is available here:
* https://book.cakephp.org/phinx/0/en/seeding.html
*/
public function run()
{
$data = [
[
'code' => 'CLP',
'name' => 'Peso Chileno'
],
[
'code' => 'CLF',
'name' => 'Unidad de Fomento'
],
[
'code' => 'USD',
'name' => 'US Dollar'
],
[
'code' => 'BTC',
'name' => 'Bitcoin'
]
];
$this->table('currencies')->insert($data)->saveData();
}
}

45
db/seeds/Sources.php Normal file
View File

@ -0,0 +1,45 @@
<?php
use Phinx\Seed\AbstractSeed;
class Sources extends AbstractSeed
{
public function getDependencies() {
return [
'Currencies'
];
}
/**
* Run Method.
*
* Write your database seeder using this method.
*
* More information on writing seeders is available here:
* https://book.cakephp.org/phinx/0/en/seeding.html
*/
public function run()
{
$id = $this->query("SELECT id FROM currencies WHERE code = 'USD'")->fetchAll(\PDO::FETCH_ASSOC);
$data = [
[
'currency_id' => $id[0]['id'],
'url' => 'https://mindicador.cl/api/dolar/{year}',
'frecuency' => '1 DAY'
]
];
$id = $this->query("SELECT id FROM currencies WHERE code = 'CLF'")->fetchAll(\PDO::FETCH_ASSOC);
$data []= [
'currency_id' => $id[0]['id'],
'url' => 'https://mindicador.cl/api/uf/{year}',
'frecuency' => '1 DAY'
];
$id = $this->query("SELECT id FROM currencies WHERE code = 'BTC'")->fetchAll(\PDO::FETCH_ASSOC);
$data []= [
'currency_id' => $id[0]['id'],
'url' => 'https://mindicador.cl/api/bitcoin/{year}',
'frecuency' => '1 DAY'
];
$this->table('sources')->insert($data)->saveData();
}
}

View File

@ -73,9 +73,9 @@ services:
- 3307:3306
environment:
MYSQL_ROOT_PASSWORD: 'money'
MYSQL_DATABASE: 'money_dev'
MYSQL_USER: 'money'
MYSQL_PASSWORD: 'money_pass'
MYSQL_DATABASE: ${DB_NAME-money_dev}
MYSQL_USER: '${DB_USER-money}'
MYSQL_PASSWORD: '${DB_PASSWORD-money_pass}'
volumes:
- dbdata:/var/lib/mysql
adminer: