PHP code example of baoziyoo / hyperf-dto-validation

1. Go to this page and download the library: Download baoziyoo/hyperf-dto-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

baoziyoo / hyperf-dto-validation example snippets




declare(strict_types=1);

namespace Baoziyoo\Hyperf\Example\DTO;

use Baoziyoo\Hyperf\DTO\Validation\Annotation\Rule\Between;
use Baoziyoo\Hyperf\DTO\Validation\Annotation\Rule\Email;
use Baoziyoo\Hyperf\DTO\Validation\Annotation\Rule\In;
use Baoziyoo\Hyperf\DTO\Validation\Annotation\Rule\Integer;
use Baoziyoo\Hyperf\DTO\Validation\Annotation\Rule\Nullable;
use Baoziyoo\Hyperf\DTO\Validation\Annotation\Rule\Required;
use Baoziyoo\Hyperf\DTO\Validation\Annotation\Rule\Validation;

class Address
{
    #[Required(messages: '请输入对应的文本')]
    #[Between(1,5)]
    #[Email]
    #[In(1,5)]
    #[Integer]
    #[Nullable]
    #[Required]
    public string $street;

    public float $float;
    
    public int $int;
    
    /** @var array<int,string> */
    public array $array;
    
    public LoginTokenTypeEnum $loginTokenTypeEnum;
    
    public ?City $city = null;
}

---

class City
{
    public string $name;
}

---

enum LoginTokenTypeEnum: string
{
    case jwt = 'jwt';
    
    case password = 'password';
}

use Baoziyoo\Hyperf\DTO\Annotation\Contracts\RequestBody;
use Baoziyoo\Hyperf\DTO\Annotation\Contracts\RequestQuery;
use Baoziyoo\Hyperf\DTO\Annotation\Contracts\RequestFormData;
use Baoziyoo\Hyperf\DTO\Validation\Annotation\Contracts\Valid;

public function add(#[RequestBody] #[Valid] Address $request){}

public function add(#[RequestQuery] #[Valid] Address $request){}

public function fromData(#[RequestFormData] #[Valid] Address $formData){}

public function add(#[RequestBody] #[Valid] DemoBodyRequest $request, #[RequestQuery] #[Valid] DemoQuery $query){}

class DemoController extends AbstractController
{
    public function index(#[RequestQuery] #[Valid] DemoQuery $request): Contact
    {
        $contact = new Contact();
        $contact->name = $request->name;
        var_dump($request);
        return $contact;
    }

    public function add(#[RequestBody] #[Valid] DemoBodyRequest $request, #[RequestQuery] DemoQuery $query)
    {
        var_dump($query);
        return json_encode($request, JSON_UNESCAPED_UNICODE);
    }

    public function fromData(#[RequestFormData] #[Valid] DemoFormData $formData): bool
    {
        $file = $this->request->file('photo');
        var_dump($file);
        var_dump($formData);
        return true;
    }
}