規則收集器 2.0 gordensong/laravel-validator 基礎篇系列(一)

gordensong發表於2021-09-18

gordensong/laravel-validator

經過 gordensong/laravel-table-validator 的試水,決定建立一個更加簡單實用的版本。

新專案:gitee.com/gordensong/laravel-valid...

用法展示

routes/web.php

Route::post('/user/name-register')
    ->uses([UserController::class, 'nameRegister'])
    ->name('user.name-register');

Route::post('/user/add-addresses')
    ->uses([UserController::class, 'addAddresses'])
    ->name('user.add-addresses');

UserController.php

<?php

namespace App\Http\Controllers;

use App\Validators\Mysql\UsersAddressValidator;
use App\Validators\Mysql\UsersValidator;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function nameRegister(Request $request, UsersValidator $validator): JsonResponse
    {
        $validated = $validator->scene('name-register')->validate($request->all());

        return response()->json($validated);
    }

    public function addAddresses(Request $request, UsersAddressValidator $addressesValidator)
    {
        $validated = $addressesValidator
            ->only('province', 'city', 'district')
            ->prefix('addresses.*')
            ->validate($request->all());

        return response()->json($validated);
    }
}

UserControllerTest.php

<?php

namespace Tests\App\Http\Controllers;

use Tests\TestCase;

class UserControllerTest extends TestCase
{
    public function test_nameRegister($route = 'user.name-register')
    {
        $data = [
            'name' => 'jack',
            'password' => '123456',
            'password_confirmation' => '123456',
        ];

        $this->postJson(route($route), $data)
            ->assertOk()
            ->assertJson([
                'name' => 'jack',
                'password' => '123456',
            ]);
    }

    public function test_addAddresses($route = 'user.add-addresses')
    {
        $data = [
            'addresses' => [
                ['province' => 'PA1', 'city' => 'CA1', 'district' => 'DA1'],
                ['province' => 'PA2', 'city' => 'CA2', 'district' => 'DA2'],
            ],
        ];

        $this->postJson(route($route), $data)
            ->assertOk()
            ->assertJson($data);
    }
}

command

php artisan validator:make {table*} {--connection=mysql}

# output:
#validator       exists : /app/Validators/Mysql/UsersValidator.php
#validator trait created: /app/Validators/Mysql/UsersValidator.php
#...

目錄結構

/app

  • /Validators
    • /Mysql
      • /DatabaseRules // 存放表規則
        • UsersValidatorTrait.php // users 表
        • UsersAddressValidatorTrait.php
      • UsersValidator.php // users 表的自定義規則
      • UsersAddressValidator.php

Demo

UsersValidator.php

只生成一次。

<?php

namespace App\Validators\Mysql;

class UsersValidator extends \GordenSong\Laravel\Support\Validator
{
    use \App\Validators\Mysql\DatabaseRules\UsersValidatorTrait;

    public function customizeRules(): array
    {
        return [
            'id' => ['required'],
            'name' => ['required', 'min:3', 'max:50'], // 'min:3', 'max:50' 為自定義規則,
            'password' => ['required'],
            'created_at' => [],
            'updated_at' => [],
        ];
    }

    public function excludeRules(): array
    {
        return [
            'created_at', // 排除驗證的欄位
            'updated_at',
        ];
    }

    protected $messages = [

    ];

    protected $attributes = [
        // 'id' => '',
        // 'name' => '',
        // 'password' => '',
        // 'created_at' => '',
        // 'updated_at' => '',
    ];

    protected $scenes = [
        'name-register' => ['name', 'password' => 'confirmed'],
    ];
}

UsersValidatorTrait.php

自動生成,每次生成時自動覆蓋舊檔案。

<?php

namespace App\Validators\Mysql\DatabaseRules;

trait UsersValidatorTrait
{
    public function tableRules(): array
    {
        return [
            'id' => [
                'integer',
                'min:0',
            ],
            'name' => [
                'string',
                'max:255',
            ],
            'password' => [
                'string',
                'max:255',
            ],
            'created_at' => [
                'date',
            ],
            'updated_at' => [
                'date',
            ],
        ];
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章