framework icon indicating copy to clipboard operation
framework copied to clipboard

[11.x] Adding minRatio & maxRatio rules on Dimension validation ruleset

Open CamKem opened this issue 6 months ago • 3 comments

This PR introduces the ability to set a minimum & maximum aspect ratio in the Dimension rule.

Currently the framework only supports fixed ratios within the rule, allowing restriction of aspect ratios to only the defined values, this would allow the user to set a range of aspect ratios that an image would have to fall within.

The premise for this was conceived whilst I was doing further work on the image upload feature for Pinkary. We are have been considering how to deal with very long images, such as screenshots of full webpages taken using devtools, where the aspect ratio is on the extreme end & it would be nice to be able to set a range to handle this through validation within the framework.

Currently we would need to write a custom rule or use a closure like so:

function ($attribute, $value, $fail) {
    [$width, $height] = getimagesize($value->getPathname());
    $aspectRatio = $width / $height;
    if ($aspectRatio > 1 / 2 || $aspectRatio < 1 / 3) {
        $fail("The image aspect ratio must be between 1:2 and 1:3.");
    }

This PR introduces the ability to use it like so:

File::image()
    ->types(['jpeg', 'png', 'gif', 'webp', 'jpg'])
    ->max($this->maxFileSize)
->dimensions(Rule::dimensions()
    ->minRatio(1/2)
    ->maxRatio(1/3)
),

You could use only the minimum or maximum ratio alone, if you don't need upper or lower limits.

I also added a range method, that on evaluations adds a min_ratio and max_ratio constraint.

File::image()
    ->types(['jpeg', 'png', 'gif', 'webp', 'jpg'])
    ->max($this->maxFileSize)
->dimensions(Rule::dimensions()
    ->ratioRange(min: 1/2, max: 1/3)
),

All 3 of the added methods would be a good edition to the Validation capabilities of the framework.

I have added tests to cover the addition of these methods to the Dimension ruleset.

Screenshot 2024-08-14 at 11 56 19 PM

CamKem avatar Aug 14 '24 13:08 CamKem