Merge branch 'develop'

This commit is contained in:
Juan Pablo Vial
2023-06-22 23:18:13 -04:00
29 changed files with 784 additions and 153 deletions

View File

@ -2,3 +2,4 @@ MYSQL_DATABASE=incoviba
MYSQL_PASSWORD=5GQYFvRjVw2A4KcD
MYSQL_ROOT_PASSWORD=password
MYSQL_USER=incoviba
MYSQL_PORT=3307

View File

@ -1,8 +1,12 @@
<?php
namespace App\Contract;
use App\Alias\RemoteConnection;
use App\Definition\Contract;
use App\Service\Money;
use App\Service\Remote;
use App\Service\View as ViewService;
use GuzzleHttp\Client;
class View
{
@ -10,7 +14,12 @@ class View
protected static function newInstance()
{
return new ViewService();
$remote = new Remote(new RemoteConnection());
$money = (new Money(new Client([
'base_uri' => "http://{$remote->getIP()}:8008",
'headers' => ['Accept' => 'application/json']
])));
return new ViewService(['money' => $money]);
}
public static function show($template, $variables = null)
{

View File

@ -9,12 +9,12 @@ class View
protected $cache;
protected $blade;
public function __construct()
public function __construct(array $variables = [])
{
$this->views = config('locations.views');
$this->cache = config('locations.cache');
$this->blade = new BladeOne($this->views, $this->cache);
$this->blade = new BladeOne($this->views, $this->cache, null, $variables);
}
public function show($template, $vars = null)
{

50
app/Alias/Connection.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace App\Alias;
use PDO;
use PDOException;
class Connection
{
public function __construct(
protected string $host,
protected string $database,
protected string $username,
protected string $password,
protected ?int $port = null,
protected int $retries = 5
) {}
protected PDO $connection;
public function connect(): PDO
{
if (!isset($this->connection)) {
$r = 0;
$exception = null;
while ($r < $this->retries) {
try {
$dsn = $this->getDsn();
$this->connection = new PDO($dsn, $this->username, $this->password);
return $this->connection;
} catch (PDOException $e) {
if ($exception !== null) {
$e = new PDOException($e->getMessage(), $e->getCode(), $exception);
}
$exception = $e;
usleep(500);
}
$r ++;
}
throw $exception;
}
return $this->connection;
}
protected function getDsn(): string
{
$dsn = "mysql:host={$this->host};dbname={$this->database}";
if (isset($this->port)) {
$dsn .= ";port={$this->port}";
}
return $dsn;
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Alias;
class RemoteConnection extends Connection
{
public function __construct(protected int $retries = 5)
{
parent::__construct(
$_ENV['REMOTE_HOST'],
$_ENV['REMOTE_DATABASE'],
$_ENV['REMOTE_USER'],
$_ENV['REMOTE_PASSWORD'],
$_ENV['REMOTE_PORT'] ?? null,
$this->retries
);
}
}

86
app/Command/Money/Get.php Normal file
View File

@ -0,0 +1,86 @@
<?php
namespace App\Command\Money;
use DateTimeInterface;
use DateTimeImmutable;
use PDO;
use PDOException;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use App\Alias\Connection;
use App\Service\Money;
#[AsCommand(
name: 'money:uf:get',
hidden: false
)]
class Get extends Command
{
public function __construct(protected Money $service, protected Connection $connection, string $name = null)
{
parent::__construct($name);
}
public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Get Money');
$dates = $this->getDates();
foreach ($dates as $date_string => $ids) {
$date = $this->parseDate($date_string);
$response = $this->service->getUF($date);
if ($response->total === 0) {
continue;
}
foreach ($ids as $id) {
$this->queueUpdate($id, $response->uf->value);
}
}
$this->updateUF();
}
protected function getDates(): array
{
$query = "SELECT id, fecha FROM pago WHERE uf IS NULL AND fecha BETWEEN 0 AND DATE_ADD(CURDATE(), INTERVAL 9 DAY) ORDER BY fecha";
$statement = $this->connection->connect()->query($query);
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
if (count($rows) === 0) {
return [];
}
$dates = [];
foreach ($rows as $row) {
if (!isset($dates[$row['fecha']])) {
$dates[$row['fecha']] = [];
}
$dates[$row['fecha']] []= (int) $row['id'];
}
return $dates;
}
protected function parseDate(string $date_string): DateTimeInterface
{
return new DateTimeImmutable($date_string);
}
protected array $rows;
protected function queueUpdate(int $id, float $value): void
{
$this->rows []= [$value, $id];
}
protected function updateUF(): void
{
$query = "UPDATE pago SET uf = ? WHERE id = ?";
$statement = $this->connection->connect()->prepare($query);
foreach ($this->rows as $row) {
$this->connection->connect()->beginTransaction();
try {
$statement->execute($row);
$this->connection->connect()->commit();
} catch (PDOException $e) {
$this->connection->connect()->rollBack();
}
}
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Command\Money;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use App\Alias\Connection;
#[AsCommand(
name: 'money:lookup',
hidden: false
)]
class Lookup extends Command
{
public function __construct(protected Connection $connection, string $name = null)
{
parent::__construct($name);
}
public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Lookup Money');
while (true) {
$io->info('Checking pending');
if ($this->hasPendingMoney()) {
$io->success('Running money get UF');
$io->note($this->runGetUF());
}
}
}
protected function hasPendingMoney(): bool
{
$query = "SELECT 1 FROM pago WHERE uf IS NULL AND fecha BETWEEN 0 AND DATE_ADD(CURDATE(), INTERVAL 9 DAY)";
$statement = $this->connection->connect()->query($query);
return $statement->rowCount() > 0;
}
protected function runGetUF(): string
{
$command = "/code/bin/console money:uf:get";
$result = shell_exec($command);
if (!$result or $result === null) {
throw new \Exception();
}
return $result;
}
}

View File

@ -312,7 +312,7 @@ class Proyectos
}
return view('proyectos.reservas.base', compact('proyecto', 'pisos', 'max_unidades', 'totales'));
}
public function unidades()
public static function unidades()
{
if (get('proyecto')) {
$proyecto = model(Proyecto::class)->findOne(get('proyecto'));

View File

@ -31,27 +31,13 @@ function route_api() {
return call_user_func_array([$class, $a], $params);
}
function uf($date, $async = false) {
if (is_string($date)) {
$date = Carbon\Carbon::parse($date, config('app.timezone'));
}
$next_m_9 = Carbon\Carbon::today(config('app.timezone'))->copy()->endOfMonth()->addDays(9);
if ($date->greaterThanOrEqualTo($next_m_9)) {
return (object) ['total' => 0];
}
$url = 'http://' . config('locations.money') . '/api/uf/value/' . $date->format('Y-m-d');
$client = new \GuzzleHttp\Client(['base_uri' => 'http://' . config('locations.money') . '/', 'headers' => ['Accept' => 'application/json']]);
$response = $client->get('api/uf/value/' . $date->format('Y-m-d'));
//$response = $client->getResponse();
if (!$response) {
return (object) ['total' => 0];
}
$status = $response->getStatusCode();
if ($status >= 200 and $status < 300) {
$data = json_decode($response->getBody()->getContents());
return $data;
}
return (object) ['total' => 0];
$remote = new App\Service\Remote(new App\Alias\RemoteConnection());
return (new App\Service\Money(new GuzzleHttp\Client([
'base_uri' => "http://{$remote->getIP()}:8080",
'headers' => [
'Accept' => 'application/json'
]
])))->getUF($date);
}
function format($tipo, $valor, $format = null, $print = false) {
if ($valor === null) {

55
app/Service/Money.php Normal file
View File

@ -0,0 +1,55 @@
<?php
namespace App\Service;
use DateTimeInterface;
use Psr\Http\Message\ResponseInterface;
use Carbon\Carbon;
use GuzzleHttp\Client;
class Money
{
public function __construct(protected Client $client) {}
public function getUF(string|DateTimeInterface $date): object
{
$date = $this->parseDate($date);
if (!$this->checkNextMonthValueCalculationByDate($date)) {
return $this->emptyResult();
}
$response = $this->client->get('api/uf/value/' . $date->format('Y-m-d'));
if (!$this->isOk($response)) {
return $this->emptyResult();
}
$body = $response->getBody()->getContents();
if (trim($response->getBody()) === '') {
return $this->emptyResult();
}
return json_decode($body);
}
protected function parseDate(string|DateTimeInterface $date): DateTimeInterface
{
if (is_string($date)) {
$date = Carbon::parse($date, config('app.timezone'));
}
return $date;
}
protected function checkNextMonthValueCalculationByDate(DateTimeInterface $date): bool
{
$next_m_9 = Carbon::today(config('app.timezone'))->copy()->endOfMonth()->addDays(9);
$date = Carbon::parse($date);
return $date->lessThan($next_m_9);
}
protected function isOk(ResponseInterface $response): bool
{
$statusCode = $response->getStatusCode();
return $statusCode >= 200 and $statusCode < 300;
}
protected function emptyResult(): object
{
return (object) ['total' => 0];
}
}

19
app/Service/Remote.php Normal file
View File

@ -0,0 +1,19 @@
<?php
namespace App\Service;
use PDO;
use App\Alias\RemoteConnection;
class Remote
{
public function __construct(protected RemoteConnection $connection) {}
public function getIP(): string
{
$query = "SELECT `ip` FROM `remote_ip` WHERE `host` = 'vialdelamaza'";
$connection = $this->connection->connect();
$statement = $connection->query($query);
$result = $statement->fetch(PDO::FETCH_ASSOC);
return $result['ip'];
}
}

3
bin/console Normal file
View File

@ -0,0 +1,3 @@
#!/bin/bash
php /code/bin/index.php "$@"

8
bin/index.php Normal file
View File

@ -0,0 +1,8 @@
<?php
//$__environment = 'cli';
$app = include_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 2),
'setup',
'cli.app.php'
]);
$app->run();

View File

@ -1,6 +1,7 @@
<?php
include_once dirname(__DIR__) . '/vendor/autoload.php';
include_once 'errors.php';
include_once 'logs.php';
include_once 'dotenv.php';
include_once 'database.php';
include_once 'routes.php';

View File

@ -27,4 +27,3 @@ function load($data, $name = '') {
}
Model::$short_table_names = true;
?>

26
bootstrap/logs.php Normal file
View File

@ -0,0 +1,26 @@
<?php
use Monolog\{Handler,Processor,Formatter,Level};
function buildLogger() {
$logger = new Monolog\Logger('global', [
new Handler\FilterHandler(new Handler\RotatingFileHandler('/logs/php.log'),
Level::Debug,
Level::Notice
),
new Handler\FilterHandler(new Handler\RotatingFileHandler('/logs/error.log'),
Level::Warning,
Level::Critical
),
new Handler\FilterHandler(new Handler\NativeMailerHandler('jpvial@incoviba.cl', 'Incoviba Error', 'alert@incoviba.cl'),
Level::Alert
)
], [
new Processor\PsrLogMessageProcessor(),
new Processor\IntrospectionProcessor(),
new Processor\WebProcessor(),
new Processor\MemoryPeakUsageProcessor()
]);
return $logger;
}
$logger = buildLogger();
Monolog\ErrorHandler::register($logger);

View File

@ -3,28 +3,30 @@
"description" : "Intranet portal for Incoviba",
"type" : "project",
"require" : {
"aldarien/config" : "*",
"aldarien/asset" : "*",
"aldarien/format" : "*",
"aldarien/response" : "*",
"aldarien/view" : "*",
"aldarien/session" : "*",
"aldarien/asset": "*",
"aldarien/config": "*",
"aldarien/format": "*",
"aldarien/response": "*",
"aldarien/session": "*",
"aldarien/url": "*",
"j4mie/paris" : "^1.5",
"voku/stringy" : "^6",
"phpoffice/phpspreadsheet": "^1",
"nesbot/carbon": "^2",
"phpoffice/phpword": "^0",
"slam/php-excel": "^4.4",
"aldarien/view": "*",
"guzzlehttp/guzzle": "*",
"incoviba/modelos": "*",
"slim/slim": "^4",
"php-di/slim-bridge": "*",
"rubellum/slim-blade-view": "*",
"j4mie/paris": "^1.5",
"monolog/monolog": "^3",
"nesbot/carbon": "^2",
"nyholm/psr7": "*",
"nyholm/psr7-server": "*",
"php-di/php-di": "*",
"php-di/slim-bridge": "*",
"phpoffice/phpspreadsheet": "^1",
"phpoffice/phpword": "^0",
"rubellum/slim-blade-view": "*",
"slam/php-excel": "^4.4",
"slim/slim": "^4",
"symfony/console": "6.4.x-dev",
"vlucas/phpdotenv": "^5.3",
"monolog/monolog": "^3"
"voku/stringy": "^6"
},
"require-dev" : {
"phpunit/phpunit" : "*",
@ -39,9 +41,8 @@
],
"autoload" : {
"psr-4" : {
"App\\" : "app",
"Incoviba\\Common\\": "incoviba/common",
"Incoviba\\": "incoviba/src"
"App\\" : "app/",
"ProVM\\Common\\": "provm/common/"
},
"files" : [
"app/Helper/functions.php"

View File

@ -7,4 +7,3 @@ return [
'benchmark' => false,
'login_hours' => 5*24
];
?>

View File

@ -1,19 +1,24 @@
<?php
include_once dirname(__DIR__) . '/bootstrap/dotenv.php';
return [
'mysql' => [
'host' => $_ENV['MYSQL_HOST'],
//'port' => 3306,
'database' => $_ENV['MYSQL_DATABASE'],
'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASSWORD']
],
'mysql_copy' => [
'host' => 'localhost',
'database' => 'incoviba3',
'username' => 'incoviba',
'password' => $_ENV['MYSQL_PASSWORD']
]
]
?>
function buildDatabaseConfig(): array {
$arr = [
'mysql' => [
'host' => $_ENV['MYSQL_HOST'],
'database' => $_ENV['MYSQL_DATABASE'],
'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASSWORD']
],
'mysql_copy' => [
'host' => 'localhost',
'database' => 'incoviba3',
'username' => 'incoviba',
'password' => $_ENV['MYSQL_PASSWORD']
]
];
if (isset($_ENV['MYSQL_PORT'])) {
$arr['mysql']['port'] = $_ENV['MYSQL_PORT'];
}
return $arr;
}
return buildDatabaseConfig();

View File

@ -25,6 +25,7 @@ services:
env_file:
- .env
- .db.env
- .remote.env
volumes:
- .:/code
- ./php-errors.ini:/usr/local/etc/php/conf.d/docker-php-errors.ini
@ -39,6 +40,9 @@ services:
env_file: .db.env
volumes:
- dbdata:/var/lib/mysql
networks:
- default
- adminer_network
adminer:
profiles:
@ -68,6 +72,7 @@ services:
container_name: incoviba_logview
restart: unless-stopped
environment:
WEB_URL: 'http://provm.cl:8084'
WEB_PORT: '8084'
volumes:
- "./logs:/logs"
@ -76,3 +81,6 @@ services:
volumes:
dbdata:
networks:
adminer_network: {}

Submodule modules/operadores deleted from 4f7241e146

View File

@ -1,6 +1,6 @@
<?php
$__environment = 'api';
include_once implode(DIRECTORY_SEPARATOR, [
$app = include_once implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__, 2),
'setup',
'app.php'

View File

@ -1,116 +1,288 @@
<?php
use Carbon\Carbon;
use Incoviba\old\Proyecto\Proyecto;
use App\Contract\Auth;
use Monolog\Level;
use Monolog\Handler;
use Monolog\Processor;
use Monolog\Formatter;
use App\Service\Auth;
use Incoviba\old\Proyecto\Proyecto;
include_once dirname(__DIR__) . '/bootstrap/autoload.php';
header("Access-Control-Allow-Origin: *");
class Benchmark
{
public function __construct(protected Monolog\Logger $logger, protected bool $debug, protected bool $benchmark) {}
$logger = new Monolog\Logger('global');
$logger->pushHandler(new Handler\RotatingFileHandler('/logs/php.log'));
$handler = new Handler\NativeMailerHandler('jpvial@incoviba.cl', 'Incoviba Error', 'alert@incoviba.cl');
$handler->setFormatter(new Formatter\HtmlFormatter());
$logger->pushHandler(new Handler\FilterHandler($handler, Level::Error));
$logger->pushProcessor(new Processor\PsrLogMessageProcessor());
$logger->pushProcessor(new Processor\IntrospectionProcessor());
$logger->pushProcessor(new Processor\WebProcessor());
$logger->pushProcessor(new Processor\MemoryPeakUsageProcessor());
protected float $time = 0;
Monolog\ErrorHandler::register($logger);
public function start()
{
if ($this->debug and $this->benchmark) {
$this->time = microtime(true);
}
}
if (config('app.debug') == true) {
if (config('app.benchmark') == true) {
$benchmark = (object) ['time' => microtime(true)];
public function stop()
{
if ($this->debug and $this->benchmark) {
$this->time = microtime(true) - $this->time;
}
}
public function show()
{
if ($this->debug and $this->benchmark) {
$this->logger->debug("Time {$this->time}");
echo view('benchmark', ['benchmark' => $this->time]);
}
}
}
Carbon::setLocale(config('app.locale'));
setlocale(LC_TIME, 'es_ES');
class Request
{
public function __construct()
{
sanitize();
}
sanitize();
protected array $server;
protected array $headers;
protected object $uri;
protected array $query;
protected object $body;
try {
Auth::isIn();
} catch (PDOException $e) {
$logger->error($e);
header('Location: install');
die();
public function getServerParams(): array
{
return $this->server;
}
public function getHeaders(): array
{
return $this->headers;
}
public function getUri(): object
{
return $this->uri;
}
public function getQueryParams(): array
{
return $this->query;
}
public function getBody(): object
{
return $this->body;
}
public static function createFromGlobals(): Request
{
$request = new Request();
$request->server = $_SERVER;
$request->headers = apache_request_headers();
$request->uri = (object) parse_url($_SERVER['REQUEST_URI']);
$request->query = $_GET;
$request->body = new class() {
public function __construct()
{
$this->contents = fopen('php://stdin', 'r');
}
protected $contents;
public function getContent(): string
{
return stream_get_contents($this->contents);
}
};
return $request;
}
}
class Container
{
public function __construct(array $definitions = [])
{
foreach ($definitions as $name => $value)
{
$this->set($name, $value);
}
if (!isset($definitions[Container::class])) {
$this->set(Container::class, $this);
}
}
try {
if (Auth::isIn()) {
if ((get('p') !== false or get('page') !== false or get('m') !== false or get('module') !== false)) {
if (($route = route()) !== false) {
echo $route;
protected array $definitions;
public function get(string $name)
{
if (!isset($this->definitions[$name]) and class_exists($name)) {
$this->set($name, $name);
}
return $this->eval($this->definitions[$name]);
}
public function set(string $name, $value): Container
{
$this->definitions[$name] = $value;
return $this;
}
protected function eval($value)
{
if (is_callable($value)) {
return $this->evalCallable($value);
}
if (is_string($value) and class_exists($value)) {
return $this->evalNewClass($value);
}
return $value;
}
protected function evalCallable(callable $value)
{
$args = $this->getMethodParameters(new ReflectionFunction($value));
return call_user_func_array($value, $args);
}
protected function evalNewClass(string $class)
{
$ref = new reflectionClass($class);
$args = $this->getMethodParameters($ref->getConstructor());
return $ref->newInstanceArgs($args);
}
protected function getMethodParameters(ReflectionFunctionAbstract $function)
{
return array_map(function(ReflectionParameter $parameter) {
return $this->get($parameter->getType()->getName());
}, $function->getParameters());
}
}
class App
{
public function __construct(
protected Auth $authWrapper,
protected Request $request,
protected Monolog\Logger $logger,
protected Benchmark $benchmark,
) {}
public function run()
{
header("Access-Control-Allow-Origin: *");
Monolog\ErrorHandler::register($this->logger);
$this->benchmark->start();
Carbon::setLocale(config('app.locale'));
setlocale(LC_TIME, 'es_ES');
try {
$this->authWrapper->isIn();
} catch (PDOException $e) {
$this->logger->error($e);
header('Location: install');
die();
}
$get = $this->request->getQueryParams();
try {
if ($this->authWrapper->isIn()) {
if ((($get['p'] ?? false) !== false or ($get['page'] ?? false) !== false or ($get['m'] ?? false) !== false or ($get['module'] ?? false) !== false)) {
if (($route = route()) !== false) {
echo $route;
} else {
echo view('construccion');
}
} else {
$proyectos = model(Proyecto::class)->findMany();
$dias = [];
$cierres = [];
$pendientes = 0;
$hoy = 0;
foreach ($proyectos as $proyecto) {
$pendientes += $proyecto->cuotasPendientes();
$hoy += $proyecto->cuotasHoy();
foreach ($proyecto->cuotasMes() as $cuota) {
$f = $cuota->pago()->fecha();
if ($f->isoWeekday() == 6 or $f->isoWeekDay() == 7) {
$f = $f->copy()->addDays(2)->startOfWeek();
}
$dia = $f->format('Y-m-d');
if (!isset($dias[$dia])) {
$dias[$dia] = [$proyecto->descripcion => 0];
}
if (!isset($dias[$dia][$proyecto->descripcion])) {
$dias[$dia][$proyecto->descripcion] = 0;
}
$dias[$dia][$proyecto->descripcion] ++;
}
if (count($proyecto->cierres()) > 0) {
$cierres[$proyecto->descripcion] = (object) ['total' => count($proyecto->cierres()),'vigentes' => $proyecto->cierres(3), 'rechazados' => $proyecto->cierres(-1), 'pendientes' => $proyecto->cierres(2)];
}
}
uksort($dias, function($a, $b) {
return strcmp($a, $b);
});
uksort($cierres, function($a, $b) {
return strcmp($a, $b);
});
echo view('home', compact('pendientes', 'hoy', 'dias', 'cierres'));
}
} elseif (($get['p'] ?? false) === 'auth' or ($get['page'] ?? false) === 'auth') {
$route = route();
if ($route !== false) {
echo $route;
} else {
echo view('guest');
}
} else {
echo view('construccion');
echo view('guest');
}
} else {
$proyectos = model(Proyecto::class)->findMany();
$dias = [];
$cierres = [];
$pendientes = 0;
$hoy = 0;
foreach ($proyectos as $proyecto) {
$pendientes += $proyecto->cuotasPendientes();
$hoy += $proyecto->cuotasHoy();
foreach ($proyecto->cuotasMes() as $cuota) {
$f = $cuota->pago()->fecha();
if ($f->isoWeekday() == 6 or $f->isoWeekDay() == 7) {
$f = $f->copy()->addDays(2)->startOfWeek();
}
$dia = $f->format('Y-m-d');
if (!isset($dias[$dia])) {
$dias[$dia] = [$proyecto->descripcion => 0];
}
if (!isset($dias[$dia][$proyecto->descripcion])) {
$dias[$dia][$proyecto->descripcion] = 0;
}
$dias[$dia][$proyecto->descripcion] ++;
}
if (count($proyecto->cierres()) > 0) {
$cierres[$proyecto->descripcion] = (object) ['total' => count($proyecto->cierres()),'vigentes' => $proyecto->cierres(3), 'rechazados' => $proyecto->cierres(-1), 'pendientes' => $proyecto->cierres(2)];
}
}
uksort($dias, function($a, $b) {
return strcmp($a, $b);
});
uksort($cierres, function($a, $b) {
return strcmp($a, $b);
});
echo view('home', compact('pendientes', 'hoy', 'dias', 'cierres'));
} catch (Exception $e) {
$this->logger->warning($e);
die();
} catch (Error $e) {
$this->logger->error($e);
die();
}
} elseif (get('p') == 'auth' or get('page') == 'auth') {
$route = route();
if ($route !== false) {
echo $route;
} else {
echo view('guest');
$this->benchmark->stop();
if (($get['ajax'] ?? false) !== '1' and ($get['p'] ?? false) !== 'ajax' and ($get['p'] ?? false) !== 'informes') {
$this->benchmark->show();
}
} else {
echo view('guest');
}
} catch (Exception $e) {
$logger->warning($e);
echo "";
} catch (Error $e) {
$logger->error($e);
echo "";
}
if (config('app.debug') == 'true') {
if (config('app.benchmark') == 'true') {
$benchmark->time = microtime(true) - $benchmark->time;
$logger->debug("Time {$benchmark->time}");
if (get('ajax') != '1' and get('p') != 'ajax' and get('p') != 'informes') {
echo view('benchmark', compact('benchmark'));
}
}
}
?>
$container = new Container([
Monolog\Logger::class => function() {
return (new Monolog\Logger('global'))
->pushHandler((new Handler\FilterHandler(
(new Handler\RotatingFileHandler('/logs/php.log'))
->setFormatter(new Formatter\LineFormatter(null, null, true)),
Level::Debug,
Level::Notice
)))
->pushHandler((new Handler\FilterHandler(
(new Handler\NativeMailerHandler('jpvial@incoviba.cl', 'Error - Incoviba', 'alert@incoviba.cl'))
->setFormatter(new Formatter\HtmlFormatter()),
Level::Warning,
Level::Emergency
)))
->pushProcessor(new Processor\PsrLogMessageProcessor())
->pushProcessor(new Processor\IntrospectionProcessor())
->pushProcessor(new Processor\HostnameProcessor())
->pushProcessor(new Processor\WebProcessor())
->pushProcessor(new Processor\MemoryPeakUsageProcessor());
},
Request::class => function() {
return Request::createFromGlobals();
},
Auth::class => function() {
return new Auth();
},
Benchmark::class => function(Container $container) {
return new Benchmark($container->get(Monolog\Logger::class), config('app.debug'), config('app.benchmark'));
}
]);
$app = $container->get(App::class);
$app->run();

5
resources/routes/cli.php Normal file
View File

@ -0,0 +1,5 @@
<?php
use App\Command;
$app->add($app->getContainer()->get(Command\Money\Lookup::class));
$app->add($app->getContainer()->get(Command\Money\Get::class));

View File

@ -9,6 +9,9 @@ $folders = [
'setups'
];
$builder = new Builder();
if (isset($__environment)) {
$builder->addDefinitions(['environment' => $__environment]);
}
foreach ($folders as $f) {
$folder = implode(DIRECTORY_SEPARATOR, [
__DIR__,
@ -50,3 +53,5 @@ $app->addErrorMiddleware(true, true, true);
include_once 'database.php';
include_once 'router.php';
return $app;

48
setup/cli.app.php Normal file
View File

@ -0,0 +1,48 @@
<?php
use Psr\Container\ContainerInterface;
use DI\ContainerBuilder;
use Symfony\Component\Console\Application;
require_once 'composer.php';
$builder = new ContainerBuilder();
$files = [
'config',
'setups'
];
foreach ($files as $f) {
$filename = implode(DIRECTORY_SEPARATOR, [
__DIR__,
'cli',
"{$f}.php"
]);
if (!file_exists($filename)) {
continue;
}
$builder->addDefinitions($filename);
}
$app = new class() extends Application
{
protected ContainerInterface $container;
public function getContainer(): ContainerInterface
{
return $this->container;
}
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
return $this;
}
};
$app->setContainer($builder->build());
$filename = implode(DIRECTORY_SEPARATOR, [
__DIR__,
'cli',
'middlewares.php'
]);
if (file_exists($filename)) {
include_once $filename;
}
return $app;

26
setup/cli/config.php Normal file
View File

@ -0,0 +1,26 @@
<?php
return [
'databases' => function() {
$container = new DI\Container([
ORM::DEFAULT_CONNECTION => new DI\Container([
'host' => $_ENV['MYSQL_HOST'],
'database' => $_ENV['MYSQL_DATABASE'],
'username' => $_ENV['MYSQL_USER'],
'password' => $_ENV['MYSQL_PASSWORD']
]),
'remote' => new DI\Container([
'host' => $_ENV['REMOTE_HOST'],
'database' => $_ENV['REMOTE_DATABASE'],
'username' => $_ENV['REMOTE_USER'],
'password' => $_ENV['REMOTE_PASSWORD']
])
]);
if (isset($_ENV['MYSQL_PORT'])) {
$container->get(ORM::DEFAULT_CONNECTION)->set('port', $_ENV['MYSQL_PORT']);
}
if (isset($_ENV['REMOTE_PORT'])) {
$container->get('remote')->set('port', $_ENV['REMOTE_PORT']);
}
return $container;
}
];

View File

@ -0,0 +1,9 @@
<?php
include_once implode(DIRECTORY_SEPARATOR, [
dirname(__FILE__, 3),
'resources',
'routes',
'cli.php'
]);
Monolog\ErrorHandler::register($app->getContainer()->get(Psr\Log\LoggerInterface::class));

43
setup/cli/setups.php Normal file
View File

@ -0,0 +1,43 @@
<?php
use Psr\Container\ContainerInterface;
return [
Psr\Log\LoggerInterface::class => function(ContainerInterface $container) {
return new Monolog\Logger('cli', [
new Monolog\Handler\FilterHandler(new Monolog\Handler\RotatingFileHandler('/logs/cli.debug.log'), Monolog\Level::Debug, Monolog\Level::Notice),
new Monolog\Handler\FilterHandler(new Monolog\Handler\RotatingFileHandler('/logs/cli.error.log'), Monolog\Level::Warning)
], [
new Monolog\Processor\PsrLogMessageProcessor(),
new Monolog\Processor\IntrospectionProcessor(),
new Monolog\Processor\MemoryUsageProcessor(),
new Monolog\Processor\MemoryPeakUsageProcessor()
]);
},
GuzzleHttp\Client::class => function(ContainerInterface $container) {
return new GuzzleHttp\Client([
'base_uri' => "http://{$container->get(App\Service\Remote::class)->getIP()}:8008",
'headers' => [
'Accept' => 'application/json'
]
]);
},
App\Alias\RemoteConnection::class => function(ContainerInterface $container) {
return new App\Alias\RemoteConnection();
},
App\Service\Remote::class => function(ContainerInterface $container) {
return new App\Service\Remote($container->get(App\Alias\RemoteConnection::class));
},
App\Service\Money::class => function(ContainerInterface $container) {
return new App\Service\Money($container->get(GuzzleHttp\Client::class));
},
App\Alias\Connection::class => function(ContainerInterface $container) {
$data = $container->get('databases')->get(ORM::DEFAULT_CONNECTION);
return new App\Alias\Connection(
$data->get('host'),
$data->get('database'),
$data->get('username'),
$data->get('password'),
$data->has('port') ? $data->get('port') : null
);
},
];