3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Validator\File
;
12 use Zend\Validator\Exception
;
15 * Validator for the md5 hash of given files
17 class Md5
extends Hash
20 * @const string Error constants
22 const DOES_NOT_MATCH
= 'fileMd5DoesNotMatch';
23 const NOT_DETECTED
= 'fileMd5NotDetected';
24 const NOT_FOUND
= 'fileMd5NotFound';
27 * @var array Error message templates
29 protected $messageTemplates = [
30 self
::DOES_NOT_MATCH
=> "File does not match the given md5 hashes",
31 self
::NOT_DETECTED
=> "An md5 hash could not be evaluated for the given file",
32 self
::NOT_FOUND
=> "File is not readable or does not exist",
36 * Options for this validator
40 protected $options = [
46 * Returns all set md5 hashes
50 public function getMd5()
52 return $this->getHash();
56 * Sets the md5 hash for one or multiple files
58 * @param string|array $options
59 * @return Hash Provides a fluent interface
61 public function setMd5($options)
63 $this->setHash($options);
68 * Adds the md5 hash for one or multiple files
70 * @param string|array $options
71 * @return Hash Provides a fluent interface
73 public function addMd5($options)
75 $this->addHash($options);
80 * Returns true if and only if the given file confirms the set hash
82 * @param string|array $value Filename to check for hash
83 * @param array $file File data from \Zend\File\Transfer\Transfer (optional)
86 public function isValid($value, $file = null)
88 if (is_string($value) && is_array($file)) {
89 // Legacy Zend\Transfer API support
90 $filename = $file['name'];
91 $file = $file['tmp_name'];
92 } elseif (is_array($value)) {
93 if (! isset($value['tmp_name']) ||
! isset($value['name'])) {
94 throw new Exception\
InvalidArgumentException(
95 'Value array must be in $_FILES format'
98 $file = $value['tmp_name'];
99 $filename = $value['name'];
102 $filename = basename($file);
104 $this->setValue($filename);
106 // Is file readable ?
107 if (empty($file) ||
false === is_readable($file)) {
108 $this->error(self
::NOT_FOUND
);
112 $hashes = array_unique(array_keys($this->getHash()));
113 $filehash = hash_file('md5', $file);
114 if ($filehash === false) {
115 $this->error(self
::NOT_DETECTED
);
119 foreach ($hashes as $hash) {
120 if ($filehash === $hash) {
125 $this->error(self
::DOES_NOT_MATCH
);