Last active
August 29, 2015 14:01
-
-
Save opalfroot/14524bf50f9657ef7d21 to your computer and use it in GitHub Desktop.
Silverstripe Simple Image Size Upload Validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ImageUpload_Validator extends Upload_Validator{ | |
public $minwidth; | |
public $minheight; | |
public function setMinDimensions($width,$height){ | |
if(is_numeric($width) && intval($width)>=0) | |
$this->minwidth=intval($width); | |
else | |
user_error('Invalid minimum width, value must be numeric and at least 0',E_USER_ERROR); | |
if(is_numeric($height) && intval($height)>=0) | |
$this->minheight=intval($height); | |
else | |
user_error('Invalid minimum height, value must be numeric and at least 0',E_USER_ERROR); | |
} | |
public function isValidDimensions() { | |
//if we cannot determine the image size return false | |
if(!$dims = getimagesize($this->tmpFile['tmp_name'])) | |
return false; | |
if(($this->minheight && $dims[1]<=$this->minheight) || ($this->minwidth && $dims[0]<=$this->minwidth)) | |
return false; | |
return true; | |
} | |
public function validate(){ | |
if(!isset($this->tmpFile['name']) || empty($this->tmpFile['name'])) | |
return true; | |
if(!$this->isValidDimensions()){ | |
$this->errors[]=sprintf('Minimum image size is %s x %s ', $this->minwidth?$this->minwidth.'px':'(ANY)',$this->minheight?$this->minheight.'px':'(ANY)'); | |
return false; | |
} | |
return parent::validate(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyObject extends DataObject{ | |
private static $has_one = array( | |
'Image' => 'Image' | |
); | |
public function getCMSFields() | |
{ | |
$fields = parent::getCMSFields(); | |
$uploadfield = new UploadField('Image','Main Image'); | |
//setup the new validator | |
$validator = new ImageUpload_Validator(); | |
$validator->setMinDimensions(1000,70); | |
$validator->setAllowedExtensions(array('jpg','jpeg', 'gif', 'png')); | |
$validator->setAllowedMaxFileSize(array('*' => 4194304)); | |
$uploadfield->setValidator($validator); | |
$fields->addFieldToTab('Root.Main',$uploadfield,'Content'); | |
return $fields; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment