small/forms-bundle

提供PHP类以在symfony中验证api数据。

1.0.2 2024-08-24 11:58 UTC

This package is auto-updated.

Last update: 2024-09-09 03:02:32 UTC


README

            

关于

此项目是small/forms的Symfony桥接器。

small/forms-bundle是一个用于验证、归一化和反归一化api数据的库。

此包绕过symfony正常化器。

安装

composer require small/forms-bundle

内联表单

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

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

\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属性解析出来。

验证规则列表

  • ValidateBoolean
  • 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
  • ValidateCallback
  • ValidateAtLeastOneOf
  • ValidateSequencialy

修饰符列表

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