feature/cierres (#25)

Varios cambios

Co-authored-by: Juan Pablo Vial <jpvialb@incoviba.cl>
Reviewed-on: #25
This commit is contained in:
2025-07-22 13:18:00 +00:00
parent ba57cad514
commit 307f2ac7d7
418 changed files with 20045 additions and 984 deletions

View File

@ -1,9 +1,6 @@
<?php
namespace Incoviba\Common\Alias;
use Illuminate\Events\Dispatcher;
use Slim\Views\Blade;
class View extends Blade
{
}
class View extends Blade {}

View File

@ -8,9 +8,9 @@ interface Provider
{
/**
* @param string $money_symbol
* @param DateTimeInterface $dateTime
* @param ?DateTimeInterface $dateTime = null
* @return float
* @throws EmptyResponse
*/
public function get(string $money_symbol, DateTimeInterface $dateTime): float;
public function get(string $money_symbol, ?DateTimeInterface $dateTime = null): float;
}

View File

@ -0,0 +1,18 @@
<?php
namespace Incoviba\Common\Ideal;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
abstract class LoggerEnabled implements LoggerAwareInterface
{
public LoggerInterface $logger;
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function getLogger(): LoggerInterface
{
return $this->logger;
}
}

View File

@ -24,6 +24,11 @@ abstract class Repository implements Define\Repository
return $this;
}
public function getConnection(): Define\Connection
{
return $this->connection;
}
public function load(array $data_row): Define\Model
{
$model = $this->create($data_row);
@ -189,7 +194,7 @@ abstract class Repository implements Define\Repository
try {
$this->connection->execute($query, $values);
} catch (PDOException $exception) {
throw new EmptyResult($query, $exception);
throw new EmptyResult($query, $exception, $data);
}
return $this->fetchById($this->getIndex($model));
}
@ -205,10 +210,10 @@ abstract class Repository implements Define\Repository
try {
$result = $this->connection->execute($query, $data)->fetch(PDO::FETCH_ASSOC);
if ($result === false) {
throw new EmptyResult($query);
throw new EmptyResult($query, null, $data);
}
} catch (PDOException $exception) {
throw new EmptyResult($query, $exception);
throw new EmptyResult($query, $exception, $data);
}
return $this->load($result);
}
@ -224,7 +229,7 @@ abstract class Repository implements Define\Repository
try {
$results = $this->connection->execute($query, $data)->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $exception) {
throw new EmptyResult($query, $exception);
throw new EmptyResult($query, $exception, $data);
}
return array_map([$this, 'load'], $results);
}
@ -240,7 +245,7 @@ abstract class Repository implements Define\Repository
try {
$results = $this->connection->execute($query, $data)->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $exception) {
throw new EmptyResult($query, $exception);
throw new EmptyResult($query, $exception, $data);
}
return $results;
}

View File

@ -0,0 +1,56 @@
<?php
namespace Incoviba\Common\Ideal\Service;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction;
abstract class API extends Ideal\Service
{
public function __construct(LoggerInterface $logger)
{
parent::__construct($logger);
}
/**
* @param string|array|null $order
* @return array
*/
abstract public function getAll(null|string|array $order = null): array;
/**
* @param int $id
* @return Define\Model
* @throws ServiceAction\Read
*/
abstract public function get(int $id): Define\Model;
/**
* @param array $data
* @return Define\Model
* @throws ServiceAction\Create
*/
abstract public function add(array $data): Define\Model;
/**
* @param Define\Model $model
* @param array $new_data
* @return Define\Model
* @throws ServiceAction\Update
*/
abstract public function edit(Define\Model $model, array $new_data): Define\Model;
/**
* @param int $id
* @return Define\Model
* @throws ServiceAction\Delete
*/
abstract public function delete(int $id): Define\Model;
/**
* @param Define\Model $model
* @return Define\Model
*/
abstract protected function process(Define\Model $model): Define\Model;
}

View File

@ -0,0 +1,10 @@
<?php
namespace Incoviba\Common\Ideal\Service;
use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
abstract class Repository extends Ideal\Service
{
abstract public function getRepository(): Define\Repository;
}

View File

@ -81,6 +81,9 @@ class Insert extends Ideal\Query implements Define\Query\Insert
if ($value === (int) $value) {
return $value;
}
if (str_starts_with($value, ':')) {
return $value;
}
return "'{$value}'";
}, $this->values)) . ')';
}

View File

@ -64,10 +64,10 @@ class Select extends Ideal\Query implements Define\Query\Select
public function having(array|string $conditions): Select
{
if (is_string($conditions)) {
return $this->addCondition($conditions);
return $this->addHaving($conditions);
}
foreach ($conditions as $condition) {
$this->addCondition($condition);
$this->addHaving($condition);
}
return $this;
}

View File

@ -6,10 +6,15 @@ use Throwable;
class EmptyResult extends Exception
{
public function __construct(public string $query, ?Throwable $previous = null)
public function __construct(public string $query, ?Throwable $previous = null, protected ?array $data = null)
{
$message = "Empty results for {$query}";
$code = 700;
parent::__construct($message, $code, $previous);
}
public function getData(): ?array
{
return $this->data;
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Incoviba\Common\Implement\Exception;
use Throwable;
use Exception;
class HttpException extends Exception
{
public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace Incoviba\Common\Implement\Log\Formatter;
use Throwable;
use Monolog\Formatter\JsonFormatter;
use Monolog\LogRecord;
class PDO extends JsonFormatter
{
public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = true)
{
parent::__construct($batchMode, $appendNewline, $ignoreEmptyContextAndExtra, $includeStacktraces);
}
public function format(LogRecord $record): string
{
if (is_a($record->message, Throwable::class)) {
$exception = $record->message;
$message = $this->normalizeException($exception);
$context = $record->context;
$context['exception'] = $exception;
if ($exception->getPrevious()) {
$context['previous'] = $this->walkException($exception);
}
$new_record = new LogRecord(
$record->datetime,
$record->channel,
$record->level,
json_encode($message),
$context,
$record->extra
);
$record = $new_record;
}
$normalized = $this->normalize($record, $this->maxNormalizeDepth);
return $normalized['message'];
}
protected function walkException(Throwable $exception, int $depth = 0): array
{
$output = [];
$currentDepth = $depth;
while ($previous = $exception->getPrevious() and $currentDepth < $this->maxNormalizeDepth) {
$output []= $this->normalizeException($previous);
}
return $output;
}
}

View File

@ -1,13 +1,13 @@
<?php
namespace Incoviba\Common\Implement\Log;
namespace Incoviba\Common\Implement\Log\Handler;
use PDOStatement;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\LogRecord;
use Monolog\Level;
use Incoviba\Common\Define\Connection;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Level;
use Monolog\LogRecord;
use PDOStatement;
class MySQLHandler extends AbstractProcessingHandler
class MySQL extends AbstractProcessingHandler
{
private bool $initialized = false;
private PDOStatement $statement;
@ -19,9 +19,12 @@ class MySQLHandler extends AbstractProcessingHandler
public function write(LogRecord $record): void
{
if (!$this->initialized) {
if (!$this->checkTableExists()) {
$this->createTable();
}
$this->cleanup();
$this->initialized();
}
$this->cleanup();
$this->statement->execute([
'channel' => $record->channel,
'level' => $record->level->getName(),
@ -35,6 +38,21 @@ class MySQLHandler extends AbstractProcessingHandler
private function initialized(): void
{
$query = <<<QUERY
INSERT INTO monolog (channel, level, message, time, context, extra)
VALUES (:channel, :level, :message, :time, :context, :extra)
QUERY;
$this->statement = $this->connection->getPDO()->prepare($query);
$this->initialized = true;
}
private function checkTableExists(): bool
{
$query = "SHOW TABLES LIKE 'monolog'";
$result = $this->connection->query($query);
return $result->rowCount() > 0;
}
private function createTable(): void
{
$query = <<<QUERY
CREATE TABLE IF NOT EXISTS monolog (
channel VARCHAR(255),
level VARCHAR(100),
@ -45,12 +63,6 @@ CREATE TABLE IF NOT EXISTS monolog (
)
QUERY;
$this->connection->getPDO()->exec($query);
$query = <<<QUERY
INSERT INTO monolog (channel, level, message, time, context, extra)
VALUES (:channel, :level, :message, :time, :context, :extra)
QUERY;
$this->statement = $this->connection->getPDO()->prepare($query);
$this->initialized = true;
}
private function cleanup(): void
{

View File

@ -1,19 +0,0 @@
<?php
namespace Incoviba\Common\Implement\Log;
use Monolog\Formatter\JsonFormatter;
use Monolog\LogRecord;
class PDOFormatter extends JsonFormatter
{
public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = true)
{
parent::__construct($batchMode, $appendNewline, $ignoreEmptyContextAndExtra, $includeStacktraces);
}
public function format(LogRecord $record): string
{
$normalized = $this->normalize($record);
return $normalized['message'];
}
}

View File

@ -0,0 +1,139 @@
<?php
namespace Incoviba\Common\Implement\Log\Processor;
use DateInvalidTimeZoneException;
use DateMalformedStringException;
use DateTimeImmutable;
use DateTimeZone;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Monolog\Formatter;
use Monolog\Handler;
use Monolog\Level;
use Predis;
use Incoviba;
use Throwable;
class ArrayBuilder
{
public function __construct(protected ContainerInterface $container) {}
public function build(array $data): array
{
$handlers = [];
foreach ($data as $handlerData) {
if (in_array($handlerData['handler'], [Handler\StreamHandler::class, Handler\RotatingFileHandler::class,])) {
$params = [
"/logs/{$handlerData['filename']}",
];
if ($handlerData['handler'] === Handler\RotatingFileHandler::class) {
$params []= 10;
}
try {
$formatter = Formatter\LineFormatter::class;
if (array_key_exists('formatter', $handlerData)) {
$formatter = $handlerData['formatter'];
}
$handler = new $handlerData['handler'](...$params)
->setFormatter($this->container->get($formatter));
} catch (NotFoundExceptionInterface | ContainerExceptionInterface $exception) {
$this->log($exception, ['handlerData' => $handlerData]);
continue;
}
} elseif ($handlerData['handler'] === Incoviba\Common\Implement\Log\Handler\MySQL::class) {
try {
$params = [
$this->container->get(Incoviba\Common\Define\Connection::class)
];
$formatter = Incoviba\Common\Implement\Log\Formatter\PDO::class;
if (array_key_exists('formatter', $handlerData)) {
$formatter = $handlerData['formatter'];
}
$handler = new $handlerData['handler'](...$params)
->setFormatter($this->container->get($formatter));
} catch (NotFoundExceptionInterface | ContainerExceptionInterface $exception) {
$this->log($exception, ['handlerData' => $handlerData]);
continue;
}
} elseif ($handlerData['handler'] === Handler\RedisHandler::class) {
try {
$params = [
$this->container->get(Predis\ClientInterface::class),
"logs:{$handlerData['name']}"
];
} catch (NotFoundExceptionInterface | ContainerExceptionInterface $exception) {
$this->log($exception, ['handlerData' => $handlerData]);
continue;
}
$handler = new $handlerData['handler'](...$params);
}
if (!isset($handler)) {
$this->log("Invalid handler", ['handlerData' => $handlerData]);
continue;
}
$params = [
$handler,
];
if (is_array($handlerData['levels'])) {
foreach ($handlerData['levels'] as $level) {
$params []= $level;
}
} else {
$params []= $handlerData['levels'];
$params []= Level::Emergency;
}
$params []= false;
$handlers []= new Handler\FilterHandler(...$params);
}
return $handlers;
}
protected function log(string|Throwable $message, array $context = []): void
{
try {
$dateTime = new DateTimeImmutable('now', new DateTimeZone($_ENV['TZ'] ?? 'America/Santiago'));
} catch (DateMalformedStringException | DateInvalidTimeZoneException $exception) {
$dateTime = new DateTimeImmutable();
}
if (is_a($message, Throwable::class)) {
$exception = $message;
$message = $exception->getMessage();
}
$context = json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($context === false) {
$context = '[]';
}
$extra = [];
$extra['from'] = __FILE__;
if (isset($exception)) {
$extra['file'] = $exception->getFile();
$extra['line'] = $exception->getLine();
$extra['trace'] = $exception->getTrace();
}
$extra = json_encode($extra, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$code = 0;
if (isset($exception)) {
$code = $exception->getCode();
}
if ($extra === false) {
$extra = '[]';
}
$output = "[{$dateTime->format('Y-m-d H:i:s P')}] [{$code}] {$message} {$context} {$extra}";
$filename = '/logs/error.json';
$fileContents = [];
if (file_exists($filename)) {
$fileContents = file_get_contents($filename);
$fileContents = json_decode($fileContents, true);
if ($fileContents === false) {
$fileContents = [];
}
}
$fileContents[$dateTime->getTimestamp()] = $output;
$fileContents = json_encode($fileContents, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($fileContents === false) {
$fileContents = '[]';
}
file_put_contents($filename, $fileContents);
}
}

View File

@ -1,11 +1,11 @@
<?php
namespace Incoviba\Common\Implement\Log;
namespace Incoviba\Common\Implement\Log\Processor;
use Incoviba\Service;
use Monolog\LogRecord;
use Monolog\Processor\ProcessorInterface;
use Incoviba\Service;
class UserProcessor implements ProcessorInterface
class User implements ProcessorInterface
{
public function __construct(protected Service\Login $loginService) {}
public function __invoke(LogRecord $record): LogRecord