63 lines
1.7 KiB
PHP
63 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Rules;
|
|
|
|
use Closure;
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class ValidSql implements ValidationRule
|
|
{
|
|
/**
|
|
* Run the validation rule.
|
|
*
|
|
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
|
|
*/
|
|
public function validate(string $attribute, mixed $value, Closure $fail): void
|
|
{
|
|
$sql = trim($value);
|
|
|
|
if (empty($sql)) {
|
|
$fail('Query tidak boleh kosong.');
|
|
return;
|
|
}
|
|
|
|
if (!str_starts_with(strtolower($sql), 'select')) {
|
|
$fail('Query harus diawali dengan SELECT.');
|
|
return;
|
|
}
|
|
|
|
$forbiddenCommands = ['insert', 'update', 'delete', 'drop', 'alter', 'create', 'truncate', 'replace', 'grant', 'revoke'];
|
|
foreach ($forbiddenCommands as $command) {
|
|
if (stripos($sql, $command) !== false) {
|
|
$fail("Query tidak boleh mengandung perintah '$command'.");
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (strpos($sql, ';') !== false) {
|
|
$fail('Query tidak boleh mengandung multiple statements.');
|
|
return;
|
|
}
|
|
|
|
$pattern = '/^select\s+.+\s+from\s+\w+/i';
|
|
if (!preg_match($pattern, $sql)) {
|
|
$fail('Query tidak memiliki format SQL yang valid.');
|
|
return;
|
|
}
|
|
|
|
// try {
|
|
// DB::beginTransaction();
|
|
|
|
// $wrapped = "SELECT * FROM ({$sql}) as x LIMIT 1";
|
|
|
|
// DB::select($wrapped);
|
|
|
|
// DB::rollBack();
|
|
// } catch (\Throwable $e) {
|
|
// DB::rollBack();
|
|
// $fail("Query tidak valid: " . $e->getMessage());
|
|
// }
|
|
}
|
|
}
|