Skip to content

refactor(validator): improve SOLID principles implementation and add … #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
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
20 changes: 10 additions & 10 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions src/Processor/AbstractValidatorProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ abstract class AbstractValidatorProcessor implements Processor, ValidatableProce
protected bool $isValid = true;
protected string $errorKey = '';

/**
* Reset the processor's state back to its initial values.
*/
public function reset(): void
{
$this->isValid = true;
$this->errorKey = '';
}

protected function setInvalid(string $errorKey): void
{
$this->isValid = false;
Expand Down
13 changes: 4 additions & 9 deletions src/Processor/DefaultValidationResultProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,26 @@
namespace KaririCode\Validator\Processor;

use KaririCode\PropertyInspector\AttributeHandler;
use KaririCode\Validator\Contract\ValidationResult as ValidationResultContract;
use KaririCode\Validator\Contract\ValidationResultProcessor;
use KaririCode\Validator\ValidationResult;

class DefaultValidationResultProcessor implements ValidationResultProcessor
{
public function __construct(
private ValidationResultContract $result = new ValidationResult()
) {
}

public function process(AttributeHandler $handler): ValidationResult
{
$result = new ValidationResult();
$processedValues = $handler->getProcessedPropertyValues();
$errors = $handler->getProcessingResultErrors();

foreach ($processedValues as $property => $data) {
$this->result->setValidatedData($property, $data['value']);
$result->setValidatedData($property, $data['value']);

if (isset($errors[$property])) {
$this->addPropertyErrors($this->result, $property, $errors[$property]);
$this->addPropertyErrors($result, $property, $errors[$property]);
}
}

return $this->result;
return $result;
}

private function addPropertyErrors(
Expand Down
2 changes: 2 additions & 0 deletions src/Processor/Input/EmailValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public function process(mixed $input): mixed
return $input;
}

$input = trim($input);

if (false === filter_var($input, FILTER_VALIDATE_EMAIL)) {
$this->setInvalid('invalidFormat');
}
Expand Down
28 changes: 24 additions & 4 deletions src/ValidationResult.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,35 @@ class ValidationResult implements ValidationResultContract
{
private array $errors = [];
private array $validatedData = [];
private array $errorHashes = [];

/**
* Reset all validation state.
*
* Clears all errors, validation data, and error hashes,
* returning the ValidationResult to its initial state.
*/
public function reset(): void
{
$this->errors = [];
$this->validatedData = [];
$this->errorHashes = [];
}

public function addError(string $property, string $errorKey, string $message): void
{
if (!isset($this->errors[$property])) {
$this->errors[$property] = [];
$this->errorHashes[$property] = [];
}

// Avoid adding duplicate errors
foreach ($this->errors[$property] as $error) {
if ($error['errorKey'] === $errorKey) {
return;
}
$hash = md5($errorKey . $message);
if (isset($this->errorHashes[$property][$hash])) {
return;
}

$this->errorHashes[$property][$hash] = true;
$this->errors[$property][] = [
'errorKey' => $errorKey,
'message' => $message,
Expand Down Expand Up @@ -58,4 +73,9 @@ public function toArray(): array
'validatedData' => $this->validatedData,
];
}

public function __destruct()
{
$this->reset();
}
}
17 changes: 7 additions & 10 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,29 @@
use KaririCode\PropertyInspector\AttributeHandler;
use KaririCode\PropertyInspector\Utility\PropertyInspector;
use KaririCode\Validator\Attribute\Validate;
use KaririCode\Validator\Contract\ValidationResultProcessor;
use KaririCode\Validator\Processor\DefaultValidationResultProcessor;

class Validator implements ValidatorContract
{
private const IDENTIFIER = 'validator';

private ProcessorBuilder $builder;
private PropertyInspector $propertyInspector;
private AttributeHandler $attributeHandler;

public function __construct(
private readonly ProcessorRegistry $registry,
private readonly ValidationResultProcessor $resultProcessor = new DefaultValidationResultProcessor()
) {
$this->builder = new ProcessorBuilder($this->registry);
$this->attributeHandler = new AttributeHandler(self::IDENTIFIER, $this->builder);
$this->propertyInspector = new PropertyInspector(
new AttributeAnalyzer(Validate::class)
);
}

public function validate(mixed $object): ValidationResult
{
$handler = $this->propertyInspector->inspect($object, $this->attributeHandler);
$propertyInspector = new PropertyInspector(
new AttributeAnalyzer(Validate::class)
);
$attributeHandler = new AttributeHandler(self::IDENTIFIER, $this->builder);
$resultProcessor = new DefaultValidationResultProcessor();
$handler = $propertyInspector->inspect($object, $attributeHandler);

return $this->resultProcessor->process($handler);
return $resultProcessor->process($handler);
}
}
11 changes: 8 additions & 3 deletions tests/Attribute/ValidateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function testConstructorFiltersInvalidProcessors(): void
$expectedProcessors = ['required', 'email'];
$validate = new Validate($processors);

$this->assertEquals($expectedProcessors, $validate->getProcessors());
$this->assertEquals($expectedProcessors, array_values($validate->getProcessors()));
}

public function testConstructorWithEmptyProcessors(): void
Expand Down Expand Up @@ -89,14 +89,19 @@ public static function validProcessorsProvider(): array
[
'length' => ['minLength' => 3, 'maxLength' => 20],
],
['length'],
[
'length' => ['minLength' => 3, 'maxLength' => 20],
],
],
'mixed processors' => [
[
'required',
'email' => ['message' => 'Invalid email'],
],
['required', 'email'],
[
'required',
'email' => ['message' => 'Invalid email'],
],
],
];
}
Expand Down
34 changes: 1 addition & 33 deletions tests/ValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use KaririCode\Contract\Processor\ProcessorRegistry;
use KaririCode\Validator\Attribute\Validate;
use KaririCode\Validator\Contract\ValidationResultProcessor;
use KaririCode\Validator\Processor\Input\EmailValidator;
use KaririCode\Validator\Processor\Logic\RequiredValidator;
use KaririCode\Validator\ValidationResult;
Expand All @@ -17,21 +16,19 @@
class ValidatorTest extends TestCase
{
private ProcessorRegistry|MockObject $registry;
private ValidationResultProcessor|MockObject $resultProcessor;
private Validator $validator;

protected function setUp(): void
{
$this->registry = $this->createMock(ProcessorRegistry::class);
$this->resultProcessor = $this->createMock(ValidationResultProcessor::class);

$this->registry->method('get')
->willReturnMap([
['validator', 'required', new RequiredValidator()],
['validator', 'email', new EmailValidator()],
]);

$this->validator = new Validator($this->registry, $this->resultProcessor);
$this->validator = new Validator($this->registry);
}

public function testValidateWithValidObject(): void
Expand All @@ -44,11 +41,6 @@ public function testValidateWithValidObject(): void
$expectedResult = new ValidationResult();
$expectedResult->setValidatedData('email', 'walmir.silva@example.com');

$this->resultProcessor
->expects($this->once())
->method('process')
->willReturn($expectedResult);

$result = $this->validator->validate($testObject);

$this->assertFalse($result->hasErrors());
Expand All @@ -65,11 +57,6 @@ public function testValidateWithInvalidObject(): void
$resultWithErrors = new ValidationResult();
$resultWithErrors->addError('email', 'invalidFormat', 'Invalid email format');

$this->resultProcessor
->expects($this->once())
->method('process')
->willReturn($resultWithErrors);

$result = $this->validator->validate($testObject);

$this->assertTrue($result->hasErrors());
Expand All @@ -82,13 +69,6 @@ public function testValidateWithNoAttributes(): void
public string $name = 'Test';
};

$emptyResult = new ValidationResult();

$this->resultProcessor
->expects($this->once())
->method('process')
->willReturn($emptyResult);

$result = $this->validator->validate($testObject);

$this->assertFalse($result->hasErrors());
Expand All @@ -99,13 +79,6 @@ public function testValidateWithNullObject(): void
{
$testObject = new \stdClass();

$emptyResult = new ValidationResult();

$this->resultProcessor
->expects($this->once())
->method('process')
->willReturn($emptyResult);

$result = $this->validator->validate($testObject);

$this->assertFalse($result->hasErrors());
Expand All @@ -128,11 +101,6 @@ public function testValidateWithMultipleProperties(): void
$multiPropertyResult->setValidatedData('name', 'Walmir');
$multiPropertyResult->setValidatedData('email', 'walmir.silva@example.com');

$this->resultProcessor
->expects($this->once())
->method('process')
->willReturn($multiPropertyResult);

$result = $this->validator->validate($testObject);

$this->assertFalse($result->hasErrors());
Expand Down
Loading
Loading