File: /var/www/api_matriculas/app/Repositories/WebhookRepository.php
<?php
namespace App\Repositories;
use App\Models\WebhookLog;
use Exception;
class WebhookRepository
{
public function getAll($limit = null)
{
$query = WebhookLog::orderBy('created_at', 'desc');
if($limit > 0){
$query->limit($limit);
}
return $query->get();
}
public function getById($id)
{
$register = WebhookLog::find($id);
if (!$register) {
throw new Exception("Webhook log no existe", 404);
}
return $register;
}
public function create(array $data)
{
return WebhookLog::create([
'origin' => $data['origin'] ?? 'DESCONOCIDO',
'integration_type' => $data['integration_type'] ?? null,
'event_type' => $data['event_type'] ?? null,
'external_id' => $data['external_id'] ?? null,
'internal_id' => $data['internal_id'] ?? null,
'event_code' => $data['code'] ?? null,
'status_code' => $data['status_code'] ?? $data['statusCode'] ?? null,
'reason' => $data['reason'] ?? null,
'payload' => $this->encodeIfNeeded($data['payload'] ?? null),
'headers' => $this->encodeIfNeeded($data['headers'] ?? null),
]);
}
/**
* Codifica solo si el valor es un array u objeto.
* Si ya es string o null, lo retorna tal cual.
*/
private function encodeIfNeeded($value): ?string
{
if (is_null($value)) {
return null;
}
// Evita doble codificación si ya es JSON válido
if (is_string($value)) {
json_decode($value);
if (json_last_error() === JSON_ERROR_NONE) {
return $value;
}
}
if (is_array($value) || is_object($value)) {
return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
return (string) $value;
}
}