<?php

namespace Modules\Project\Http\Requests;

use Modules\Base\Http\Requests\BaseRequest;

class FavoriteRequest extends BaseRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'object' => [
                'required',
                function ($attribute, $value, $fail) {
                    $class = $this->getClassName();
                    if (!class_exists($class)) {
                        return $fail($attribute.' 不存在.');
                    }

                    $traits = class_uses($class);
                    if (!is_array($traits) || !isset($traits['Overtrue\LaravelFollow\Traits\CanBeFavorited'])) {
                        return $fail($value.' 不可收藏.');
                    }
                },
            ],
        ];

        switch ($this->method()) {
            case 'POST':
            case 'DELETE':
                $rules['id'] = 'required';
                break;
        }

        return $rules;
    }

    /**获取正确类名
     * @return mixed|string
     */
    public function getClassName()
    {
        $value = $this->object;
        if (!strpos($value, '\\')) {
            $value = config('follow.model_namespace').'\\'.studly_case($value);
        }

        if (substr($value, 0, 1) != '\\') {
            $value = '\\'.$value;
        }

        return $value;
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}
