Image.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2020 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
11 namespace wcmf\lib\validation\impl;
12 
15 
16 /**
17  * Image validates an image value.
18  *
19  * Configuration examples:
20  * @code
21  * // width exactly 200px, height less than 100px
22  * image:{"width":[200,1],"height":[100,0]}
23  *
24  * // arbitrary width, height exactly 300px
25  * image:{"height":[300,0]}
26  * @endcode
27  *
28  * @author ingo herwig <ingo@wemove.com>
29  */
30 class Image implements ValidateType {
31 
32  /**
33  * @see ValidateType::validate
34  * $options is an associative array with keys 'width' (optional) and 'height' (optional)
35  * where each array entry is an array with the size as first value and an boolean
36  * indicating if the size should be matched exactly as second value
37  */
38  public function validate($value, $options=null, $context=null) {
39  if (strlen($value) == 0) {
40  return true;
41  }
42 
43  $imgWidth = isset($options['width']) ? $options['width'] : false;
44  $imgHeight = isset($options['height']) ? $options['height'] : false;
45 
46  if ($imgWidth === false && $imgHeight === false) {
47  return true;
48  }
49 
50  // translate path
51  $absValue = WCMF_BASE.$value;
52  $value = FileUtil::fixFilename(FileUtil::realpath(dirname($absValue)).'/'.FileUtil::basename($absValue));
53  if (!$value) {
54  return false;
55  }
56 
57  // check dimensions of the image
58  list($width, $height) = @getimagesize($value);
59  $widthOk = $imgWidth !== false ?
60  ($imgWidth[1] && $imgWidth[0] == $width) || (!$imgWidth[1] && $imgWidth[0] <= $width) :
61  true;
62  $heightOk = $imgHeight !== false ?
63  ($imgHeight[1] && $imgHeight[0] == $height) || (!$imgHeight[1] && $imgHeight[0] <= $height) :
64  true;
65 
66  return $widthOk && $heightOk;
67  }
68 }
69 ?>
static basename($file)
Get the trailing name component of a path (locale independent)
Definition: FileUtil.php:327
ValidateType defines the interface for all validator classes.
Image validates an image value.
Definition: Image.php:30
FileUtil provides basic support for file functionality like HTTP file upload.
Definition: FileUtil.php:22
static realpath($path)
Realpath function that also works for non existing paths code from http://www.php....
Definition: FileUtil.php:244
validate($value, $options=null, $context=null)
Definition: Image.php:38
static fixFilename($file)
Fix the name of an existing file to be used with php file functions.
Definition: FileUtil.php:286