<?php

namespace App\Support;

use Illuminate\Database\QueryException;

/** 识别数据库唯一约束冲突（PostgreSQL / SQLite / MySQL）。 */
final class DatabaseUniqueViolation
{
    public static function matches(QueryException $e): bool
    {
        $sqlState = (string) $e->getCode();
        $errorInfo = $e->errorInfo ?? null;
        $driverCode = is_array($errorInfo) ? (int) ($errorInfo[1] ?? 0) : 0;

        if ($sqlState === '23505' || $sqlState === '23000' || $sqlState === '19') {
            return true;
        }

        if ($driverCode === 19 || $driverCode === 1062) {
            return true;
        }

        return stripos($e->getMessage(), 'unique') !== false;
    }
}