HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux Bradford-Sitios 6.14.0-1017-azure #17~24.04.1-Ubuntu SMP Mon Dec 1 20:10:50 UTC 2025 x86_64
User: www-data (33)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
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;
    }
}