Laravel.io
function best_fit($max_width, $max_height) {
        // If it already fits, there's nothing to do
        if ($this->width <= $max_width && $this->height <= $max_height) {
            return $this;
        }
        // Determine aspect ratio
        $aspect_ratio = $this->height / $this->width;
        // Make width fit into new dimensions
        if ($this->width > $max_width) {
            $width = $max_width;
            $height = $width * $aspect_ratio;
        } else {
            $width = $this->width;
            $height = $this->height;
        }
        // Make height fit into new dimensions
        if ($height > $max_height) {
            $height = $max_height;
            $width = $height / $aspect_ratio;
        }
        return $this->resize($width, $height);
    }

Please note that all pasted data is publicly available.