validation
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
<?php namespace Lucent\Core\Record;
|
||||
|
||||
use Lucent\Core\Data\RecordError;
|
||||
use Lucent\Core\Data\RecordField;
|
||||
use Lucent\Core\Data\RecordMode;
|
||||
use Lucent\Core\Schema\Data\Field;
|
||||
|
||||
class RecordValidationModule
|
||||
{
|
||||
/**
|
||||
* Validates a record against a schema.
|
||||
*
|
||||
* @param string[] $locales
|
||||
* @param Field[] $schemaFields
|
||||
* @param RecordField[] $recordFields
|
||||
* @return RecordError[]
|
||||
*/
|
||||
public static function validate(
|
||||
array $locales,
|
||||
array $schemaFields,
|
||||
array $recordFields,
|
||||
): array {
|
||||
$errors = [];
|
||||
foreach ($schemaFields as $schemaField) {
|
||||
$res = static::validateField("main", $schemaField, $recordFields);
|
||||
$errors = array_merge($errors, $res);
|
||||
if ($schemaField->translatable) {
|
||||
foreach ($locales as $locale) {
|
||||
$res = static::validateField(
|
||||
$locale["id"],
|
||||
$schemaField,
|
||||
$recordFields,
|
||||
);
|
||||
$errors = array_merge($errors, $res);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return collect($errors)
|
||||
->filter(fn($err) => $err !== null)
|
||||
->values()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param Field $schemaField
|
||||
* @param RecordField[] $recordFields
|
||||
* @return array
|
||||
*/
|
||||
public static function validateField(
|
||||
string $locale,
|
||||
Field $schemaField,
|
||||
array $recordFields,
|
||||
): array {
|
||||
// General Validations
|
||||
$error = static::validateRequired($locale, $schemaField, $recordFields);
|
||||
// Type specific
|
||||
|
||||
return collect([$error])
|
||||
->filter(fn($err) => $err !== null)
|
||||
->values()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param Field $schemaField
|
||||
* @param RecordField[] $recordFields
|
||||
* @return ?RecordError
|
||||
*/
|
||||
public static function validateRequired(
|
||||
string $locale,
|
||||
Field $schemaField,
|
||||
array $recordFields,
|
||||
): ?RecordError {
|
||||
if ($schemaField->required === false) {
|
||||
return null;
|
||||
}
|
||||
$recordField = collect($recordFields)->first(
|
||||
fn(RecordField $field) => $field->id === $schemaField->id &&
|
||||
$field->locale === $locale &&
|
||||
$field->mode === RecordMode::DRAFT,
|
||||
);
|
||||
|
||||
if (empty($recordField) || empty($recordField->value)) {
|
||||
return new RecordError(
|
||||
$schemaField->id,
|
||||
$locale,
|
||||
"This field is required",
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user