small/forms

提供PHP类来验证API数据。

1.5.0 2024-09-05 15:29 UTC

This package is auto-updated.

Last update: 2024-09-05 15:30:02 UTC


README

            

关于

此项目提供数据验证表单。

有助于验证API输入数据。

与Symfony约束注解兼容

安装

composer require small/forms

内联表单

您可以在控制器操作中轻松创建表单。

例如,我们想检查此条目数据是否与我们的控制器操作匹配

\Small\Forms\Form\FormBuilder::createInlineForm()
    ->addField(
        'name', 
        new \Small\Forms\Form\Field\Type\StringType(),
        [new \Small\Forms\ValidationRule\ValidateNumberCharsLessThan(256)]
    )->addField('age', new \Small\Forms\Form\Field\Type\IntType())
;

try {
    $form->fillFromSymfonyRequest($request)
        ->validate($messages = new \Small\Collection\Collection\StringCollection())
    ;
} catch (\Small\Forms\ValidationRule\Exception\ValidationFailException) {
    return new \Symfony\Component\HttpFoundation\JsonResponse($messages, \Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
}

$arrayData = $form->toArray();

类表单

如果您想重用您的表单,您可以将它声明为一个类

namespace App\Form;

class PersonForm extends \Small\Forms\Form\AbstractForm
{

    public function build(): self {
        
        $this->addField(
            'name', 
            new \Small\Forms\Form\Field\Type\StringType(),
            [new \Small\Forms\ValidationRule\ValidateNumberCharsLessThan(256)]
        );
        
        $this->addField('age', new \Small\Forms\Form\Field\Type\IntType());
        
    }
    
}

然后在控制器中使用它

try {
    $form = \Small\Forms\Form\FormBuilder::createFromFormClass(App\Form\PersonForm::class)
        ->fillFromSymfonyRequest($request)
        ->validate($messages = new \Small\Collection\Collection\StringCollection())
    ;
} catch (\Small\Forms\ValidationRule\Exception\ValidationFailException) {
    return new \Symfony\Component\HttpFoundation\JsonResponse($messages, \Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
}

$arrayData = $form->toArray();

具有属性的标准化对象

您也可以直接从对象创建表单

namespace App\DTO;

use Small\Forms\Modifier\NullIfEmptyModifier;use Small\Forms\ValidationRule\ValidateNotEmpty;
use Small\Forms\ValidationRule\ValidateGreaterOrEqual;

class Person
{

    #[ValidateNotEmpty]
    private string $name;
    #[ValidateGreaterThanOrEqual(18)]
    #[NullIfEmptyModifier]
    private int $age;

}
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Employe
{
    
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column]
    #[Assert\NotBlank]
    private string $name;
    #[ORM\Column]
    private int $age;
    #[ORM\Column]
    private int $idService;
    
    #[ORM\ManyToOne(inversedBy: 'Service')]
    #[ORM\JoinColumn(name: "idService", referencedColumnName: "id", nullable: true)]
    private Service|null $service = null;

}
try {

    $form = \Small\Forms\Form\FormBuilder::createFromAdapter(
        new \Small\Forms\Adapter\AnnotationAdapter($person)
    )->validate($messages = new \Small\Collection\Collection\StringCollection())
    ->hydrate($employe = new App\Entity\Employe());

} catch (\Small\Forms\ValidationRule\Exception\ValidationFailException) {
    return new \Symfony\Component\HttpFoundation\JsonResponse($messages, \Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
}

$useCase->joinCompanyUseCase($employe);

$form->fillFromObject($employe)
    ->hydrate($person)
;

return new \Symfony\Component\HttpFoundation\JsonResponse($person);

验证规则将从您的实体类PHP属性中解析。

Symfony DTO或实体

您也可以从DTO对象创建表单

namespace App\DTO;

use Symfony\Component\Validator\Constraints as Assert;

class Person
{

    #[Assert\NotBlank]
    private string $name;
    #[Assert\GreaterThanOrEqual(18)]
    private int $age;

}
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Employe
{
    
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column]
    #[Assert\NotBlank]
    private string $name;
    #[ORM\Column]
    private int $age;
    #[ORM\Column]
    private int $idService;
    
    #[ORM\ManyToOne(inversedBy: 'Service')]
    #[ORM\JoinColumn(name: "idService", referencedColumnName: "id", nullable: true)]
    private Service|null $service = null;

}
try {

    $form = \Small\Forms\Form\FormBuilder::createFromAdapter(
        new \Small\Forms\Adapter\SymfonyAnnotationAdapter($person)
    )->validate($messages = new \Small\Collection\Collection\StringCollection())
    ->hydrate($employe = new App\Entity\Employe());

} catch (\Small\Forms\ValidationRule\Exception\ValidationFailException) {
    return new \Symfony\Component\HttpFoundation\JsonResponse($messages, \Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
}

$useCase->joinCompanyUseCase($employe);

$form->fillFromObject($employe)
    ->hydrate($person)
;

return new \Symfony\Component\HttpFoundation\JsonResponse($person);

验证规则将从您的实体类PHP属性中解析。

验证规则列表

  • ValidateAtLeastOneOf
  • ValidateBoolean
  • ValidateCallback
  • ValidateChoice
  • ValidateCountLessOrEqualThan
  • ValidateCountGreaterThan
  • ValidateCountLessOrEqualThan
  • ValidateCountLessThan
  • ValidateDateTime
  • ValidateDecimal
  • ValidateDivisibleBy
  • ValidateEmail
  • ValidateString
  • ValidateStringArray
  • ValidateUnique
  • ValidateDateTime
  • ValidateDivisibleBy
  • ValidateEmail
  • ValidateEmpty
  • ValidateEqual
  • ValidateFloat
  • ValidateFloatArray
  • ValidateGreater
  • ValidateGreaterOrEqual
  • ValidateInt
  • ValidateIntArray
  • ValidateIsFalse
  • ValidateIsNull
  • ValidateIsTrue
  • ValidateJson
  • ValidateLess
  • ValidateLessOrEqual
  • ValidateMatchRegex
  • ValidateMixedArray
  • ValidateNegativeNumber
  • ValidateNotEmpty
  • ValidateNotEqual
  • ValidateNotMatchRegex
  • ValidateNotNull
  • ValidateNumberCharsBetween
  • ValidateNumberCharLessThan
  • ValidatePositiveNumber
  • ValidateRange
  • ValidateRequired
  • ValidateChoice
  • ValidateSequencialy
  • ValidateString
  • ValidateStringArray
  • ValidateUnique

修饰符列表

  • ArrayToCollectionModifier
  • ExplodeModifier
  • FalseIfEmptyModifier
  • FormBooleanToPhpModifier
  • ImplodeModifier
  • LTrimModifier
  • NullIfEmptyModifier
  • RoundModifier
  • RTrimModifier
  • StringToDateTimeImmutableModifier
  • StringToDateTimeModifier
  • SubStrModifier
  • ToLowerModifier
  • ToUpperModifier
  • TrimModifier
  • UcFirstModifier
  • UcWordsModifier