Skip to content

Commit

Permalink
Merge pull request #60 from WendellAdriel/feature/after-hook
Browse files Browse the repository at this point in the history
Add after hook for validation
  • Loading branch information
WendellAdriel committed Oct 16, 2023
2 parents 9e3da20 + 26e3019 commit 13bef8e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/ValidatedDTO.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ public function attributes(): array
return [];
}

protected function after(\Illuminate\Validation\Validator $validator): void
{
// Do nothing
}

/**
* Builds the validated data from the given data and the rules.
*
Expand Down Expand Up @@ -84,6 +89,8 @@ protected function isValidData(): bool
$this->attributes()
);

$this->validator->after(fn (\Illuminate\Validation\Validator $validator) => $this->after($validator));

return $this->validator->passes();
}

Expand Down
28 changes: 28 additions & 0 deletions tests/Datasets/NameAfterDTO.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace WendellAdriel\ValidatedDTO\Tests\Datasets;

use Illuminate\Validation\Validator;
use WendellAdriel\ValidatedDTO\Attributes\Rules;
use WendellAdriel\ValidatedDTO\Concerns\EmptyCasts;
use WendellAdriel\ValidatedDTO\Concerns\EmptyDefaults;
use WendellAdriel\ValidatedDTO\Concerns\EmptyRules;
use WendellAdriel\ValidatedDTO\ValidatedDTO;

class NameAfterDTO extends ValidatedDTO
{
use EmptyCasts, EmptyDefaults, EmptyRules;

#[Rules(['required', 'string'])]
public string $first_name;

#[Rules(['required', 'string'])]
public string $last_name;

protected function after(Validator $validator): void
{
$validator->errors()->add('test', 'After test!');
}
}
8 changes: 8 additions & 0 deletions tests/Unit/ValidatedDTOTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use WendellAdriel\ValidatedDTO\Tests\Datasets\MapBeforeValidationDTO;
use WendellAdriel\ValidatedDTO\Tests\Datasets\MapDataDTO;
use WendellAdriel\ValidatedDTO\Tests\Datasets\MappedNameDTO;
use WendellAdriel\ValidatedDTO\Tests\Datasets\NameAfterDTO;
use WendellAdriel\ValidatedDTO\Tests\Datasets\NameDTO;
use WendellAdriel\ValidatedDTO\Tests\Datasets\NullableDTO;
use WendellAdriel\ValidatedDTO\Tests\Datasets\User;
Expand Down Expand Up @@ -60,6 +61,13 @@
->toBeNull();
});

it('handles the after hook when instantiating a ValidatedDTO')
->expect(fn () => new NameAfterDTO([
'first_name' => $this->subject_name,
'last_name' => $this->subject_name,
]))
->throws(ValidationException::class);

it('returns null when trying to access a property that does not exist', function () {
$validatedDTO = new ValidatedDTOInstance(['name' => $this->subject_name]);

Expand Down

0 comments on commit 13bef8e

Please sign in to comment.