216 lines
8.5 KiB
PHP
216 lines
8.5 KiB
PHP
<?php
|
||
|
||
namespace App\Support\Legacy\Concerns;
|
||
|
||
use Illuminate\Support\Carbon;
|
||
use Illuminate\Support\Facades\Validator;
|
||
use Illuminate\Validation\ValidationException;
|
||
|
||
/**
|
||
* Logika isian biodata yang dipakai bersama StudentBiodata dan EmployeeBiodata: bentuk baku nilai kolom, nilai isian dan
|
||
* teks tampil satu bagian, serta validasi yang hanya memeriksa isian yang berubah (data lama boleh tidak seragam).
|
||
*
|
||
* Isian bagian: name (kunci JSON dan kolom), label, type (text|textarea|email|date|number|select), max, min, lookup (nama
|
||
* pilihan untuk select), required, wide, alnum, digits, notnull (kolom teks NOT NULL: kosong ditulis ''), zero (kode 0 adalah
|
||
* nilai nyata, bukan "tidak diisi"), placeholder, affix (front|back: gelar depan/belakang; di formulir ditulis tanpa koma dan
|
||
* spasi pemisah, DB lama menyimpannya sebagai "Dr. " dan ", M.Pd" sehingga pemisah ditambahkan saat menulis).
|
||
*/
|
||
trait BiodataFields
|
||
{
|
||
/**
|
||
* Pilihan select (kode => label) menurut nama lookup.
|
||
*
|
||
* @return array<string, array<int, string>>
|
||
*/
|
||
abstract public function lookups(): array;
|
||
|
||
/**
|
||
* Nilai kolom dalam bentuk baku agar dua nilai bisa dibandingkan: teks dipangkas (kosong = null), tanggal Y-m-d,
|
||
* angka integer, pilihan integer (kosong = 0 pada pilihan yang punya kode 0, selain itu null).
|
||
*
|
||
* @param array<string, mixed> $field
|
||
* @param array<string, array<int, string>> $lookups
|
||
*/
|
||
protected function normalize(array $field, mixed $value, array $lookups): string|int|null
|
||
{
|
||
$type = $field['type'] ?? 'text';
|
||
$text = is_scalar($value) ? trim((string) $value) : '';
|
||
|
||
// Pilihan tanpa kode 0: nilai kosong atau 0 di DB berarti belum diisi (null).
|
||
$none = $type === 'select' && ! isset($lookups[$field['lookup']][0]);
|
||
|
||
return match ($type) {
|
||
'select' => $text === '' || ($none && (int) $text === 0) ? ($none ? null : 0) : (int) $text,
|
||
'number' => $text === '' ? null : (int) $text,
|
||
'date' => $text === '' ? null : substr($text, 0, 10),
|
||
default => ($text = self::stripAffix($field, $text)) === '' ? null : $text,
|
||
};
|
||
}
|
||
|
||
/** Buang pemisah gelar (koma dan spasi di depan gelar belakang, spasi pada gelar depan) agar nilai konsisten. */
|
||
private static function stripAffix(array $field, string $text): string
|
||
{
|
||
return match ($field['affix'] ?? null) {
|
||
'back' => trim(ltrim($text, " ,\t")),
|
||
'front' => trim($text),
|
||
default => $text,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Nilai siap tulis ke kolom: gelar belakang diberi awalan ", " dan gelar depan spasi penutup (konvensi DB lama);
|
||
* kolom teks NOT NULL yang kosong ditulis ''.
|
||
*
|
||
* @param array<string, mixed> $field
|
||
*/
|
||
private function stored(array $field, string|int|null $value): string|int|null
|
||
{
|
||
if ($value === null) {
|
||
return ($field['notnull'] ?? false) ? '' : null;
|
||
}
|
||
|
||
return match ($field['affix'] ?? null) {
|
||
'back' => ', '.$value,
|
||
'front' => $value.' ',
|
||
default => $value,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Nilai isian (untuk formulir) dan teks tampil satu bagian.
|
||
*
|
||
* @param array<string, mixed> $section
|
||
* @param array<string, array<int, string>> $lookups
|
||
* @return array{fields: list<array<string, mixed>>, values: array<string, mixed>, display: array<string, string>}
|
||
*/
|
||
protected function present(array $section, object $row, array $lookups): array
|
||
{
|
||
$fields = [];
|
||
$values = [];
|
||
$display = [];
|
||
|
||
foreach ($section['fields'] as $field) {
|
||
$name = $field['name'];
|
||
$value = $this->normalize($field, $row->{$name} ?? null, $lookups);
|
||
|
||
if (($field['type'] ?? '') === 'select') {
|
||
$options = $lookups[$field['lookup']];
|
||
if ($value === null) {
|
||
// Kolom boleh kosong dan pilihannya tidak punya kode 0: tampil pilihan kosong.
|
||
$field['blank'] = true;
|
||
$values[$name] = '';
|
||
$display[$name] = '–';
|
||
} else {
|
||
// Kode yang tidak ada di tabel referensi tetap tampil dan bisa dipertahankan.
|
||
$options += isset($options[$value]) ? [] : [$value => 'Kode '.$value];
|
||
$values[$name] = $value;
|
||
$display[$name] = $value === 0 && ! ($field['zero'] ?? false) ? '–' : $options[$value];
|
||
}
|
||
$field['options'] = $options;
|
||
} else {
|
||
$values[$name] = $value ?? '';
|
||
$display[$name] = match (true) {
|
||
$value === null => '–',
|
||
($field['type'] ?? '') === 'date' => Carbon::parse($value)->locale('id')->isoFormat('D MMMM YYYY'),
|
||
default => (string) $value,
|
||
};
|
||
}
|
||
|
||
$fields[] = $field;
|
||
}
|
||
|
||
return ['fields' => $fields, 'values' => $values, 'display' => $display];
|
||
}
|
||
|
||
/**
|
||
* Kolom yang berubah dari satu bagian (kolom => nilai baru siap tulis). Isian yang tidak dikirim dilewati.
|
||
*
|
||
* @param list<array<string, mixed>> $fields
|
||
* @param array<string, mixed> $input
|
||
* @param array<string, array<int, string>> $lookups
|
||
* @return array<string, string|int|null>
|
||
*/
|
||
protected function changes(array $fields, object $row, array $input, array $lookups): array
|
||
{
|
||
$changes = [];
|
||
foreach ($fields as $field) {
|
||
$name = $field['name'];
|
||
if (! array_key_exists($name, $input)) {
|
||
continue;
|
||
}
|
||
$new = $this->normalize($field, $input[$name], $lookups);
|
||
if ($new !== $this->normalize($field, $row->{$name} ?? null, $lookups)) {
|
||
$changes[$name] = $this->stored($field, $new);
|
||
}
|
||
}
|
||
|
||
return $changes;
|
||
}
|
||
|
||
/**
|
||
* Periksa isian satu bagian. Isian yang nilainya sama dengan yang tersimpan (dan tidak kosong) tidak diperiksa bentuknya
|
||
* dan tidak ikut dikembalikan; isian wajib yang kosong selalu diperiksa.
|
||
*
|
||
* @param list<array<string, mixed>> $fields
|
||
* @param array<string, mixed> $input
|
||
* @param array<string, list<mixed>> $extraRules aturan tambahan per isian
|
||
* @return array<string, mixed>
|
||
*
|
||
* @throws ValidationException
|
||
*/
|
||
protected function validateFields(array $fields, object $row, array $input, array $extraRules = []): array
|
||
{
|
||
$lookups = $this->lookups();
|
||
$rules = $this->rulesFor($fields, $lookups);
|
||
|
||
foreach ($fields as $field) {
|
||
$name = $field['name'];
|
||
if (array_key_exists($name, $input)) {
|
||
$new = $this->normalize($field, $input[$name], $lookups);
|
||
if ($new !== null && $new === $this->normalize($field, $row->{$name} ?? null, $lookups)) {
|
||
unset($rules[$name]);
|
||
|
||
continue;
|
||
}
|
||
}
|
||
if (isset($extraRules[$name])) {
|
||
$rules[$name] = array_merge($rules[$name], $extraRules[$name]);
|
||
}
|
||
}
|
||
|
||
$attributes = collect($fields)->mapWithKeys(fn (array $f): array => [$f['name'] => mb_strtolower($f['label'])])->all();
|
||
|
||
return Validator::make($input, $rules, [], $attributes)->validate();
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string, mixed>> $fields
|
||
* @param array<string, array<int, string>> $lookups
|
||
* @return array<string, list<string>>
|
||
*/
|
||
private function rulesFor(array $fields, array $lookups): array
|
||
{
|
||
$rules = [];
|
||
|
||
foreach ($fields as $field) {
|
||
$type = $field['type'] ?? 'text';
|
||
$base = ($field['required'] ?? false) ? ['required'] : ['nullable'];
|
||
|
||
$rules[$field['name']] = array_merge($base, match (true) {
|
||
$type === 'select' => ['integer', 'in:'.implode(',', array_keys($lookups[$field['lookup']]))],
|
||
$type === 'number' => ['integer', 'min:'.($field['min'] ?? 0), 'max:'.($field['max'] ?? 99)],
|
||
$type === 'date' => ['date_format:Y-m-d', 'before_or_equal:today'],
|
||
$type === 'email' => ['string', 'email', 'max:'.$field['max']],
|
||
default => array_values(array_filter([
|
||
'string',
|
||
'max:'.$field['max'],
|
||
($field['alnum'] ?? false) ? 'regex:/^[0-9A-Za-z]+$/' : null,
|
||
($field['digits'] ?? false) ? 'regex:/^[0-9]{4}$/' : null,
|
||
])),
|
||
});
|
||
}
|
||
|
||
return $rules;
|
||
}
|
||
}
|