Skip to content
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
18 changes: 18 additions & 0 deletions src/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,24 @@ public function has(string $propertyName): bool
return array_key_exists($propertyName, $this->global);
}

public function push(string $propertyName, mixed $value): void
{
if (! $this->has($propertyName)) {
$this->global[$propertyName] = [];
}

$this->global[$propertyName][] = $value;
}

public function pop(string $propertyName): mixed
{
if (! $this->has($propertyName)) {
return null;
}

return array_pop($this->global[$propertyName]);
}

public function getAll(): array
{
return $this->global;
Expand Down
14 changes: 8 additions & 6 deletions src/ErrorInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,17 @@

use Attributes\Validation\Exceptions\ValidationException;
use Exception;
use Respect\Validation\Exceptions\NestedValidationException as RespectNestedValidationException;

class ErrorInfo
{
private Context $context;

private array $errors = [];

private bool $rawExceptions;

public function __construct(Context $context, bool $rawExceptions = false)
public function __construct(Context $context)
{
$this->context = $context;
$this->rawExceptions = $rawExceptions;
}

public function getErrors(): array
Expand All @@ -62,7 +60,7 @@ public function hasErrors(): bool
*/
public function addError(Exception|string $error): void
{
$propertyPath = $this->context->getOptional('propertyPath', []);
$propertyPath = $this->context->getOptional('internal.currentProperty', []);
$errors = &$this->errors;
foreach ($propertyPath as $property) {
if (! isset($errors[$property])) {
Expand All @@ -71,7 +69,11 @@ public function addError(Exception|string $error): void

$errors = &$errors[$property];
}
$errors[] = $this->rawExceptions || is_string($error) ? $error : $error->getMessage();
if ($error instanceof RespectNestedValidationException) {
$errors += array_values($error->getMessages());
} else {
$errors[] = is_string($error) ? $error : $error->getMessage();
}

if ($this->context->get('option.stopFirstError')) {
if (! is_string($error)) {
Expand Down
9 changes: 9 additions & 0 deletions src/Exceptions/ContinueValidationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

namespace Attributes\Validation\Exceptions;

use Exception;

final class ContinueValidationException extends Exception {}
7 changes: 7 additions & 0 deletions src/Exceptions/StopValidationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

declare(strict_types=1);

namespace Attributes\Validation\Exceptions;

class StopValidationException extends BaseException {}
20 changes: 17 additions & 3 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace Attributes\Validation;

use Attributes\Validation\Exceptions\ContextPropertyException;
use Attributes\Validation\Exceptions\ContinueValidationException;
use Attributes\Validation\Exceptions\StopValidationException;
use Attributes\Validation\Exceptions\ValidationException;
use Attributes\Validation\Validators\AttributesValidator;
use Attributes\Validation\Validators\ChainValidator;
Expand Down Expand Up @@ -32,7 +34,7 @@ public function __construct(?PropertyValidator $validator = null, bool $stopFirs
$this->validator = $this->context->getOptional(PropertyValidator::class, $validator) ?? $this->getDefaultPropertyValidator();
$this->context->set(PropertyValidator::class, $this->validator);

$factory = $this->context->getOptional(Factory::class, new Factory);
$factory = $this->context->getOptional(Factory::class) ?: new Factory;
Factory::setDefaultInstance(
$factory
->withRuleNamespace('Attributes\\Validation\\RulesExtractors\\Rules')
Expand Down Expand Up @@ -65,16 +67,19 @@ public function validate(array $data, string|object $model): object

$validModel = is_string($model) ? new $model : $model;
$reflectionClass = new ReflectionClass($validModel);
$errorInfo = new ErrorInfo($this->context);
$this->context->set(ErrorInfo::class, $errorInfo);
$errorInfo = $this->context->getOptional(ErrorInfo::class) ?: new ErrorInfo($this->context);
$this->context->set(ErrorInfo::class, $errorInfo, override: true);
foreach ($reflectionClass->getProperties() as $reflectionProperty) {
$propertyName = $reflectionProperty->getName();
$this->context->push('internal.currentProperty', $propertyName);

if (! array_key_exists($propertyName, $data)) {
if (! $reflectionProperty->isInitialized($validModel)) {
$errorInfo->addError("Missing required property '$propertyName'");
}

$this->context->pop('internal.currentProperty');

continue;
}

Expand All @@ -86,7 +91,16 @@ public function validate(array $data, string|object $model): object
$this->validator->validate($property, $this->context);
$reflectionProperty->setValue($validModel, $property->getValue());
} catch (ValidationException|RespectValidationException $error) {
if ($error->getMessage() == 'Invalid data' && $this->context->get('option.stopFirstError')) {
break;
}

$errorInfo->addError($error);
} catch (ContinueValidationException $error) {
} catch (StopValidationException $error) {
break;
} finally {
$this->context->pop('internal.currentProperty');
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/Validators/ChainValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Attributes\Validation\Context;
use Attributes\Validation\ErrorInfo;
use Attributes\Validation\Exceptions\ContinueValidationException;
use Attributes\Validation\Exceptions\ValidationException;
use Attributes\Validation\Property;
use Respect\Validation\Exceptions\ValidationException as RespectValidationException;
Expand All @@ -20,6 +21,7 @@ class ChainValidator implements PropertyValidator
* @param Property $property - Property to yield the rules from
*
* @throws ValidationException
* @throws ContinueValidationException - When errors do exist, and we still want to check the remaining data
*/
public function validate(Property $property, Context $context): void
{
Expand All @@ -29,11 +31,12 @@ public function validate(Property $property, Context $context): void
$validator->validate($property, $context);
} catch (ValidationException|RespectValidationException $error) {
$errorInfo->addError($error);
} catch (ContinueValidationException $error) {
}
}

if ($errorInfo->hasErrors()) {
throw new ValidationException('Invalid data', $errorInfo);
throw new ContinueValidationException('Continue validation');
}
}

Expand Down
25 changes: 18 additions & 7 deletions src/Validators/Types/AnyClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

use Attributes\Validation\Context;
use Attributes\Validation\Exceptions\ContextPropertyException;
use Attributes\Validation\Exceptions\ContinueValidationException;
use Attributes\Validation\Exceptions\StopValidationException;
use Attributes\Validation\Exceptions\ValidationException;
use Attributes\Validation\Property;
use Attributes\Validation\Validator;
Expand All @@ -27,8 +29,9 @@ final class AnyClass implements BaseType
*
* @throws RespectValidationException - If not valid array
* @throws ContextPropertyException
* @throws ValidationException
* @throws ReflectionException
* @throws ContinueValidationException - When validation should keep running even when an error is encountered
* @throws StopValidationException - When we should stop when the first error is encountered
*/
public function validate(Property $property, Context $context): void
{
Expand All @@ -39,11 +42,19 @@ public function validate(Property $property, Context $context): void
}

v::arrayVal()->assert($value);
$clonedContext = clone $context;
$recursionLevel = $clonedContext->getOptional('internal.recursionLevel', 0);
$clonedContext->set('internal.recursionLevel', $recursionLevel + 1, override: true);
$validator = new Validator(context: $clonedContext);
$validModel = $validator->validate((array) $value, $typeHint);
$property->setValue($validModel);
$recursionLevel = $context->getOptional('internal.recursionLevel', 0);
$context->set('internal.recursionLevel', $recursionLevel + 1, override: true);
$validator = new Validator(context: $context);
try {
$validModel = $validator->validate((array) $value, $typeHint);
$property->setValue($validModel);
} catch (ValidationException) {
if ($context->get('option.stopFirstError')) {
throw new StopValidationException('Stop validation');
}
throw new ContinueValidationException('Class validation failed');
} finally {
$context->set('internal.recursionLevel', $recursionLevel, override: true);
}
}
}
Loading