Cviebrock\ImageValidator\ImageValidator::validateImageAspect PHP Method

validateImageAspect() public method

Usage: image_aspect:ratio
public validateImageAspect ( $attribute, $value, $parameters ) : boolean
$attribute string
$value string|array
$parameters array
return boolean
    public function validateImageAspect($attribute, $value, $parameters)
    {
        $image = $this->getImagePath($value);
        // Get the image dimension info, or fail.
        $image_size = @getimagesize($image);
        if ($image_size === false) {
            return false;
        }
        $image_width = $image_size[0];
        $image_height = $image_size[1];
        // Parse the parameter(s).  Options are:
        //
        // 	"0.75"   - one param: a decimal ratio (width/height)
        // 	"3,4"    - two params: width, height
        //
        // If the first value is prefixed with "~", the orientation doesn't matter, i.e.:
        //
        // 	"~3,4"   - would accept either "3:4" or "4:3" images
        $both_orientations = false;
        if (substr($parameters[0], 0, 1) == '~') {
            $parameters[0] = substr($parameters[0], 1);
            $both_orientations = true;
        }
        if (count($parameters) == 1) {
            $aspect_width = $parameters[0];
            $aspect_height = 1;
        } else {
            $aspect_width = intval($parameters[0]);
            $aspect_height = intval($parameters[1]);
        }
        if ($aspect_width == 0 || $aspect_height == 0) {
            throw new \RuntimeException('Aspect is zero or infinite: ' . $parameters[0]);
        }
        $check = $image_width * $aspect_height / $aspect_width;
        if (round($check) == $image_height) {
            return true;
        }
        if ($both_orientations) {
            $check = $image_width * $aspect_width / $aspect_height;
            if (round($check) == $image_height) {
                return true;
            }
        }
        return false;
    }