Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow complex validation rules #91

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

cgslivre
Copy link

I didn't find a way to annotate a complex validation rule and implemented a way for the src/Concerns/RulesValidation.php class to look for an internal Model method that returns an Illuminate\Validation\Rule.

I also modified the applyValidations method call in src/Lift.php to simplify the validation process without needing to be triggered twice.

Example

Rule::unique(static::class, 'name')->ignore($this->getKey())

Solution

class Client extends Model
{
    #[Fillable]
    #[Cast('string')]
    #[Rules(['required', 'max:255', 'uniqueNameRule'])]
    public string $name;

    public function uniqueNameRule()
    {
        return Rule::unique(static::class, 'name')->ignore($this->getKey());
    }
}

Changes
src/Lift.php
I modified the call to the apply Validations method by adding the payment Model $model;
I removed the calls to the methods: applyCreateValidations and applyUpdateValidations;

src/Concerns/RulesValidation.php
I added the parseValidationRules method that checks if a validation rule is a valid method name of the Model and then triggers it.

private static function parseValidationRules(Model $model, array $properties) {}

I changed the signature of the applyValidations method to receive the Model instance.

private static function applyValidations(Model $model, Collection $properties): void {}

I merged the validation rules to unite: validationRules, createValidationRules and updateValidationRules according to the Model context.

    $validator = Validator::make(
        data: $data->toArray(),
        rules: self::parseValidationRules($model, [
            ...self::validationRules(),
            ...(blank($model->getKey()) ? self::createValidationRules() : self::updateValidationRules())
        ]),
        messages: [
            ...self::validationMessages(),
            ...(blank($model->getKey()) ? self::createValidationMessages() : self::updateValidationMessages())
        ],
    );

That's it folks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant