DynamicUpdateRequest.php 1.31 KB
<?php

namespace App\Http\Container\AppSection\Requests;

use App\Models\UserDynamic;
use Closure;
use Hikoon\LaravelApi\Support\ApiRequest;

class DynamicUpdateRequest extends ApiRequest
{
    /**
     * @return void
     */
    protected function passedValidation(): void
    {
        if ($this->has('is_top') && $this->input('is_top') === 1) {
            $this->getInputSource()?->set('is_top', now()->timestamp);
            optional($this->getValidatorInstance())->setData($this->all());
        }
    }


    public function rules(): array
    {
        return [
            'is_top' => ['sometimes', 'integer', 'in:0,1', function (string $attribute, int $value, Closure $fail) {
                if ($value === 1 && $this->getTopCount() >= 3) {
                    $fail('最多允许置顶3条内容~');
                }
            }]
        ];
    }

    /**
     * @return string[]
     */
    public function messages(): array
    {
        return [
            'is_top.in' => '请选择置顶状态'
        ];
    }

    /**
     * @return int
     */
    public function getTopCount(): int
    {
        return UserDynamic::query()
            ->where('user_id', $this->route('dynamic.user_id'))
            ->where('type', $this->route('dynamic.type'))
            ->where('is_top', '!=', 0)
            ->count();
    }
}