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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"license": "MIT",
"require": {
"php": "^8.1",
"respect/validation": "^2.3"
"respect/validation": "^2.0"
},
"autoload": {
"psr-4": {
Expand Down
26 changes: 13 additions & 13 deletions composer.lock

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

5 changes: 3 additions & 2 deletions src/ErrorInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

namespace Attributes\Validation;

use Attributes\Validation\Exceptions\StopValidationException;
use Attributes\Validation\Exceptions\ValidationException;
use Exception;
use Respect\Validation\Exceptions\NestedValidationException as RespectNestedValidationException;
Expand Down Expand Up @@ -77,9 +78,9 @@ public function addError(Exception|string $error): void

if ($this->context->get('option.stopFirstError')) {
if (! is_string($error)) {
throw new ValidationException('Invalid data', $this, previous: $error);
throw new StopValidationException('Invalid data', $this, previous: $error);
}
throw new ValidationException('Invalid data', $this);
throw new StopValidationException('Invalid data', $this);
}
}
}
7 changes: 7 additions & 0 deletions src/Exceptions/InvalidOptionException.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 InvalidOptionException extends ValidationException {}
23 changes: 23 additions & 0 deletions src/Options/Alias.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Attributes\Validation\Options;

use Attribute;

#[Attribute(Attribute::TARGET_PROPERTY)]
class Alias
{
private string $alias;

public function __construct(string $alias)
{
$this->alias = $alias;
}

public function getAlias(): string
{
return $this->alias;
}
}
78 changes: 78 additions & 0 deletions src/Options/AliasGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

declare(strict_types=1);

namespace Attributes\Validation\Options;

use Attribute;
use Attributes\Validation\Exceptions\InvalidOptionException;

#[Attribute(Attribute::TARGET_CLASS)]
class AliasGenerator
{
private $aliasGenerator;

/**
* @param string|callable $aliasGenerator - The alias generator. Either a callable or a string with either 'camel', 'pascal' or 'snake'
*/
public function __construct(string|callable $aliasGenerator)
{
$this->aliasGenerator = $aliasGenerator;
}

/**
* @throws InvalidOptionException
*/
public function getAliasGenerator(): callable
{
if (is_callable($this->aliasGenerator)) {
return $this->aliasGenerator;
}

switch ($this->aliasGenerator) {
case 'camel':
return $this->toCamel(...);
case 'pascal':
return $this->toPascal(...);
case 'snake':
return $this->toSnake(...);
default:
throw new InvalidOptionException("Invalid alias generator '$this->aliasGenerator'");
}
}

/**
* Converts a string into camelCase
*
* @taken https://github.com/symfony/string/blob/7.3/ByteString.php#camel
*/
public function toCamel(string $propertyName): string
{
$parts = explode(' ', trim(ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $propertyName))));
$parts[0] = \strlen($parts[0]) !== 1 && ctype_upper($parts[0]) ? $parts[0] : lcfirst($parts[0]);

return implode('', $parts);
}

/**
* Converts a string into PascalCase
*/
public function toPascal(string $propertyName): string
{
$propertyName = $this->toCamel($propertyName);

return ucfirst($propertyName);
}

/**
* Converts a string into snake_case
*
* @taken https://github.com/symfony/string/blob/7.3/ByteString.php#snake
*/
public function toSnake(string $propertyName): string
{
$propertyName = $this->toCamel($propertyName);

return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1_\2', $propertyName));
}
}
55 changes: 48 additions & 7 deletions src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
use Attributes\Validation\Exceptions\ContinueValidationException;
use Attributes\Validation\Exceptions\StopValidationException;
use Attributes\Validation\Exceptions\ValidationException;
use Attributes\Validation\Options as Options;
use Attributes\Validation\Validators\AttributesValidator;
use Attributes\Validation\Validators\ChainValidator;
use Attributes\Validation\Validators\PropertyValidator;
use Attributes\Validation\Validators\TypeHintValidator;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;
use Respect\Validation\Exceptions\ValidationException as RespectValidationException;
use Respect\Validation\Factory;

Expand All @@ -31,6 +33,7 @@ public function __construct(?PropertyValidator $validator = null, bool $stopFirs
$this->context = $context ?? new Context;
$this->context->set('option.stopFirstError', $stopFirstError);
$this->context->set('option.strict', $strict);
$this->context->set('option.alias.generator', fn (string $name) => $name);
$this->validator = $this->context->getOptional(PropertyValidator::class, $validator) ?? $this->getDefaultPropertyValidator();
$this->context->set(PropertyValidator::class, $this->validator);

Expand Down Expand Up @@ -69,32 +72,30 @@ public function validate(array $data, string|object $model): object
$reflectionClass = new ReflectionClass($validModel);
$errorInfo = $this->context->getOptional(ErrorInfo::class) ?: new ErrorInfo($this->context);
$this->context->set(ErrorInfo::class, $errorInfo, override: true);
$defaultAliasGenerator = $this->getDefaultAliasGenerator($reflectionClass);
foreach ($reflectionClass->getProperties() as $reflectionProperty) {
$propertyName = $reflectionProperty->getName();
$aliasName = $this->getAliasName($reflectionProperty, $defaultAliasGenerator);
$this->context->push('internal.currentProperty', $propertyName);

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

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

continue;
}

$propertyValue = $data[$propertyName];
$propertyValue = $data[$aliasName];
$property = new Property($reflectionProperty, $propertyValue, $validModel::class);
$this->context->set(Property::class, $property, override: true);

try {
$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) {
Expand All @@ -119,4 +120,44 @@ private function getDefaultPropertyValidator(): PropertyValidator

return $chainRulesExtractor;
}

/**
* Retrieves the default alias generator for a given class
*
* @throws ContextPropertyException
*/
private function getDefaultAliasGenerator(ReflectionClass $reflectionClass): callable
{
$allAttributes = $reflectionClass->getAttributes(Options\AliasGenerator::class);
foreach ($allAttributes as $attribute) {
$instance = $attribute->newInstance();

return $instance->getAliasGenerator();
}

$aliasGenerator = $this->context->get('option.alias.generator');
if (is_callable($aliasGenerator)) {
return $aliasGenerator;
}

$aliasGenerator = new Options\AliasGenerator($aliasGenerator);

return $aliasGenerator->getAliasGenerator();
}

/**
* Retrieves the alias for a given property
*/
private function getAliasName(ReflectionProperty $reflectionProperty, callable $defaultAliasGenerator): string
{
$propertyName = $reflectionProperty->getName();
$allAttributes = $reflectionProperty->getAttributes(Options\Alias::class);
foreach ($allAttributes as $attribute) {
$instance = $attribute->newInstance();

return $instance->getAlias($propertyName);
}

return $defaultAliasGenerator($propertyName);
}
}
5 changes: 3 additions & 2 deletions src/Validators/AttributesValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Attributes\Validation\ErrorInfo;
use Attributes\Validation\Exceptions\ContextPropertyException;
use Attributes\Validation\Property;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionException;
use Respect\Validation\Exceptions\ValidationException as RespectValidationException;
Expand All @@ -27,15 +28,15 @@ class AttributesValidator implements PropertyValidator
*/
public function validate(Property $property, Context $context): void
{
$allAttributes = $property->getReflection()->getAttributes();
$allAttributes = $property->getReflection()->getAttributes(Validatable::class, ReflectionAttribute::IS_INSTANCEOF);
if (! $allAttributes) {
return;
}

$errorInfo = $context->get(ErrorInfo::class);
foreach ($allAttributes as $attribute) {
$className = $attribute->getName();
if (! is_subclass_of($className, Validatable::class) || $className == Rules\DateTime::class) {
if ($className == Rules\DateTime::class) {
continue;
}

Expand Down
2 changes: 1 addition & 1 deletion tests/Integration/ErrorHandlingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,4 @@
}
})
->with([true, false])
->group('validator', 'error-handling', 'nested', 'strict');
->group('validator', 'error-handling', 'nested');
Loading