Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 14 additions & 18 deletions lib/Validations.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@
*
* Available options:
* @phpstan-type ValidateNumericOptions array{
* message?: string|null,
* allow_blank: bool,
* allow_null:bool,
* only_integer?: bool,
* even?: bool,
* off?: bool,
Expand All @@ -57,8 +60,6 @@
* equal_to?: int|float,
* less_than?: int|float,
* less_than_or_equal_to:int|float,
* allow_blank: bool,
* allow_null:bool,
* }
* @phpstan-type ValidateLengthOptions array{
* is?: int,
Expand All @@ -82,10 +83,10 @@
* within?: list<string>
* }
* @phpstan-type ValidateFormatOptions array{
* with: string,
* message?: string|null,
* allow_blank?:bool,
* allow_null?: bool
* allow_null?: bool,
* with: string,
* }
*/
class Validations
Expand All @@ -97,7 +98,7 @@ class Validations
private Model $model;

/**
* @var array<string>
* @var array<string, ValidationOptions>
*/
private array $validators = [];
private ValidationErrors $errors;
Expand Down Expand Up @@ -138,12 +139,8 @@ public function __construct(Model $model)
$this->model = $model;
$this->errors = new ValidationErrors($this->model);
$this->klass = Reflections::instance()->get(get_class($this->model));
/** @var array<string,string> $validators */
$validators = array_intersect(
array_keys($this->klass->getStaticProperties()),
self::$VALIDATION_FUNCTIONS
);
$this->validators = $validators;

$this->validators = array_intersect_key($this->klass->getStaticProperties(), array_flip(self::$VALIDATION_FUNCTIONS));
}

public function get_errors(): ValidationErrors
Expand All @@ -159,9 +156,7 @@ public function get_errors(): ValidationErrors
public function rules(): array
{
$data = [];
foreach ($this->validators as $validate) {
$attrs = $this->klass->getStaticPropertyValue($validate);

foreach ($this->validators as $validate => $attrs) {
foreach (wrap_values_in_arrays($attrs) as $field => $attr) {
$data[$field] ??= [];
$attr['validator'] = $validate;
Expand All @@ -180,8 +175,11 @@ public function rules(): array
*/
public function validate(): ValidationErrors
{
foreach ($this->validators as $validate) {
$values = $this->klass->getStaticPropertyValue($validate);
foreach ($this->validators as $validate => $values) {
assert(
in_array($validate, self::$VALIDATION_FUNCTIONS),
new \Exception('Unknown validator'));

$definition = wrap_values_in_arrays($values);
switch ($validate) {
case 'validates_presence_of':
Expand All @@ -205,8 +203,6 @@ public function validate(): ValidationErrors
case 'validates_numericality_of':
$this->validates_numericality_of($definition);
break;
default:
throw new \Exception('Unknown validator');
}
}

Expand Down