diff --git a/CHANGELOG.md b/CHANGELOG.md index eac7054c3b9..2276d9d8b2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ - The initializer for ServiceManagerAwareInterface was removed to prevent confusion between ServiceManagerAwareInterface and ServiceLocatorAwareInterface, and to promote using the latter interface. +- File upload functionality has been rewritten and moved out of Zend\File + into Zend\Form and Zend\InputFilter. File elements are now + specified and handled with Zend\Form just like any other form element. +- File upload progress functionality has been moved out of Zend\File into + specific classes under Zend\ProgressBar\Upload based on the type of + handler (APC, UploadProgress module, and Session progress in PHP 5.4). +- New form elements under Zend\Form\Element\File for the various upload + progress identifiers. +- New Zend\Filter\File\RenameUpload filter for securely moving uploaded + files. +- New Zend\Mvc\Controller\Plugin\FilePostRedirectGet plugin for file + upload forms. + ## 2.0.2: diff --git a/library/Zend/File/Transfer/Adapter/AbstractAdapter.php b/library/Zend/File/Transfer/Adapter/AbstractAdapter.php deleted file mode 100644 index 6f717d68331..00000000000 --- a/library/Zend/File/Transfer/Adapter/AbstractAdapter.php +++ /dev/null @@ -1,1508 +0,0 @@ - array( - Form is the name within the form or, if not set the filename - * name, - Original name of this file - * type, - Mime type of this file - * size, - Filesize in bytes - * tmp_name, - Internally temporary filename for uploaded files - * error, - Error which has occurred - * destination, - New destination for this file - * validators, - Set validator names for this file - * files - Set file names for this file - * )) - * - * @var array - */ - protected $files = array(); - - /** - * TMP directory - * @var string - */ - protected $tmpDir; - - /** - * Available options for file transfers - */ - protected $options = array( - 'ignoreNoFile' => false, - 'useByteString' => true, - 'magicFile' => null, - 'detectInfos' => true, - ); - - /** - * Send file - * - * @param mixed $options - * @return bool - */ - abstract public function send($options = null); - - /** - * Receive file - * - * @param mixed $options - * @return bool - */ - abstract public function receive($options = null); - - /** - * Is file sent? - * - * @param array|string|null $files - * @return bool - */ - abstract public function isSent($files = null); - - /** - * Is file received? - * - * @param array|string|null $files - * @return bool - */ - abstract public function isReceived($files = null); - - /** - * Has a file been uploaded ? - * - * @param array|string|null $files - * @return bool - */ - abstract public function isUploaded($files = null); - - /** - * Has the file been filtered ? - * - * @param array|string|null $files - * @return bool - */ - abstract public function isFiltered($files = null); - - /** - * Adds one or more files - * - * @param string|array $file File to add - * @param string|array $validator Validators to use for this file, must be set before - * @param string|array $filter Filters to use for this file, must be set before - * @return AbstractAdapter - * @throws Exception Not implemented - */ - //abstract public function addFile($file, $validator = null, $filter = null); - - /** - * Returns all set types - * - * @return array List of set types - * @throws Exception Not implemented - */ - //abstract public function getType(); - - /** - * Adds one or more type of files - * - * @param string|array $type Type of files to add - * @param string|array $validator Validators to use for this file, must be set before - * @param string|array $filter Filters to use for this file, must be set before - * @return AbstractAdapter - * @throws Exception Not implemented - */ - //abstract public function addType($type, $validator = null, $filter = null); - - /** - * Returns all set files - * - * @return array List of set files - */ - //abstract public function getFile(); - - /** - * Set the filter plugin manager instance - * - * @param FilterPluginManager $filterManager - * @return AbstractAdapter - */ - public function setFilterManager(FilterPluginManager $filterManager) - { - $this->filterManager = $filterManager; - return $this; - } - - /** - * Get the filter plugin manager instance - * - * @return FilterPluginManager - */ - public function getFilterManager() - { - if (!$this->filterManager instanceof FilterPluginManager) { - $this->setFilterManager(new FilterPluginManager()); - } - return $this->filterManager; - } - - /** - * Set the validator plugin manager instance - * - * @param ValidatorPluginManager $validatorManager - * @return AbstractAdapter - */ - public function setValidatorManager(ValidatorPluginManager $validatorManager) - { - $this->validatorManager = $validatorManager; - return $this; - } - - /** - * Get the validator plugin manager instance - * - * @return ValidatorPluginManager - */ - public function getValidatorManager() - { - if (!$this->validatorManager instanceof ValidatorPluginManager) { - $this->setValidatorManager(new ValidatorPluginManager()); - } - return $this->validatorManager; - } - - /** - * Adds a new validator for this class - * - * @param string|Validator\ValidatorInterface $validator Type of validator to add - * @param boolean $breakChainOnFailure If the validation chain should stop an failure - * @param string|array $options Options to set for the validator - * @param string|array $files Files to limit this validator to - * @return AbstractAdapter - * @throws Exception\InvalidArgumentException for invalid type - */ - public function addValidator($validator, $breakChainOnFailure = false, $options = null, $files = null) - { - if (is_string($validator)) { - $validator = $this->getValidatorManager()->get($validator, $options); - if (is_array($options) && isset($options['messages'])) { - if (is_array($options['messages'])) { - $validator->setMessages($options['messages']); - } elseif (is_string($options['messages'])) { - $validator->setMessage($options['messages']); - } - - unset($options['messages']); - } - } - - if (!$validator instanceof Validator\ValidatorInterface) { - throw new Exception\InvalidArgumentException( - 'Invalid validator provided to addValidator; ' . - 'must be string or Zend\Validator\ValidatorInterface' - ); - } - - $name = get_class($validator); - - $this->validators[$name] = $validator; - $this->break[$name] = $breakChainOnFailure; - $files = $this->getFiles($files, true, true); - foreach ($files as $file) { - if ($name == 'NotEmpty') { - $temp = $this->files[$file]['validators']; - $this->files[$file]['validators'] = array($name); - $this->files[$file]['validators'] += $temp; - } else { - $this->files[$file]['validators'][] = $name; - } - - $this->files[$file]['validated'] = false; - } - - return $this; - } - - /** - * Add Multiple validators at once - * - * @param array $validators - * @param string|array $files - * @return AbstractAdapter - * @throws Exception\InvalidArgumentException for invalid type - */ - public function addValidators(array $validators, $files = null) - { - foreach ($validators as $name => $validatorInfo) { - if ($validatorInfo instanceof Validator\ValidatorInterface) { - $this->addValidator($validatorInfo, null, null, $files); - } elseif (is_string($validatorInfo)) { - if (!is_int($name)) { - $this->addValidator($name, null, $validatorInfo, $files); - } else { - $this->addValidator($validatorInfo, null, null, $files); - } - } elseif (is_array($validatorInfo)) { - $argc = count($validatorInfo); - $breakChainOnFailure = false; - $options = array(); - if (isset($validatorInfo['validator'])) { - $validator = $validatorInfo['validator']; - if (isset($validatorInfo['breakChainOnFailure'])) { - $breakChainOnFailure = $validatorInfo['breakChainOnFailure']; - } - - if (isset($validatorInfo['options'])) { - $options = $validatorInfo['options']; - } - - $this->addValidator($validator, $breakChainOnFailure, $options, $files); - } else { - if (is_string($name)) { - $validator = $name; - $options = $validatorInfo; - $this->addValidator($validator, $breakChainOnFailure, $options, $files); - } else { - $file = $files; - switch (true) { - case (0 == $argc): - break; - case (1 <= $argc): - $validator = array_shift($validatorInfo); - case (2 <= $argc): - $breakChainOnFailure = array_shift($validatorInfo); - case (3 <= $argc): - $options = array_shift($validatorInfo); - case (4 <= $argc): - if (!empty($validatorInfo)) { - $file = array_shift($validatorInfo); - } - default: - $this->addValidator($validator, $breakChainOnFailure, $options, $file); - break; - } - } - } - } else { - throw new Exception\InvalidArgumentException('Invalid validator passed to addValidators()'); - } - } - - return $this; - } - - /** - * Sets a validator for the class, erasing all previous set - * - * @param array $validators Validators to set - * @param string|array $files Files to limit this validator to - * @return AbstractAdapter - */ - public function setValidators(array $validators, $files = null) - { - $this->clearValidators(); - return $this->addValidators($validators, $files); - } - - /** - * Determine if a given validator has already been registered - * - * @param string $name - * @return bool - */ - public function hasValidator($name) - { - return (false !== $this->getValidatorIdentifier($name)); - } - - /** - * Retrieve individual validator - * - * @param string $name - * @return Validator\ValidatorInterface|null - */ - public function getValidator($name) - { - if (false === ($identifier = $this->getValidatorIdentifier($name))) { - return null; - } - return $this->validators[$identifier]; - } - - /** - * Returns all set validators - * - * @param string|array $files (Optional) Returns the validator for this files - * @return null|array List of set validators - */ - public function getValidators($files = null) - { - if ($files == null) { - return $this->validators; - } - - $files = $this->getFiles($files, true, true); - $validators = array(); - foreach ($files as $file) { - if (!empty($this->files[$file]['validators'])) { - $validators += $this->files[$file]['validators']; - } - } - - $validators = array_unique($validators); - $result = array(); - foreach ($validators as $validator) { - $result[$validator] = $this->validators[$validator]; - } - - return $result; - } - - /** - * Remove an individual validator - * - * @param string $name - * @return AbstractAdapter - */ - public function removeValidator($name) - { - if (false === ($key = $this->getValidatorIdentifier($name))) { - return $this; - } - - unset($this->validators[$key]); - foreach (array_keys($this->files) as $file) { - if (empty($this->files[$file]['validators'])) { - continue; - } - - $index = array_search($key, $this->files[$file]['validators']); - if ($index === false) { - continue; - } - - unset($this->files[$file]['validators'][$index]); - $this->files[$file]['validated'] = false; - } - - return $this; - } - - /** - * Remove all validators - * - * @return AbstractAdapter - */ - public function clearValidators() - { - $this->validators = array(); - foreach (array_keys($this->files) as $file) { - $this->files[$file]['validators'] = array(); - $this->files[$file]['validated'] = false; - } - - return $this; - } - - /** - * Sets Options for adapters - * - * @param array $options Options to set - * @param array $files (Optional) Files to set the options for - * @return AbstractAdapter - */ - public function setOptions($options = array(), $files = null) - { - $file = $this->getFiles($files, false, true); - - if (is_array($options)) { - if (empty($file)) { - $this->options = array_merge($this->options, $options); - } - - foreach ($options as $name => $value) { - foreach ($file as $key => $content) { - switch ($name) { - case 'magicFile' : - $this->files[$key]['options'][$name] = (string) $value; - break; - - case 'ignoreNoFile' : - case 'useByteString' : - case 'detectInfos' : - $this->files[$key]['options'][$name] = (boolean) $value; - break; - - default: - continue; - } - } - } - } - - return $this; - } - - /** - * Returns set options for adapters or files - * - * @param array $files (Optional) Files to return the options for - * @return array Options for given files - */ - public function getOptions($files = null) - { - $file = $this->getFiles($files, false, true); - - foreach ($file as $key => $content) { - if (isset($this->files[$key]['options'])) { - $options[$key] = $this->files[$key]['options']; - } else { - $options[$key] = array(); - } - } - - return $options; - } - - /** - * Checks if the files are valid - * - * @param string|array $files (Optional) Files to check - * @return boolean True if all checks are valid - */ - public function isValid($files = null) - { - $check = $this->getFiles($files, false, true); - if (empty($check)) { - return false; - } - - $translator = $this->getTranslator(); - $this->messages = array(); - $break = false; - foreach ($check as $content) { - if (array_key_exists('validators', $content) && - in_array('Zend\Validator\File\Count', $content['validators'])) { - $validator = $this->validators['Zend\Validator\File\Count']; - $count = $content; - if (empty($content['tmp_name'])) { - continue; - } - - if (array_key_exists('destination', $content)) { - $checkit = $content['destination']; - } else { - $checkit = dirname($content['tmp_name']); - } - - $checkit .= DIRECTORY_SEPARATOR . $content['name']; - $validator->addFile($checkit); - } - } - - if (isset($count)) { - if (!$validator->isValid($count['tmp_name'], $count)) { - $this->messages += $validator->getMessages(); - } - } - - foreach ($check as $key => $content) { - $fileerrors = array(); - if (array_key_exists('validators', $content) && $content['validated']) { - continue; - } - - if (array_key_exists('validators', $content)) { - foreach ($content['validators'] as $class) { - $validator = $this->validators[$class]; - if (method_exists($validator, 'setTranslator')) { - $validator->setTranslator($translator); - } - - if (($class === 'Zend\Validator\File\Upload') and (empty($content['tmp_name']))) { - $tocheck = $key; - } else { - $tocheck = $content['tmp_name']; - } - - if (!$validator->isValid($tocheck, $content)) { - $fileerrors += $validator->getMessages(); - } - - if (!empty($content['options']['ignoreNoFile']) and (isset($fileerrors['fileUploadErrorNoFile']))) { - unset($fileerrors['fileUploadErrorNoFile']); - break; - } - - if (($class === 'Zend\Validator\File\Upload') and (count($fileerrors) > 0)) { - break; - } - - if (($this->break[$class]) and (count($fileerrors) > 0)) { - $break = true; - break; - } - } - } - - if (count($fileerrors) > 0) { - $this->files[$key]['validated'] = false; - } else { - $this->files[$key]['validated'] = true; - } - - $this->messages += $fileerrors; - if ($break) { - break; - } - } - - if (count($this->messages) > 0) { - return false; - } - - return true; - } - - /** - * Returns found validation messages - * - * @return array - */ - public function getMessages() - { - return $this->messages; - } - - /** - * Retrieve error codes - * - * @return array - */ - public function getErrors() - { - return array_keys($this->messages); - } - - /** - * Are there errors registered? - * - * @return boolean - */ - public function hasErrors() - { - return (!empty($this->messages)); - } - - /** - * Adds a new filter for this class - * - * @param string|Filter\FilterInterface $filter Type of filter to add - * @param string|array $options Options to set for the filter - * @param string|array $files Files to limit this filter to - * @return AbstractAdapter - * @throws Exception\InvalidArgumentException for invalid type - */ - public function addFilter($filter, $options = null, $files = null) - { - if (is_string($filter)) { - $filter = $this->getFilterManager()->get($filter, $options); - } - - if (!$filter instanceof Filter\FilterInterface) { - throw new Exception\InvalidArgumentException('Invalid filter specified'); - } - - $class = get_class($filter); - $this->filters[$class] = $filter; - $files = $this->getFiles($files, true, true); - foreach ($files as $file) { - $this->files[$file]['filters'][] = $class; - } - - return $this; - } - - /** - * Add Multiple filters at once - * - * @param array $filters - * @param string|array $files - * @return AbstractAdapter - */ - public function addFilters(array $filters, $files = null) - { - foreach ($filters as $key => $spec) { - if ($spec instanceof Filter\FilterInterface) { - $this->addFilter($spec, null, $files); - continue; - } - - if (is_string($key)) { - $this->addFilter($key, $spec, $files); - continue; - } - - if (is_int($key)) { - if (is_string($spec)) { - $this->addFilter($spec, null, $files); - continue; - } - - if (is_array($spec)) { - if (!array_key_exists('filter', $spec)) { - continue; - } - - $filter = $spec['filter']; - unset($spec['filter']); - $this->addFilter($filter, $spec, $files); - continue; - } - - continue; - } - } - - return $this; - } - - /** - * Sets a filter for the class, erasing all previous set - * - * @param array $filters Filter to set - * @param string|array $files Files to limit this filter to - * @return Filter\AbstractFilter - */ - public function setFilters(array $filters, $files = null) - { - $this->clearFilters(); - return $this->addFilters($filters, $files); - } - - /** - * Determine if a given filter has already been registered - * - * @param string $name - * @return bool - */ - public function hasFilter($name) - { - return (false !== $this->getFilterIdentifier($name)); - } - - /** - * Retrieve individual filter - * - * @param string $name - * @return Filter\FilterInterface|null - */ - public function getFilter($name) - { - if (false === ($identifier = $this->getFilterIdentifier($name))) { - return null; - } - - return $this->filters[$identifier]; - } - - /** - * Returns all set filters - * - * @param string|array $files (Optional) Returns the filter for this files - * @return array List of set filters - * @throws Exception\RuntimeException When file not found - */ - public function getFilters($files = null) - { - if ($files === null) { - return $this->filters; - } - - $files = $this->getFiles($files, true, true); - $filters = array(); - foreach ($files as $file) { - if (!empty($this->files[$file]['filters'])) { - $filters += $this->files[$file]['filters']; - } - } - - $filters = array_unique($filters); - $result = array(); - foreach ($filters as $filter) { - $result[] = $this->filters[$filter]; - } - - return $result; - } - - /** - * Remove an individual filter - * - * @param string $name - * @return AbstractAdapter - */ - public function removeFilter($name) - { - if (false === ($key = $this->getFilterIdentifier($name))) { - return $this; - } - - unset($this->filters[$key]); - foreach (array_keys($this->files) as $file) { - if (empty($this->files[$file]['filters'])) { - continue; - } - - $index = array_search($key, $this->files[$file]['filters']); - if ($index === false) { - continue; - } - - unset($this->files[$file]['filters'][$index]); - } - return $this; - } - - /** - * Remove all filters - * - * @return AbstractAdapter - */ - public function clearFilters() - { - $this->filters = array(); - foreach (array_keys($this->files) as $file) { - $this->files[$file]['filters'] = array(); - } - - return $this; - } - - /** - * Retrieves the filename of transferred files. - * - * @param string $file (Optional) Element to return the filename for - * @param boolean $path (Optional) Should the path also be returned ? - * @return string|array - */ - public function getFileName($file = null, $path = true) - { - $files = $this->getFiles($file, true, true); - $result = array(); - $directory = ""; - foreach ($files as $file) { - if (empty($this->files[$file]['name'])) { - continue; - } - - if ($path === true) { - $directory = $this->getDestination($file) . DIRECTORY_SEPARATOR; - } - - $result[$file] = $directory . $this->files[$file]['name']; - } - - if (count($result) == 1) { - return current($result); - } - - return $result; - } - - /** - * Retrieve additional internal file informations for files - * - * @param string $file (Optional) File to get informations for - * @return array - */ - public function getFileInfo($file = null) - { - return $this->getFiles($file); - } - - /** - * Sets a new destination for the given files - * - * @deprecated Will be changed to be a filter!!! - * @param string $destination New destination directory - * @param string|array $files Files to set the new destination for - * @return AbstractAdapter - * @throws Exception\InvalidArgumentException when the given destination is not a directory or does not exist - */ - public function setDestination($destination, $files = null) - { - $orig = $files; - $destination = rtrim($destination, "/\\"); - if (!is_dir($destination)) { - throw new Exception\InvalidArgumentException('The given destination is not a directory or does not exist'); - } - - if (!is_writable($destination)) { - throw new Exception\InvalidArgumentException('The given destination is not writeable'); - } - - if ($files === null) { - foreach ($this->files as $file => $content) { - $this->files[$file]['destination'] = $destination; - } - } else { - $files = $this->getFiles($files, true, true); - if (empty($files) and is_string($orig)) { - $this->files[$orig]['destination'] = $destination; - } - - foreach ($files as $file) { - $this->files[$file]['destination'] = $destination; - } - } - - return $this; - } - - /** - * Retrieve destination directory value - * - * @param null|string|array $files - * @throws Exception\InvalidArgumentException - * @return null|string|array - */ - public function getDestination($files = null) - { - $orig = $files; - $files = $this->getFiles($files, false, true); - $destinations = array(); - if (empty($files) and is_string($orig)) { - if (isset($this->files[$orig]['destination'])) { - $destinations[$orig] = $this->files[$orig]['destination']; - } else { - throw new Exception\InvalidArgumentException( - sprintf('The file transfer adapter can not find "%s"', $orig) - ); - } - } - - foreach ($files as $key => $content) { - if (isset($this->files[$key]['destination'])) { - $destinations[$key] = $this->files[$key]['destination']; - } else { - $tmpdir = $this->getTmpDir(); - $this->setDestination($tmpdir, $key); - $destinations[$key] = $tmpdir; - } - } - - if (empty($destinations)) { - $destinations = $this->getTmpDir(); - } elseif (count($destinations) == 1) { - $destinations = current($destinations); - } - - return $destinations; - } - - /** - * Sets translator to use in helper - * - * @param Translator $translator [optional] translator. - * Default is null, which sets no translator. - * @param string $textDomain [optional] text domain - * Default is null, which skips setTranslatorTextDomain - * @return AbstractAdapter - */ - public function setTranslator(Translator $translator = null, $textDomain = null) - { - $this->translator = $translator; - if (null !== $textDomain) { - $this->setTranslatorTextDomain($textDomain); - } - return $this; - } - - /** - * Retrieve localization translator object - * - * @return Translator|null - */ - public function getTranslator() - { - if ($this->isTranslatorEnabled()) { - return null; - } - - return $this->translator; - } - - /** - * Checks if the helper has a translator - * - * @return bool - */ - public function hasTranslator() - { - return (bool) $this->getTranslator(); - } - - /** - * Indicate whether or not translation should be enabled - * - * @param bool $flag - * @return AbstractAdapter - */ - public function setTranslatorEnabled($flag = true) - { - $this->translatorEnabled = (bool) $flag; - return $this; - } - - /** - * Is translation enabled? - * - * @return bool - */ - public function isTranslatorEnabled() - { - return $this->translatorEnabled; - } - - /** - * Set translation text domain - * - * @param string $textDomain - * @return AbstractAdapter - */ - public function setTranslatorTextDomain($textDomain = 'default') - { - $this->translatorTextDomain = $textDomain; - return $this; - } - - /** - * Return the translation text domain - * - * @return string - */ - public function getTranslatorTextDomain() - { - return $this->translatorTextDomain; - } - - /** - * Returns the hash for a given file - * - * @param string $hash Hash algorithm to use - * @param string|array $files Files to return the hash for - * @return string|array Hashstring - * @throws Exception\InvalidArgumentException On unknown hash algorithm - */ - public function getHash($hash = 'crc32', $files = null) - { - if (!in_array($hash, hash_algos())) { - throw new Exception\InvalidArgumentException('Unknown hash algorithm'); - } - - $files = $this->getFiles($files); - $result = array(); - foreach ($files as $key => $value) { - if (file_exists($value['name'])) { - $result[$key] = hash_file($hash, $value['name']); - } elseif (file_exists($value['tmp_name'])) { - $result[$key] = hash_file($hash, $value['tmp_name']); - } elseif (empty($value['options']['ignoreNoFile'])) { - throw new Exception\InvalidArgumentException("The file '{$value['name']}' does not exist"); - } - } - - if (count($result) == 1) { - return current($result); - } - - return $result; - } - - /** - * Returns the real filesize of the file - * - * @param string|array $files Files to get the filesize from - * @return string|array Filesize - * @throws Exception\InvalidArgumentException When the file does not exist - */ - public function getFileSize($files = null) - { - $files = $this->getFiles($files); - $result = array(); - foreach ($files as $key => $value) { - if (file_exists($value['name']) || file_exists($value['tmp_name'])) { - if ($value['options']['useByteString']) { - $result[$key] = self::toByteString($value['size']); - } else { - $result[$key] = $value['size']; - } - } elseif (empty($value['options']['ignoreNoFile'])) { - throw new Exception\InvalidArgumentException("The file '{$value['name']}' does not exist"); - } else { - continue; - } - } - - if (count($result) == 1) { - return current($result); - } - - return $result; - } - - /** - * Internal method to detect the size of a file - * - * @param array $value File infos - * @return string Filesize of given file - */ - protected function detectFileSize($value) - { - if (file_exists($value['name'])) { - $filename = $value['name']; - } elseif (file_exists($value['tmp_name'])) { - $filename = $value['tmp_name']; - } else { - return null; - } - - ErrorHandler::start(); - $filesize = filesize($filename); - $return = ErrorHandler::stop(); - if ($return instanceof ErrorException) { - $filesize = 0; - } - - return sprintf("%u", $filesize); - } - - /** - * Returns the real mimetype of the file - * Uses fileinfo, when not available mime_magic and as last fallback a manual given mimetype - * - * @param string|array $files Files to get the mimetype from - * @return string|array MimeType - * @throws Exception\InvalidArgumentException When the file does not exist - */ - public function getMimeType($files = null) - { - $files = $this->getFiles($files); - $result = array(); - foreach ($files as $key => $value) { - if (file_exists($value['name']) || file_exists($value['tmp_name'])) { - $result[$key] = $value['type']; - } elseif (empty($value['options']['ignoreNoFile'])) { - throw new Exception\InvalidArgumentException("the file '{$value['name']}' does not exist"); - } else { - continue; - } - } - - if (count($result) == 1) { - return current($result); - } - - return $result; - } - - /** - * Internal method to detect the mime type of a file - * - * @param array $value File infos - * @return string Mimetype of given file - */ - protected function detectMimeType($value) - { - if (file_exists($value['name'])) { - $file = $value['name']; - } elseif (file_exists($value['tmp_name'])) { - $file = $value['tmp_name']; - } else { - return null; - } - - if (class_exists('finfo', false)) { - $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME; - if (!empty($value['options']['magicFile'])) { - ErrorHandler::start(); - $mime = finfo_open($const, $value['options']['magicFile']); - ErrorHandler::stop(); - } - - if (empty($mime)) { - ErrorHandler::start(); - $mime = finfo_open($const); - ErrorHandler::stop(); - } - - if (!empty($mime)) { - $result = finfo_file($mime, $file); - } - - unset($mime); - } - - if (empty($result) && (function_exists('mime_content_type') - && ini_get('mime_magic.magicfile'))) { - $result = mime_content_type($file); - } - - if (empty($result)) { - $result = 'application/octet-stream'; - } - - return $result; - } - - /** - * Returns the formatted size - * - * @param integer $size - * @return string - */ - protected static function toByteString($size) - { - $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); - for ($i=0; $size >= 1024 && $i < 9; $i++) { - $size /= 1024; - } - - return round($size, 2) . $sizes[$i]; - } - - /** - * Internal function to filter all given files - * - * @param string|array $files (Optional) Files to check - * @return boolean False on error - */ - protected function filter($files = null) - { - $check = $this->getFiles($files); - foreach ($check as $name => $content) { - if (array_key_exists('filters', $content)) { - foreach ($content['filters'] as $class) { - $filter = $this->filters[$class]; - try { - $result = $filter->filter($this->getFileName($name)); - - $this->files[$name]['destination'] = dirname($result); - $this->files[$name]['name'] = basename($result); - } catch (FilterException\ExceptionInterface $e) { - $this->messages += array($e->getMessage()); - } - } - } - } - - if (count($this->messages) > 0) { - return false; - } - - return true; - } - - /** - * Determine system TMP directory and detect if we have read access - * - * @return string - * @throws Exception\RuntimeException if unable to determine directory - */ - protected function getTmpDir() - { - if (null === $this->tmpDir) { - $tmpdir = array(); - if (function_exists('sys_get_temp_dir')) { - $tmpdir[] = sys_get_temp_dir(); - } - - if (!empty($_ENV['TMP'])) { - $tmpdir[] = realpath($_ENV['TMP']); - } - - if (!empty($_ENV['TMPDIR'])) { - $tmpdir[] = realpath($_ENV['TMPDIR']); - } - - if (!empty($_ENV['TEMP'])) { - $tmpdir[] = realpath($_ENV['TEMP']); - } - - $upload = ini_get('upload_tmp_dir'); - if ($upload) { - $tmpdir[] = realpath($upload); - } - - foreach ($tmpdir as $directory) { - if ($this->isPathWriteable($directory)) { - $this->tmpDir = $directory; - } - } - - if (empty($this->tmpDir)) { - // Attemp to detect by creating a temporary file - $tempFile = tempnam(md5(uniqid(rand(), true)), ''); - if ($tempFile) { - $this->tmpDir = realpath(dirname($tempFile)); - unlink($tempFile); - } else { - throw new Exception\RuntimeException('Could not determine a temporary directory'); - } - } - - $this->tmpDir = rtrim($this->tmpDir, "/\\"); - } - return $this->tmpDir; - } - - /** - * Tries to detect if we can read and write to the given path - * - * @param string $path - * @return bool - */ - protected function isPathWriteable($path) - { - $tempFile = rtrim($path, "/\\"); - $tempFile .= '/' . 'test.1'; - - ErrorHandler::start(); - $result = file_put_contents($tempFile, 'TEST'); - ErrorHandler::stop(); - - if ($result == false) { - return false; - } - - ErrorHandler::start(); - $result = unlink($tempFile); - ErrorHandler::stop(); - - if ($result == false) { - return false; - } - - return true; - } - - /** - * Returns found files based on internal file array and given files - * - * @param string|array $files (Optional) Files to return - * @param boolean $names (Optional) Returns only names on true, else complete info - * @param boolean $noexception (Optional) Allows throwing an exception, otherwise returns an empty array - * @return array Found files - * @throws Exception\RuntimeException On false filename - */ - protected function getFiles($files, $names = false, $noexception = false) - { - $check = array(); - - if (is_string($files)) { - $files = array($files); - } - - if (is_array($files)) { - foreach ($files as $find) { - $found = array(); - foreach ($this->files as $file => $content) { - if (!isset($content['name'])) { - continue; - } - - if (($content['name'] === $find) && isset($content['multifiles'])) { - foreach ($content['multifiles'] as $multifile) { - $found[] = $multifile; - } - break; - } - - if ($file === $find) { - $found[] = $file; - break; - } - - if ($content['name'] === $find) { - $found[] = $file; - break; - } - } - - if (empty($found)) { - if ($noexception !== false) { - return array(); - } - - throw new Exception\RuntimeException(sprintf('The file transfer adapter can not find "%s"', $find)); - } - - foreach ($found as $checked) { - $check[$checked] = $this->files[$checked]; - } - } - } - - if ($files === null) { - $check = $this->files; - $keys = array_keys($check); - foreach ($keys as $key) { - if (isset($check[$key]['multifiles'])) { - unset($check[$key]); - } - } - } - - if ($names) { - $check = array_keys($check); - } - - return $check; - } - - /** - * Retrieve internal identifier for a named validator - * - * @param string $name - * @return string - */ - protected function getValidatorIdentifier($name) - { - if (array_key_exists($name, $this->validators)) { - return $name; - } - - foreach (array_keys($this->validators) as $test) { - if (preg_match('/' . preg_quote($name) . '$/i', $test)) { - return $test; - } - } - - return false; - } - - /** - * Retrieve internal identifier for a named filter - * - * @param string $name - * @return string - */ - protected function getFilterIdentifier($name) - { - if (array_key_exists($name, $this->filters)) { - return $name; - } - - foreach (array_keys($this->filters) as $test) { - if (preg_match('/' . preg_quote($name) . '$/i', $test)) { - return $test; - } - } - - return false; - } -} diff --git a/library/Zend/File/Transfer/Adapter/FilterPluginManager.php b/library/Zend/File/Transfer/Adapter/FilterPluginManager.php deleted file mode 100644 index cae31ddcd82..00000000000 --- a/library/Zend/File/Transfer/Adapter/FilterPluginManager.php +++ /dev/null @@ -1,38 +0,0 @@ -'filedecrypt', - 'encrypt' =>'fileencrypt', - 'lowercase' =>'filelowercase', - 'rename' =>'filerename', - 'uppercase' =>'fileuppercase', - ); -} diff --git a/library/Zend/File/Transfer/Adapter/Http.php b/library/Zend/File/Transfer/Adapter/Http.php deleted file mode 100644 index a1508d318ae..00000000000 --- a/library/Zend/File/Transfer/Adapter/Http.php +++ /dev/null @@ -1,468 +0,0 @@ -setOptions($options); - $this->prepareFiles(); - $this->addValidator('Upload', false, $this->files); - } - - /** - * Sets a validator for the class, erasing all previous set - * - * @param array $validators Validator to set - * @param string|array $files Files to limit this validator to - * @return AbstractAdapter - */ - public function setValidators(array $validators, $files = null) - { - $this->clearValidators(); - return $this->addValidators($validators, $files); - } - - /** - * Remove an individual validator - * - * @param string $name - * @return AbstractAdapter - */ - public function removeValidator($name) - { - if ($name == 'Upload') { - return $this; - } - - return parent::removeValidator($name); - } - - /** - * Clear the validators - * - * @return AbstractAdapter - */ - public function clearValidators() - { - parent::clearValidators(); - $this->addValidator('Upload', false, $this->files); - - return $this; - } - - /** - * Send the file to the client (Download) - * - * @param string|array $options Options for the file(s) to send - * @return void - * @throws Exception\BadMethodCallException Not implemented - */ - public function send($options = null) - { - throw new Exception\BadMethodCallException('Method not implemented'); - } - - /** - * Checks if the files are valid - * - * @param string|array $files (Optional) Files to check - * @return boolean True if all checks are valid - */ - public function isValid($files = null) - { - // Workaround for WebServer not conforming HTTP and omitting CONTENT_LENGTH - $content = 0; - if (isset($_SERVER['CONTENT_LENGTH'])) { - $content = $_SERVER['CONTENT_LENGTH']; - } elseif (!empty($_POST)) { - $content = serialize($_POST); - } - - // Workaround for a PHP error returning empty $_FILES when form data exceeds php settings - if (empty($this->files) && ($content > 0)) { - if (is_array($files)) { - $files = current($files); - } - - $temp = array($files => array( - 'name' => $files, - 'error' => 1)); - $validator = $this->validators['Zend\Validator\File\Upload']; - $validator->setTranslator($this->getTranslator()) - ->setFiles($temp) - ->isValid($files, null); - $this->messages += $validator->getMessages(); - return false; - } - - return parent::isValid($files); - } - - /** - * Receive the file from the client (Upload) - * - * @param string|array $files (Optional) Files to receive - * @return boolean - */ - public function receive($files = null) - { - if (!$this->isValid($files)) { - return false; - } - - $check = $this->getFiles($files); - foreach ($check as $file => $content) { - if (!$content['received']) { - $directory = ''; - $destination = $this->getDestination($file); - if ($destination !== null) { - $directory = $destination . DIRECTORY_SEPARATOR; - } - - $filename = $directory . $content['name']; - $rename = $this->getFilter('Rename'); - if ($rename !== null) { - $tmp = $rename->getNewName($content['tmp_name']); - if ($tmp != $content['tmp_name']) { - $filename = $tmp; - } - - if (dirname($filename) == '.') { - $filename = $directory . $filename; - } - - $key = array_search(get_class($rename), $this->files[$file]['filters']); - unset($this->files[$file]['filters'][$key]); - } - - // Should never return false when it's tested by the upload validator - if (!move_uploaded_file($content['tmp_name'], $filename)) { - if ($content['options']['ignoreNoFile']) { - $this->files[$file]['received'] = true; - $this->files[$file]['filtered'] = true; - continue; - } - - $this->files[$file]['received'] = false; - return false; - } - - if ($rename !== null) { - $this->files[$file]['destination'] = dirname($filename); - $this->files[$file]['name'] = basename($filename); - } - - $this->files[$file]['tmp_name'] = $filename; - $this->files[$file]['received'] = true; - } - - if (!$content['filtered']) { - if (!$this->filter($file)) { - $this->files[$file]['filtered'] = false; - return false; - } - - $this->files[$file]['filtered'] = true; - } - } - - return true; - } - - /** - * Checks if the file was already sent - * - * @param string|array $files Files to check - * @return boolean - * @throws Exception\BadMethodCallException Not implemented - */ - public function isSent($files = null) - { - throw new Exception\BadMethodCallException('Method not implemented'); - } - - /** - * Checks if the file was already received - * - * @param string|array $files (Optional) Files to check - * @return boolean - */ - public function isReceived($files = null) - { - $files = $this->getFiles($files, false, true); - if (empty($files)) { - return false; - } - - foreach ($files as $content) { - if ($content['received'] !== true) { - return false; - } - } - - return true; - } - - /** - * Checks if the file was already filtered - * - * @param string|array $files (Optional) Files to check - * @return boolean - */ - public function isFiltered($files = null) - { - $files = $this->getFiles($files, false, true); - if (empty($files)) { - return false; - } - - foreach ($files as $content) { - if ($content['filtered'] !== true) { - return false; - } - } - - return true; - } - - /** - * Has a file been uploaded ? - * - * @param array|string|null $files - * @return boolean - */ - public function isUploaded($files = null) - { - $files = $this->getFiles($files, false, true); - if (empty($files)) { - return false; - } - - foreach ($files as $file) { - if (empty($file['name'])) { - return false; - } - } - - return true; - } - - /** - * Returns the actual progress of file up-/downloads - * - * @param string|array $id The upload to get the progress for - * @return array|null - * @throws Exception\PhpEnvironmentException whether APC nor UploadProgress extension installed - * @throws Exception\RuntimeException - */ - public static function getProgress($id = null) - { - if (!self::isApcAvailable() && !self::isUploadProgressAvailable()) { - throw new Exception\PhpEnvironmentException('Neither APC nor UploadProgress extension installed'); - } - - $session = 'Zend\File\Transfer\Adapter\Http\ProgressBar'; - $status = array( - 'total' => 0, - 'current' => 0, - 'rate' => 0, - 'message' => '', - 'done' => false - ); - - if (is_array($id)) { - if (isset($id['progress'])) { - $adapter = $id['progress']; - } - - if (isset($id['session'])) { - $session = $id['session']; - } - - if (isset($id['id'])) { - $id = $id['id']; - } else { - unset($id); - } - } - - if (!empty($id) && (($id instanceof Adapter\AbstractAdapter) || ($id instanceof ProgressBar\ProgressBar))) { - $adapter = $id; - unset($id); - } - - if (empty($id)) { - if (!isset($_GET['progress_key'])) { - $status['message'] = 'No upload in progress'; - $status['done'] = true; - } else { - $id = $_GET['progress_key']; - } - } - - if (!empty($id)) { - if (self::isApcAvailable()) { - - $call = call_user_func(self::$callbackApc, ini_get('apc.rfc1867_prefix') . $id); - if (is_array($call)) { - $status = $call + $status; - } - } elseif (self::isUploadProgressAvailable()) { - $call = call_user_func(self::$callbackUploadProgress, $id); - if (is_array($call)) { - $status = $call + $status; - $status['total'] = $status['bytes_total']; - $status['current'] = $status['bytes_uploaded']; - $status['rate'] = $status['speed_average']; - if ($status['total'] == $status['current']) { - $status['done'] = true; - } - } - } - - if (!is_array($call)) { - $status['done'] = true; - $status['message'] = 'Failure while retrieving the upload progress'; - } elseif (!empty($status['cancel_upload'])) { - $status['done'] = true; - $status['message'] = 'The upload has been canceled'; - } else { - $status['message'] = self::toByteString($status['current']) . " - " . self::toByteString($status['total']); - } - - $status['id'] = $id; - } - - if (isset($adapter) && isset($status['id'])) { - if ($adapter instanceof Adapter\AbstractAdapter) { - $adapter = new ProgressBar\ProgressBar($adapter, 0, $status['total'], $session); - } - - if (!($adapter instanceof ProgressBar\ProgressBar)) { - throw new Exception\RuntimeException('Unknown Adapter given'); - } - - if ($status['done']) { - $adapter->finish(); - } else { - $adapter->update($status['current'], $status['message']); - } - - $status['progress'] = $adapter; - } - - return $status; - } - - /** - * Checks the APC extension for progress information - * - * @return boolean - */ - public static function isApcAvailable() - { - return (bool) ini_get('apc.enabled') && (bool) ini_get('apc.rfc1867') && is_callable(self::$callbackApc); - } - - /** - * Checks the UploadProgress extension for progress information - * - * @return boolean - */ - public static function isUploadProgressAvailable() - { - return is_callable(self::$callbackUploadProgress); - } - - /** - * Prepare the $_FILES array to match the internal syntax of one file per entry - * - * @return Http - */ - protected function prepareFiles() - { - $this->files = array(); - foreach ($_FILES as $form => $content) { - if (is_array($content['name'])) { - foreach ($content as $param => $file) { - foreach ($file as $number => $target) { - $this->files[$form . '_' . $number . '_'][$param] = $target; - $this->files[$form]['multifiles'][$number] = $form . '_' . $number . '_'; - } - } - - $this->files[$form]['name'] = $form; - foreach ($this->files[$form]['multifiles'] as $key => $value) { - $this->files[$value]['options'] = $this->options; - $this->files[$value]['validated'] = false; - $this->files[$value]['received'] = false; - $this->files[$value]['filtered'] = false; - - $mimetype = $this->detectMimeType($this->files[$value]); - $this->files[$value]['type'] = $mimetype; - - $filesize = $this->detectFileSize($this->files[$value]); - $this->files[$value]['size'] = $filesize; - - if ($this->options['detectInfos']) { - $_FILES[$form]['type'][$key] = $mimetype; - $_FILES[$form]['size'][$key] = $filesize; - } - } - } else { - $this->files[$form] = $content; - $this->files[$form]['options'] = $this->options; - $this->files[$form]['validated'] = false; - $this->files[$form]['received'] = false; - $this->files[$form]['filtered'] = false; - - $mimetype = $this->detectMimeType($this->files[$form]); - $this->files[$form]['type'] = $mimetype; - - $filesize = $this->detectFileSize($this->files[$form]); - $this->files[$form]['size'] = $filesize; - - if ($this->options['detectInfos']) { - $_FILES[$form]['type'] = $mimetype; - $_FILES[$form]['size'] = $filesize; - } - } - } - - return $this; - } -} diff --git a/library/Zend/File/Transfer/Adapter/ValidatorPluginManager.php b/library/Zend/File/Transfer/Adapter/ValidatorPluginManager.php deleted file mode 100644 index e58e9674b73..00000000000 --- a/library/Zend/File/Transfer/Adapter/ValidatorPluginManager.php +++ /dev/null @@ -1,41 +0,0 @@ -'filecount', - 'crc32' =>'filecrc32', - 'excludeextension' =>'fileexcludeextension', - 'excludemimetype' =>'fileexcludemimetype', - 'exists' =>'fileexists', - 'extension' =>'fileextension', - 'filessize' =>'filefilessize', - 'hash' =>'filehash', - 'imagesize' =>'fileimagesize', - 'iscompressed' =>'fileiscompressed', - 'isimage' =>'fileisimage', - 'md5' =>'filemd5', - 'mimetype' =>'filemimetype', - 'notexists' =>'filenotexists', - 'sha1' =>'filesha1', - 'size' =>'filesize', - 'upload' =>'fileupload', - 'wordcount' =>'filewordcount', - ); -} diff --git a/library/Zend/File/Transfer/Exception/BadMethodCallException.php b/library/Zend/File/Transfer/Exception/BadMethodCallException.php deleted file mode 100644 index f9164a4f173..00000000000 --- a/library/Zend/File/Transfer/Exception/BadMethodCallException.php +++ /dev/null @@ -1,21 +0,0 @@ -setAdapter($adapter, $direction, $options); - } - - /** - * Sets a new adapter - * - * @param string $adapter Adapter to use - * @param boolean $direction OPTIONAL False means Download, true means upload - * @param array $options OPTIONAL Options to set for this adapter - * @return Transfer - * @throws Exception\InvalidArgumentException - */ - public function setAdapter($adapter, $direction = false, $options = array()) - { - if (!is_string($adapter)) { - throw new Exception\InvalidArgumentException('Adapter must be a string'); - } - - if ($adapter[0] != '\\') { - $adapter = '\Zend\File\Transfer\Adapter\\' . ucfirst($adapter); - } - - $direction = (integer) $direction; - $this->adapter[$direction] = new $adapter($options); - if (!$this->adapter[$direction] instanceof Adapter\AbstractAdapter) { - throw new Exception\InvalidArgumentException( - 'Adapter ' . $adapter . ' does not extend Zend\File\Transfer\Adapter\AbstractAdapter' - ); - } - - return $this; - } - - /** - * Returns all set adapters - * - * @param boolean $direction On null, all directions are returned - * On false, download direction is returned - * On true, upload direction is returned - * @return array|Adapter\AbstractAdapter - */ - public function getAdapter($direction = null) - { - if ($direction === null) { - return $this->adapter; - } - - $direction = (integer) $direction; - return $this->adapter[$direction]; - } - - /** - * Calls all methods from the adapter - * - * @param string $method Method to call - * @param array $options Options for this method - * @throws Exception\BadMethodCallException if unknown method - * @return mixed - */ - public function __call($method, array $options) - { - if (array_key_exists('direction', $options)) { - $direction = (integer) $options['direction']; - } else { - $direction = 0; - } - - if (method_exists($this->adapter[$direction], $method)) { - return call_user_func_array(array($this->adapter[$direction], $method), $options); - } - - throw new Exception\BadMethodCallException("Unknown method '" . $method . "' called!"); - } -} diff --git a/library/Zend/File/composer.json b/library/Zend/File/composer.json index eac6a35d984..620194d3d91 100644 --- a/library/Zend/File/composer.json +++ b/library/Zend/File/composer.json @@ -15,11 +15,5 @@ "require": { "php": ">=5.3.3", "zendframework/zend-stdlib": "self.version" - }, - "suggest": { - "zendframework/zend-filter": "Zend\\Filter component", - "zendframework/zend-loader": "Zend\\Loader component", - "zendframework/zend-i18n": "Zend\\I18n component", - "zendframework/zend-validator": "Zend\\Validator component" } } diff --git a/library/Zend/Filter/File/RenameUpload.php b/library/Zend/Filter/File/RenameUpload.php new file mode 100644 index 00000000000..ecf99a49bff --- /dev/null +++ b/library/Zend/Filter/File/RenameUpload.php @@ -0,0 +1,51 @@ +getNewName($value, true); + if (is_string($file)) { + return $file; + } + + ErrorHandler::start(); + $result = move_uploaded_file($file['source'], $file['target']); + $warningException = ErrorHandler::stop(); + if (!$result || null !== $warningException) { + throw new Exception\RuntimeException( + sprintf("File '%s' could not be renamed. An error occurred while processing the file.", $value), + 0, $warningException + ); + } + + return $file['target']; + } +} diff --git a/library/Zend/Filter/FilterPluginManager.php b/library/Zend/Filter/FilterPluginManager.php index 0f58a4e3a4d..7c1e589b578 100644 --- a/library/Zend/Filter/FilterPluginManager.php +++ b/library/Zend/Filter/FilterPluginManager.php @@ -53,6 +53,7 @@ class FilterPluginManager extends AbstractPluginManager 'fileencrypt' => 'Zend\Filter\File\Encrypt', 'filelowercase' => 'Zend\Filter\File\LowerCase', 'filerename' => 'Zend\Filter\File\Rename', + 'filerenameupload' => 'Zend\Filter\File\RenameUpload', 'fileuppercase' => 'Zend\Filter\File\UpperCase', 'htmlentities' => 'Zend\Filter\HtmlEntities', 'inflector' => 'Zend\Filter\Inflector', diff --git a/library/Zend/Form/Element/File.php b/library/Zend/Form/Element/File.php index 48e6e2204c3..e343a28154e 100644 --- a/library/Zend/Form/Element/File.php +++ b/library/Zend/Form/Element/File.php @@ -21,9 +21,13 @@ namespace Zend\Form\Element; +use Zend\Form\Form; use Zend\Form\Element; use Zend\Form\ElementPrepareAwareInterface; -use Zend\Form\Form; +use Zend\Form\Exception; +use Zend\InputFilter\InputProviderInterface; +use Zend\Validator\File\Explode as FileExplodeValidator; +use Zend\Validator\File\Upload as FileUploadValidator; /** * @category Zend @@ -32,7 +36,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class File extends Element implements ElementPrepareAwareInterface +class File extends Element implements InputProviderInterface, ElementPrepareAwareInterface { /** * Seed attributes @@ -43,6 +47,11 @@ class File extends Element implements ElementPrepareAwareInterface 'type' => 'file', ); + /** + * @var ValidatorInterface + */ + protected $validator; + /** * Prepare the form element (mostly used for rendering purposes) * @@ -54,4 +63,46 @@ public function prepareElement(Form $form) // Ensure the form is using correct enctype $form->setAttribute('enctype', 'multipart/form-data'); } + + /** + * Get validator + * + * @return ValidatorInterface + */ + protected function getValidator() + { + if (null === $this->validator) { + $validator = new FileUploadValidator(); + + $multiple = (isset($this->attributes['multiple'])) + ? $this->attributes['multiple'] : null; + + if (true === $multiple || 'multiple' === $multiple) { + $validator = new FileExplodeValidator(array( + 'validator' => $validator + )); + } + + $this->validator = $validator; + } + return $this->validator; + } + + /** + * Should return an array specification compatible with + * {@link Zend\InputFilter\Factory::createInput()}. + * + * @return array + */ + public function getInputSpecification() + { + return array( + 'type' => 'Zend\InputFilter\FileInput', + 'name' => $this->getName(), + 'required' => false, + 'validators' => array( + $this->getValidator(), + ), + ); + } } diff --git a/library/Zend/Form/Element/File/ApcProgress.php b/library/Zend/Form/Element/File/ApcProgress.php new file mode 100644 index 00000000000..4717d24aff3 --- /dev/null +++ b/library/Zend/Form/Element/File/ApcProgress.php @@ -0,0 +1,42 @@ + 'hidden', + 'id' => 'progress_key', + ); + + /** + * Retrieve the element value + * + * @return mixed + */ + public function getValue() + { + if (!isset($this->value)) { + $this->value = uniqid(); + } + return $this->value; + } + + /** + * Get value for name + * + * @return string|int + */ + public function getName() + { + return 'UPLOAD_IDENTIFIER'; + } +} diff --git a/library/Zend/Form/Form.php b/library/Zend/Form/Form.php index 983105dfca6..b7840069ca0 100644 --- a/library/Zend/Form/Form.php +++ b/library/Zend/Form/Form.php @@ -402,6 +402,10 @@ public function hasValidated() */ public function isValid() { + if ($this->hasValidated) { + return $this->isValid; + } + $this->isValid = false; if (!is_array($this->data) && !is_object($this->object)) { diff --git a/library/Zend/Form/View/Helper/FormFile.php b/library/Zend/Form/View/Helper/FormFile.php index d8fda5c9e43..080e3fda8f6 100644 --- a/library/Zend/Form/View/Helper/FormFile.php +++ b/library/Zend/Form/View/Helper/FormFile.php @@ -11,6 +11,7 @@ namespace Zend\Form\View\Helper; use Zend\Form\ElementInterface; +use Zend\Form\Exception; /** * @category Zend @@ -46,4 +47,42 @@ protected function getType(ElementInterface $element) { return 'file'; } + + /** + * Render a form element from the provided $element + * + * @param ElementInterface $element + * @throws Exception\DomainException + * @return string + */ + public function render(ElementInterface $element) + { + $name = $element->getName(); + if ($name === null || $name === '') { + throw new Exception\DomainException(sprintf( + '%s requires that the element has an assigned name; none discovered', + __METHOD__ + )); + } + + $attributes = $element->getAttributes(); + $attributes['type'] = $this->getType($element); + $attributes['name'] = $name; + if (array_key_exists('multiple', $attributes) && $attributes['multiple']) { + $attributes['name'] .= '[]'; + } + + $value = $element->getValue(); + if (is_array($value) && isset($value['name']) && !is_array($value['name'])) { + $attributes['value'] = $value['name']; + } elseif (is_string($value)) { + $attributes['value'] = $value; + } + + return sprintf( + 'createAttributesString($attributes), + $this->getInlineClosingBracket() + ); + } } diff --git a/library/Zend/InputFilter/BaseInputFilter.php b/library/Zend/InputFilter/BaseInputFilter.php index 4297873e424..a407a566ba7 100644 --- a/library/Zend/InputFilter/BaseInputFilter.php +++ b/library/Zend/InputFilter/BaseInputFilter.php @@ -165,6 +165,11 @@ public function isValid() if (!array_key_exists($name, $this->data) || (null === $this->data[$name]) || (is_string($this->data[$name]) && strlen($this->data[$name]) === 0) + // Single and Multi File Uploads + || (is_array($this->data[$name]) + && isset($this->data[$name]['error']) && $this->data[$name]['error'] === UPLOAD_ERR_NO_FILE) + || (is_array($this->data[$name]) && count($this->data[$name]) === 1 + && isset($this->data[$name][0]['error']) && $this->data[$name][0]['error'] === UPLOAD_ERR_NO_FILE) ) { if ($input instanceof InputInterface) { // - test if input is required diff --git a/library/Zend/InputFilter/FileInput.php b/library/Zend/InputFilter/FileInput.php new file mode 100644 index 00000000000..52e2a02c954 --- /dev/null +++ b/library/Zend/InputFilter/FileInput.php @@ -0,0 +1,62 @@ +getFilterChain(); + $value = (is_array($this->value) && isset($this->value['tmp_name'])) + ? $this->value['tmp_name'] : $this->value; + if ($this->isValid) { + $value = $filter->filter($value); + } + return $value; + } + + /** + * @param mixed $context Extra "context" to provide the validator + * @return boolean + */ + public function isValid($context = null) + { + $this->injectNotEmptyValidator(); + $validator = $this->getValidatorChain(); + //$value = $this->getValue(); // Do not run the filters yet for File uploads + $this->isValid = $validator->isValid($this->getRawValue(), $context); + return $this->isValid; + } + + /** + * @return void + */ + protected function injectNotEmptyValidator() + { + $this->notEmptyValidator = true; + } +} diff --git a/library/Zend/InputFilter/Input.php b/library/Zend/InputFilter/Input.php index 42390c959a6..bc354c960fb 100644 --- a/library/Zend/InputFilter/Input.php +++ b/library/Zend/InputFilter/Input.php @@ -309,6 +309,9 @@ public function getMessages() return $validator->getMessages(); } + /** + * @return void + */ protected function injectNotEmptyValidator() { if ((!$this->isRequired() && $this->allowEmpty()) || $this->notEmptyValidator) { diff --git a/library/Zend/Mvc/Controller/Plugin/FilePostRedirectGet.php b/library/Zend/Mvc/Controller/Plugin/FilePostRedirectGet.php new file mode 100644 index 00000000000..4fa5d2cf3bd --- /dev/null +++ b/library/Zend/Mvc/Controller/Plugin/FilePostRedirectGet.php @@ -0,0 +1,117 @@ +getController(); + $request = $controller->getRequest(); + $container = $this->getSessionContainer(); + + if ($request->isPost()) { + $post = array_merge( + $request->getPost()->toArray(), + $request->getFiles()->toArray() + ); + $container->post = $post; + + $form->setData($post); + if (!$form->isValid()) { + $container->errors = $form->getMessages(); + } + + return $this->redirect($redirect, $redirectToUrl); + } else { + if (null !== $container->post) { + $post = $container->post; + $errors = $container->errors; + unset($container->post); + unset($container->errors); + + $form->setData($post); + if (null !== $errors) { + $form->setMessages($errors); + } + + return $post; + } + + return false; + } + } + + protected function getSessionContainer() + { + if (!isset($this->sessionContainer)) { + $this->sessionContainer = new Container('file_prg_post1'); + $this->sessionContainer->setExpirationHops(1, array('post', 'errors')); + } + return $this->sessionContainer; + } + + protected function redirect($redirect, $redirectToUrl) + { + $controller = $this->getController(); + $params = array(); + + if (null === $redirect) { + $routeMatch = $controller->getEvent()->getRouteMatch(); + + $redirect = $routeMatch->getMatchedRouteName(); + $params = $routeMatch->getParams(); + } + + if (method_exists($controller, 'getPluginManager')) { + // get the redirect plugin from the plugin manager + $redirector = $controller->getPluginManager()->get('Redirect'); + } else { + /* + * If the user wants to redirect to a route, the redirector has to come + * from the plugin manager -- otherwise no router will be injected + */ + if ($redirectToUrl === false) { + throw new RuntimeException('Could not redirect to a route without a router'); + } + + $redirector = new Redirect(); + } + + if ($redirectToUrl === false) { + $response = $redirector->toRoute($redirect, $params); + $response->setStatusCode(303); + return $response; + } + + $response = $redirector->toUrl($redirect); + $response->setStatusCode(303); + + return $response; + } +} diff --git a/library/Zend/Mvc/Controller/Plugin/PostRedirectGet.php b/library/Zend/Mvc/Controller/Plugin/PostRedirectGet.php index 83e88508178..0428352a2f8 100644 --- a/library/Zend/Mvc/Controller/Plugin/PostRedirectGet.php +++ b/library/Zend/Mvc/Controller/Plugin/PostRedirectGet.php @@ -23,10 +23,43 @@ */ class PostRedirectGet extends AbstractPlugin { + /** + * @var Container + */ + protected $sessionContainer; + public function __invoke($redirect = null, $redirectToUrl = false) { $controller = $this->getController(); $request = $controller->getRequest(); + $container = $this->getSessionContainer(); + + if ($request->isPost()) { + $container->post = $request->getPost()->toArray(); + return $this->redirect($redirect, $redirectToUrl); + } else { + if ($container->post !== null) { + $post = $container->post; + unset($container->post); + return $post; + } + + return false; + } + } + + protected function getSessionContainer() + { + if (!isset($this->sessionContainer)) { + $this->sessionContainer = new Container('prg_post1'); + $this->sessionContainer->setExpirationHops(1, 'post'); + } + return $this->sessionContainer; + } + + protected function redirect($redirect, $redirectToUrl) + { + $controller = $this->getController(); $params = array(); if (null === $redirect) { @@ -36,45 +69,30 @@ public function __invoke($redirect = null, $redirectToUrl = false) $params = $routeMatch->getParams(); } - $container = new Container('prg_post1'); - - if ($request->isPost()) { - $container->setExpirationHops(1, 'post'); - $container->post = $request->getPost()->toArray(); - - if (method_exists($controller, 'getPluginManager')) { - // get the redirect plugin from the plugin manager - $redirector = $controller->getPluginManager()->get('Redirect'); - } else { - /* - * If the user wants to redirect to a route, the redirector has to come - * from the plugin manager -- otherwise no router will be injected - */ - if ($redirectToUrl === false) { - throw new RuntimeException('Could not redirect to a route without a router'); - } - - $redirector = new Redirect(); - } - + if (method_exists($controller, 'getPluginManager')) { + // get the redirect plugin from the plugin manager + $redirector = $controller->getPluginManager()->get('Redirect'); + } else { + /* + * If the user wants to redirect to a route, the redirector has to come + * from the plugin manager -- otherwise no router will be injected + */ if ($redirectToUrl === false) { - $response = $redirector->toRoute($redirect, $params); - $response->setStatusCode(303); - return $response; + throw new RuntimeException('Could not redirect to a route without a router'); } - $response = $redirector->toUrl($redirect); - $response->setStatusCode(303); + $redirector = new Redirect(); + } + if ($redirectToUrl === false) { + $response = $redirector->toRoute($redirect, $params); + $response->setStatusCode(303); return $response; - } else { - if ($container->post !== null) { - $post = $container->post; - unset($container->post); - return $post; - } - - return false; } + + $response = $redirector->toUrl($redirect); + $response->setStatusCode(303); + + return $response; } } diff --git a/library/Zend/Mvc/Controller/PluginManager.php b/library/Zend/Mvc/Controller/PluginManager.php index 4466dbb32fc..0bd0dab6c9e 100644 --- a/library/Zend/Mvc/Controller/PluginManager.php +++ b/library/Zend/Mvc/Controller/PluginManager.php @@ -33,13 +33,14 @@ class PluginManager extends AbstractPluginManager * @var array */ protected $invokableClasses = array( - 'flashmessenger' => 'Zend\Mvc\Controller\Plugin\FlashMessenger', - 'forward' => 'Zend\Mvc\Controller\Plugin\Forward', - 'layout' => 'Zend\Mvc\Controller\Plugin\Layout', - 'params' => 'Zend\Mvc\Controller\Plugin\Params', - 'postredirectget' => 'Zend\Mvc\Controller\Plugin\PostRedirectGet', - 'redirect' => 'Zend\Mvc\Controller\Plugin\Redirect', - 'url' => 'Zend\Mvc\Controller\Plugin\Url', + 'flashmessenger' => 'Zend\Mvc\Controller\Plugin\FlashMessenger', + 'forward' => 'Zend\Mvc\Controller\Plugin\Forward', + 'layout' => 'Zend\Mvc\Controller\Plugin\Layout', + 'params' => 'Zend\Mvc\Controller\Plugin\Params', + 'postredirectget' => 'Zend\Mvc\Controller\Plugin\PostRedirectGet', + 'filepostredirectget' => 'Zend\Mvc\Controller\Plugin\FilePostRedirectGet', + 'redirect' => 'Zend\Mvc\Controller\Plugin\Redirect', + 'url' => 'Zend\Mvc\Controller\Plugin\Url', ); /** @@ -48,7 +49,8 @@ class PluginManager extends AbstractPluginManager * @var array */ protected $aliases = array( - 'prg' => 'postredirectget', + 'prg' => 'postredirectget', + 'fileprg' => 'filepostredirectget', ); /** diff --git a/library/Zend/File/Transfer/Exception/PhpEnvironmentException.php b/library/Zend/ProgressBar/Exception/PhpEnvironmentException.php similarity index 79% rename from library/Zend/File/Transfer/Exception/PhpEnvironmentException.php rename to library/Zend/ProgressBar/Exception/PhpEnvironmentException.php index a271344532f..2cf35b42268 100644 --- a/library/Zend/File/Transfer/Exception/PhpEnvironmentException.php +++ b/library/Zend/ProgressBar/Exception/PhpEnvironmentException.php @@ -5,14 +5,14 @@ * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @package Zend_File + * @package Zend_ProgressBar */ -namespace Zend\File\Transfer\Exception; +namespace Zend\ProgressBar\Exception; /** * @category Zend - * @package Zend_File_Transfer + * @package Zend_ProgressBar */ class PhpEnvironmentException extends RuntimeException {} diff --git a/library/Zend/ProgressBar/Upload/AbstractUploadHandler.php b/library/Zend/ProgressBar/Upload/AbstractUploadHandler.php new file mode 100644 index 00000000000..822f000359f --- /dev/null +++ b/library/Zend/ProgressBar/Upload/AbstractUploadHandler.php @@ -0,0 +1,185 @@ +setOptions($options); + } + } + + /** + * Set options for a upload handler. Accepted options are: + * - session_namespace: session namespace for upload progress + * - progress_adapter: progressbar adapter to use for updating progress + * + * @param array|\Traversable $options + * @return AbstractUploadHandler + * @throws Exception\InvalidArgumentException + */ + public function setOptions($options) + { + if ($options instanceof Traversable) { + $options = ArrayUtils::iteratorToArray($options); + } elseif (!is_array($options)) { + throw new Exception\InvalidArgumentException( + 'The options parameter must be an array or a Traversable' + ); + } + + if (isset($options['session_namespace'])) { + $this->setSessionNamespace($options['session_namespace']); + } + if (isset($options['progress_adapter'])) { + $this->setProgressAdapter($options['progress_adapter']); + } + + return $this; + } + + /** + * @param string $sessionNamespace + * @return AbstractUploadHandler|UploadHandlerInterface + */ + public function setSessionNamespace($sessionNamespace) + { + $this->sessionNamespace = $sessionNamespace; + return $this; + } + + /** + * @return string + */ + public function getSessionNamespace() + { + return $this->sessionNamespace; + } + + /** + * @param AbstractProgressAdapter|ProgressBar $progressAdapter + * @return AbstractUploadHandler|UploadHandlerInterface + */ + public function setProgressAdapter($progressAdapter) + { + $this->progressAdapter = $progressAdapter; + return $this; + } + + /** + * @return AbstractProgressAdapter|ProgressBar + */ + public function getProgressAdapter() + { + return $this->progressAdapter; + } + + /** + * @param string $id + * @return array + */ + public function getProgress($id) + { + $status = array( + 'total' => 0, + 'current' => 0, + 'rate' => 0, + 'message' => 'No upload in progress', + 'done' => true + ); + if (empty($id)) { + return $status; + } + + $newStatus = $this->getUploadProgress($id); + if (false === $newStatus) { + return $status; + } + $status = $newStatus; + if ('' === $status['message']) { + $status['message'] = $this->toByteString($status['current']) . + " - " . $this->toByteString($status['total']); + } + $status['id'] = $id; + + $adapter = $this->getProgressAdapter(); + if (isset($adapter)) { + if ($adapter instanceof AbstractProgressAdapter) { + $adapter = new ProgressBar( + $adapter, 0, $status['total'], $this->getSessionNamespace() + ); + $this->setProgressAdapter($adapter); + } + + if (!$adapter instanceof ProgressBar) { + throw new Exception\RuntimeException('Unknown Adapter type given'); + } + + if ($status['done']) { + $adapter->finish(); + } else { + $adapter->update($status['current'], $status['message']); + } + } + + return $status; + } + + /** + * @param string $id + * @return array|boolean + */ + abstract protected function getUploadProgress($id); + + /** + * Returns the formatted size + * + * @param integer $size + * @return string + */ + protected function toByteString($size) + { + $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); + for ($i=0; $size >= 1024 && $i < 9; $i++) { + $size /= 1024; + } + + return round($size, 2) . $sizes[$i]; + } +} diff --git a/library/Zend/ProgressBar/Upload/ApcProgress.php b/library/Zend/ProgressBar/Upload/ApcProgress.php new file mode 100644 index 00000000000..3273208671a --- /dev/null +++ b/library/Zend/ProgressBar/Upload/ApcProgress.php @@ -0,0 +1,68 @@ +isApcAvailable()) { + throw new Exception\PhpEnvironmentException('APC extension is not installed'); + } + + $uploadInfo = apc_fetch(ini_get('apc.rfc1867_prefix') . $id); + if (!is_array($uploadInfo)) { + return false; + } + + $status = array( + 'total' => 0, + 'current' => 0, + 'rate' => 0, + 'message' => '', + 'done' => false + ); + $status = $uploadInfo + $status; + if (!empty($status['cancel_upload'])) { + $status['done'] = true; + $status['message'] = 'The upload has been canceled'; + } + + return $status; + } + + /** + * Checks for the APC extension + * + * @return boolean + */ + public function isApcAvailable() + { + return (bool) ini_get('apc.enabled') + && (bool) ini_get('apc.rfc1867') + && is_callable('apc_fetch'); + } +} diff --git a/library/Zend/ProgressBar/Upload/SessionProgress.php b/library/Zend/ProgressBar/Upload/SessionProgress.php new file mode 100644 index 00000000000..5cf6cbf0857 --- /dev/null +++ b/library/Zend/ProgressBar/Upload/SessionProgress.php @@ -0,0 +1,72 @@ +isSessionUploadProgressAvailable()) { + throw new Exception\PhpEnvironmentException( + 'Session Upload Progress is not available' + ); + } + + $uploadInfo = $_SESSION[ini_get('session.upload_progress.prefix') . $id]; + if (!is_array($uploadInfo)) { + return false; + } + + $status = array( + 'total' => 0, + 'current' => 0, + 'rate' => 0, + 'message' => '', + 'done' => false + ); + $status = $uploadInfo + $status; + $status['total'] = $status['content_length']; + $status['current'] = $status['bytes_processed']; + $status['rate'] = $status['bytes_processed'] / (time() - $status['start_time']); + if (!empty($status['cancel_upload'])) { + $status['done'] = true; + $status['message'] = 'The upload has been canceled'; + } + + return $status; + } + + /** + * Checks if Session Upload Progress is available + * + * @return boolean + */ + public function isSessionUploadProgressAvailable() + { + return (bool) version_compare(PHP_VERSION, '5.4.0rc1', '>=') + && (bool) ini_get('session.upload_progress.enabled'); + } +} diff --git a/library/Zend/ProgressBar/Upload/UploadHandlerInterface.php b/library/Zend/ProgressBar/Upload/UploadHandlerInterface.php new file mode 100644 index 00000000000..ff65de56742 --- /dev/null +++ b/library/Zend/ProgressBar/Upload/UploadHandlerInterface.php @@ -0,0 +1,29 @@ +isUploadProgressAvailable()) { + throw new Exception\PhpEnvironmentException( + 'UploadProgress extension is not installed' + ); + } + + $uploadInfo = uploadprogress_get_info($id); + if (!is_array($uploadInfo)) { + return false; + } + + $status = array( + 'total' => 0, + 'current' => 0, + 'rate' => 0, + 'message' => '', + 'done' => false + ); + $status = $uploadInfo + $status; + $status['total'] = $status['bytes_total']; + $status['current'] = $status['bytes_uploaded']; + $status['rate'] = $status['speed_average']; + if ($status['total'] == $status['current']) { + $status['done'] = true; + } + + return $status; + } + + /** + * Checks for the UploadProgress extension + * + * @return boolean + */ + public function isUploadProgressAvailable() + { + return is_callable('uploadprogress_get_info'); + } +} diff --git a/library/Zend/Validator/File/Count.php b/library/Zend/Validator/File/Count.php deleted file mode 100644 index 2737f086f96..00000000000 --- a/library/Zend/Validator/File/Count.php +++ /dev/null @@ -1,252 +0,0 @@ - "Too many files, maximum '%max%' are allowed but '%count%' are given", - self::TOO_FEW => "Too few files, minimum '%min%' are expected but '%count%' are given", - ); - - /** - * @var array Error message template variables - */ - protected $messageVariables = array( - 'min' => array('options' => 'min'), - 'max' => array('options' => 'max'), - 'count' => 'count' - ); - - /** - * Actual filecount - * - * @var integer - */ - protected $count; - - /** - * Internal file array - * @var array - */ - protected $files; - - /** - * Options for this validator - * - * @var array - */ - protected $options = array( - 'min' => null, // Minimum file count, if null there is no minimum file count - 'max' => null, // Maximum file count, if null there is no maximum file count - ); - - /** - * Sets validator options - * - * Min limits the file count, when used with max=null it is the maximum file count - * It also accepts an array with the keys 'min' and 'max' - * - * If $options is a integer, it will be used as maximum file count - * As Array is accepts the following keys: - * 'min': Minimum filecount - * 'max': Maximum filecount - * - * @param integer|array|\Traversable $options Options for the adapter - */ - public function __construct($options = null) - { - if (is_string($options) || is_numeric($options)) { - $options = array('max' => $options); - } - - if (1 < func_num_args()) { - $options['min'] = func_get_arg(0); - $options['max'] = func_get_arg(1); - } - - parent::__construct($options); - } - - /** - * Returns the minimum file count - * - * @return integer - */ - public function getMin() - { - return $this->options['min']; - } - - /** - * Sets the minimum file count - * - * @param integer|array $min The minimum file count - * @return Count Provides a fluent interface - * @throws Exception\InvalidArgumentException When min is greater than max - */ - public function setMin($min) - { - if (is_array($min) and isset($min['min'])) { - $min = $min['min']; - } - - if (!is_string($min) and !is_numeric($min)) { - throw new Exception\InvalidArgumentException('Invalid options to validator provided'); - } - - $min = (integer) $min; - if (($this->getMax() !== null) && ($min > $this->getMax())) { - throw new Exception\InvalidArgumentException("The minimum must be less than or equal to the maximum file count, but $min >" - . " {$this->getMax()}"); - } - - $this->options['min'] = $min; - return $this; - } - - /** - * Returns the maximum file count - * - * @return integer - */ - public function getMax() - { - return $this->options['max']; - } - - /** - * Sets the maximum file count - * - * @param integer|array $max The maximum file count - * @return Count Provides a fluent interface - * @throws Exception\InvalidArgumentException When max is smaller than min - */ - public function setMax($max) - { - if (is_array($max) and isset($max['max'])) { - $max = $max['max']; - } - - if (!is_string($max) and !is_numeric($max)) { - throw new Exception\InvalidArgumentException('Invalid options to validator provided'); - } - - $max = (integer) $max; - if (($this->getMin() !== null) && ($max < $this->getMin())) { - throw new Exception\InvalidArgumentException("The maximum must be greater than or equal to the minimum file count, but " - . "$max < {$this->getMin()}"); - } - - $this->options['max'] = $max; - return $this; - } - - /** - * Adds a file for validation - * - * @param string|array $file - * @return Count - */ - public function addFile($file) - { - if (is_string($file)) { - $file = array($file); - } - - if (is_array($file)) { - foreach ($file as $name) { - if (!isset($this->files[$name]) && !empty($name)) { - $this->files[$name] = $name; - } - } - } - - return $this; - } - - /** - * Returns true if and only if the file count of all checked files is at least min and - * not bigger than max (when max is not null). Attention: When checking with set min you - * must give all files with the first call, otherwise you will get an false. - * - * @param string|array $value Filenames to check for count - * @param array $file File data from \Zend\File\Transfer\Transfer - * @return boolean - */ - public function isValid($value, $file = null) - { - if (($file !== null) && !array_key_exists('destination', $file)) { - $file['destination'] = dirname($value); - } - - if (($file !== null) && array_key_exists('tmp_name', $file)) { - $value = $file['destination'] . DIRECTORY_SEPARATOR . $file['name']; - } - - if (($file === null) || !empty($file['tmp_name'])) { - $this->addFile($value); - } - - $this->count = count($this->files); - if (($this->getMax() !== null) && ($this->count > $this->getMax())) { - return $this->throwError($file, self::TOO_MANY); - } - - if (($this->getMin() !== null) && ($this->count < $this->getMin())) { - return $this->throwError($file, self::TOO_FEW); - } - - return true; - } - - /** - * Throws an error of the given type - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function throwError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $this->value = $file['name']; - } - } elseif (is_string($file)) { - $this->value = $file; - } - } - - $this->error($errorType); - return false; - } -} diff --git a/library/Zend/Validator/File/Crc32.php b/library/Zend/Validator/File/Crc32.php index 2103e15e11f..676df339528 100644 --- a/library/Zend/Validator/File/Crc32.php +++ b/library/Zend/Validator/File/Crc32.php @@ -10,6 +10,8 @@ namespace Zend\Validator\File; +use Zend\Validator\Exception; + /** * Validator for the crc32 hash of given files * @@ -29,9 +31,9 @@ class Crc32 extends Hash * @var array Error message templates */ protected $messageTemplates = array( - self::DOES_NOT_MATCH => "File '%value%' does not match the given crc32 hashes", + self::DOES_NOT_MATCH => "File does not match the given crc32 hashes", self::NOT_DETECTED => "A crc32 hash could not be evaluated for the given file", - self::NOT_FOUND => "File '%value%' is not readable or does not exist", + self::NOT_FOUND => "File is not readable or does not exist", ); /** @@ -81,25 +83,36 @@ public function addCrc32($options) /** * Returns true if and only if the given file confirms the set hash * - * @param string $value Filename to check for hash - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Filename to check for hash * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_FOUND); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_FOUND); + return false; } $hashes = array_unique(array_keys($this->getHash())); - $filehash = hash_file('crc32', $value); + $filehash = hash_file('crc32', $file); if ($filehash === false) { - return $this->throwError($file, self::NOT_DETECTED); + $this->error(self::NOT_DETECTED); + return false; } foreach ($hashes as $hash) { @@ -108,6 +121,7 @@ public function isValid($value, $file = null) } } - return $this->throwError($file, self::DOES_NOT_MATCH); + $this->error(self::DOES_NOT_MATCH); + return false; } } diff --git a/library/Zend/Validator/File/ExcludeExtension.php b/library/Zend/Validator/File/ExcludeExtension.php index 0ac8d6e38fd..27010324f96 100644 --- a/library/Zend/Validator/File/ExcludeExtension.php +++ b/library/Zend/Validator/File/ExcludeExtension.php @@ -10,6 +10,8 @@ namespace Zend\Validator\File; +use Zend\Validator\Exception; + /** * Validator for the excluding file extensions * @@ -28,52 +30,56 @@ class ExcludeExtension extends Extension * @var array Error message templates */ protected $messageTemplates = array( - self::FALSE_EXTENSION => "File '%value%' has a false extension", - self::NOT_FOUND => "File '%value%' is not readable or does not exist", + self::FALSE_EXTENSION => "File has an incorrect extension", + self::NOT_FOUND => "File is not readable or does not exist", ); /** * Returns true if and only if the file extension of $value is not included in the * set extension list * - * @param string $value Real file to check for extension - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Real file to check for extension * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_FOUND); - } - - if ($file !== null) { - $info['extension'] = substr($file['name'], strrpos($file['name'], '.') + 1); - } else { - $info = pathinfo($value); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_FOUND); + return false; } + $extension = substr($filename, strrpos($filename, '.') + 1); $extensions = $this->getExtension(); - if ($this->getCase() and (!in_array($info['extension'], $extensions))) { + if ($this->getCase() and (!in_array($extension, $extensions))) { return true; } elseif (!$this->getCase()) { - $found = false; - foreach ($extensions as $extension) { - if (strtolower($extension) == strtolower($info['extension'])) { - $found = true; + foreach ($extensions as $ext) { + if (strtolower($ext) == strtolower($extension)) { + $this->error(self::FALSE_EXTENSION); + return false; } } - if (!$found) { - return true; - } + return true; } - return $this->throwError($file, self::FALSE_EXTENSION); + $this->error(self::FALSE_EXTENSION); + return false; } } diff --git a/library/Zend/Validator/File/ExcludeMimeType.php b/library/Zend/Validator/File/ExcludeMimeType.php index a94124c58cf..c0ab10944d1 100644 --- a/library/Zend/Validator/File/ExcludeMimeType.php +++ b/library/Zend/Validator/File/ExcludeMimeType.php @@ -11,6 +11,7 @@ namespace Zend\Validator\File; use finfo; +use Zend\Validator\Exception; /** * Validator for the mime type of a file @@ -29,22 +30,31 @@ class ExcludeMimeType extends MimeType * of mimetypes can be checked. If you give for example "image" all image * mime types will not be accepted like "image/gif", "image/jpeg" and so on. * - * @param string $value Real file to check for mimetype - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Real file to check for mimetype * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array( - 'type' => null, - 'name' => $value, - ); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name']) || !isset($value['type'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + $filetype = $value['type']; + } else { + $file = $value; + $filename = basename($file); + $filetype = null; } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->createError($file, self::NOT_READABLE); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_READABLE); + return false; } $mimefile = $this->getMagicFile(); @@ -60,27 +70,29 @@ public function isValid($value, $file = null) $this->type = null; if (!empty($this->finfo)) { - $this->type = finfo_file($this->finfo, $value); + $this->type = finfo_file($this->finfo, $file); } } if (empty($this->type) && (function_exists('mime_content_type') && ini_get('mime_magic.magicfile')) ) { - $this->type = mime_content_type($value); + $this->type = mime_content_type($file); } if (empty($this->type) && $this->getHeaderCheck()) { - $this->type = $file['type']; + $this->type = $filetype; } if (empty($this->type)) { - return $this->createError($file, self::NOT_DETECTED); + $this->error(self::NOT_DETECTED); + false; } $mimetype = $this->getMimeType(true); if (in_array($this->type, $mimetype)) { - return $this->createError($file, self::FALSE_TYPE); + $this->error(self::FALSE_TYPE); + return false; } $types = explode('/', $this->type); @@ -88,7 +100,8 @@ public function isValid($value, $file = null) $types = array_merge($types, explode(';', $this->type)); foreach ($mimetype as $mime) { if (in_array($mime, $types)) { - return $this->createError($file, self::FALSE_TYPE); + $this->error(self::FALSE_TYPE); + return false; } } diff --git a/library/Zend/Validator/File/Exists.php b/library/Zend/Validator/File/Exists.php index 52b47ed0d4c..760f2b0e9c3 100644 --- a/library/Zend/Validator/File/Exists.php +++ b/library/Zend/Validator/File/Exists.php @@ -30,7 +30,7 @@ class Exists extends AbstractValidator * @var array Error message templates */ protected $messageTemplates = array( - self::DOES_NOT_EXIST => "File '%value%' does not exist", + self::DOES_NOT_EXIST => "File does not exist", ); /** @@ -71,14 +71,14 @@ public function __construct($options = null) * Returns the set file directories which are checked * * @param boolean $asArray Returns the values as array, when false an concatenated string is returned - * @return string + * @return string|null */ public function getDirectory($asArray = false) { $asArray = (bool) $asArray; - $directory = (string) $this->options['directory']; - if ($asArray) { - $directory = explode(',', $directory); + $directory = $this->options['directory']; + if ($asArray && isset($directory)) { + $directory = explode(',', (string)$directory); } return $directory; @@ -107,6 +107,9 @@ public function setDirectory($directory) public function addDirectory($directory) { $directories = $this->getDirectory(true); + if (!isset($directories)) { + $directories = array(); + } if (is_string($directory)) { $directory = explode(',', $directory); @@ -130,7 +133,8 @@ public function addDirectory($directory) } } - $this->options['directory'] = implode(',', $directories); + $this->options['directory'] = (!empty($directory)) + ? implode(',', $directories) : null; return $this; } @@ -138,58 +142,53 @@ public function addDirectory($directory) /** * Returns true if and only if the file already exists in the set directories * - * @param string $value Real file to check for existence - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Real file to check for existence * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - $directories = $this->getDirectory(true); - if (($file !== null) and (!empty($file['destination']))) { - $directories[] = $file['destination']; - } elseif (!isset($file['name'])) { - $file['name'] = $value; + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = basename($file); + $this->setValue($value['name']); + } else { + $file = $value; + $filename = basename($file); + $this->setValue($filename); } $check = false; - foreach ($directories as $directory) { - if (empty($directory)) { - continue; + $directories = $this->getDirectory(true); + if (!isset($directories)) { + $check = true; + if (!file_exists($file)) { + $this->error(self::DOES_NOT_EXIST); + return false; } + } else { + foreach ($directories as $directory) { + if (!isset($directory) || '' === $directory) { + continue; + } - $check = true; - if (!file_exists($directory . DIRECTORY_SEPARATOR . $file['name'])) { - return $this->throwError($file, self::DOES_NOT_EXIST); + $check = true; + if (!file_exists($directory . DIRECTORY_SEPARATOR . $filename)) { + $this->error(self::DOES_NOT_EXIST); + return false; + } } } if (!$check) { - return $this->throwError($file, self::DOES_NOT_EXIST); + $this->error(self::DOES_NOT_EXIST); + return false; } return true; } - - /** - * Throws an error of the given type - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function throwError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $this->value = basename($file['name']); - } - } elseif (is_string($file)) { - $this->value = basename($file); - } - } - - $this->error($errorType); - return false; - } } diff --git a/library/Zend/Validator/File/Explode.php b/library/Zend/Validator/File/Explode.php new file mode 100644 index 00000000000..60d8d974da5 --- /dev/null +++ b/library/Zend/Validator/File/Explode.php @@ -0,0 +1,76 @@ + "Invalid type given. File array expected", + ); + + /** + * Defined by Zend_Validate_Interface + * + * Returns true if all values validate true + * + * @param array $value + * @return boolean + * @throws Exception\RuntimeException + */ + public function isValid($value) + { + if (!is_array($value)) { + $this->error(self::INVALID); + return false; + } + + $values = $value; + $this->setValue($value); + + $retval = true; + $messages = array(); + $validator = $this->getValidator(); + + if (!$validator) { + throw new Exception\RuntimeException(sprintf( + '%s expects a validator to be set; none given', + __METHOD__ + )); + } + + foreach ($values as $value) { + if (!$validator->isValid($value)) { + $messages[] = $validator->getMessages(); + $retval = false; + + if ($this->isBreakOnFirstFailure()) { + break; + } + } + } + + $this->abstractOptions['messages'] = $messages; + + return $retval; + } +} diff --git a/library/Zend/Validator/File/Extension.php b/library/Zend/Validator/File/Extension.php index 567d35f1db0..e59346096c0 100644 --- a/library/Zend/Validator/File/Extension.php +++ b/library/Zend/Validator/File/Extension.php @@ -13,7 +13,7 @@ use Traversable; use Zend\Stdlib\ArrayUtils; use Zend\Validator\AbstractValidator; - +use Zend\Validator\Exception; /** * Validator for the file extension of a file * @@ -32,8 +32,8 @@ class Extension extends AbstractValidator * @var array Error message templates */ protected $messageTemplates = array( - self::FALSE_EXTENSION => "File '%value%' has a false extension", - self::NOT_FOUND => "File '%value%' is not readable or does not exist", + self::FALSE_EXTENSION => "File has an incorrect extension", + self::NOT_FOUND => "File is not readable or does not exist", ); /** @@ -42,8 +42,8 @@ class Extension extends AbstractValidator * @var array */ protected $options = array( - 'case' => false, // Validate case sensitive - 'extension' => '', // List of extensions + 'case' => false, // Validate case sensitive + 'extension' => '', // List of extensions ); /** @@ -174,62 +174,45 @@ public function addExtension($extension) * Returns true if and only if the file extension of $value is included in the * set extension list * - * @param string $value Real file to check for extension - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Real file to check for extension * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_FOUND); - } - - if ($file !== null) { - $info['extension'] = substr($file['name'], strrpos($file['name'], '.') + 1); - } else { - $info = pathinfo($value); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_FOUND); + return false; } + $extension = substr($filename, strrpos($filename, '.') + 1); $extensions = $this->getExtension(); - if ($this->getCase() && (in_array($info['extension'], $extensions))) { + if ($this->getCase() && (in_array($extension, $extensions))) { return true; } elseif (!$this->getCase()) { - foreach ($extensions as $extension) { - if (strtolower($extension) == strtolower($info['extension'])) { + foreach ($extensions as $ext) { + if (strtolower($ext) == strtolower($extension)) { return true; } } } - return $this->throwError($file, self::FALSE_EXTENSION); - } - - /** - * Throws an error of the given type - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function throwError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $this->value = $file['name']; - } - } elseif (is_string($file)) { - $this->value = $file; - } - } - - $this->error($errorType); + $this->error(self::FALSE_EXTENSION); return false; } } diff --git a/library/Zend/Validator/File/FilesSize.php b/library/Zend/Validator/File/FilesSize.php deleted file mode 100644 index a7be3735efa..00000000000 --- a/library/Zend/Validator/File/FilesSize.php +++ /dev/null @@ -1,151 +0,0 @@ - "All files in sum should have a maximum size of '%max%' but '%size%' were detected", - self::TOO_SMALL => "All files in sum should have a minimum size of '%min%' but '%size%' were detected", - self::NOT_READABLE => "One or more files can not be read", - ); - - /** - * Internal file array - * - * @var array - */ - protected $files; - - /** - * Sets validator options - * - * Min limits the used disk space for all files, when used with max=null it is the maximum file size - * It also accepts an array with the keys 'min' and 'max' - * - * @param integer|array|Traversable $options Options for this validator - * @throws \Zend\Validator\Exception\InvalidArgumentException - */ - public function __construct($options = null) - { - $this->files = array(); - $this->setSize(0); - - if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray($options); - } elseif (is_scalar($options)) { - $options = array('max' => $options); - } elseif (!is_array($options)) { - throw new Exception\InvalidArgumentException('Invalid options to validator provided'); - } - - if (1 < func_num_args()) { - $argv = func_get_args(); - array_shift($argv); - $options['max'] = array_shift($argv); - if (!empty($argv)) { - $options['useByteString'] = array_shift($argv); - } - } - - parent::__construct($options); - } - - /** - * Returns true if and only if the disk usage of all files is at least min and - * not bigger than max (when max is not null). - * - * @param string|array $value Real file to check for size - * @param array $file File data from \Zend\File\Transfer\Transfer - * @return boolean - */ - public function isValid($value, $file = null) - { - if (is_string($value)) { - $value = array($value); - } - - $min = $this->getMin(true); - $max = $this->getMax(true); - $size = $this->getSize(); - foreach ($value as $files) { - // Is file readable ? - if (false === stream_resolve_include_path($files)) { - $this->throwError($file, self::NOT_READABLE); - continue; - } - - if (!isset($this->files[$files])) { - $this->files[$files] = $files; - } else { - // file already counted... do not count twice - continue; - } - - // limited to 2GB files - ErrorHandler::start(); - $size += filesize($files); - ErrorHandler::stop(); - $this->size = $size; - if (($max !== null) && ($max < $size)) { - if ($this->getByteString()) { - $this->options['max'] = $this->toByteString($max); - $this->size = $this->toByteString($size); - $this->throwError($file, self::TOO_BIG); - $this->options['max'] = $max; - $this->size = $size; - } else { - $this->throwError($file, self::TOO_BIG); - } - } - } - - // Check that aggregate files are >= minimum size - if (($min !== null) && ($size < $min)) { - if ($this->getByteString()) { - $this->options['min'] = $this->toByteString($min); - $this->size = $this->toByteString($size); - $this->throwError($file, self::TOO_SMALL); - $this->options['min'] = $min; - $this->size = $size; - } else { - $this->throwError($file, self::TOO_SMALL); - } - } - - if (count($this->getMessages()) > 0) { - return false; - } - - return true; - } -} diff --git a/library/Zend/Validator/File/Hash.php b/library/Zend/Validator/File/Hash.php index b7a56a3f56f..9c2c2e0cabe 100644 --- a/library/Zend/Validator/File/Hash.php +++ b/library/Zend/Validator/File/Hash.php @@ -32,9 +32,9 @@ class Hash extends AbstractValidator * @var array Error message templates */ protected $messageTemplates = array( - self::DOES_NOT_MATCH => "File '%value%' does not match the given hashes", + self::DOES_NOT_MATCH => "File does not match the given hashes", self::NOT_DETECTED => "A hash could not be evaluated for the given file", - self::NOT_FOUND => "File '%value%' is not readable or does not exist" + self::NOT_FOUND => "File is not readable or does not exist" ); /** @@ -127,27 +127,38 @@ public function addHash($options) /** * Returns true if and only if the given file confirms the set hash * - * @param string $value Filename to check for hash - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value File to check for hash * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_FOUND); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_FOUND); + return false; } $algos = array_unique(array_values($this->getHash())); $hashes = array_unique(array_keys($this->getHash())); foreach ($algos as $algorithm) { - $filehash = hash_file($algorithm, $value); + $filehash = hash_file($algorithm, $file); if ($filehash === false) { - return $this->throwError($file, self::NOT_DETECTED); + $this->error(self::NOT_DETECTED); + return false; } foreach ($hashes as $hash) { @@ -157,29 +168,7 @@ public function isValid($value, $file = null) } } - return $this->throwError($file, self::DOES_NOT_MATCH); - } - - /** - * Throws an error of the given type - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function throwError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $this->value = $file['name']; - } - } elseif (is_string($file)) { - $this->value = $file; - } - } - - $this->error($errorType); + $this->error(self::DOES_NOT_MATCH); return false; } } diff --git a/library/Zend/Validator/File/ImageSize.php b/library/Zend/Validator/File/ImageSize.php index 337b49dadad..4035dee0bb7 100644 --- a/library/Zend/Validator/File/ImageSize.php +++ b/library/Zend/Validator/File/ImageSize.php @@ -36,12 +36,12 @@ class ImageSize extends AbstractValidator * @var array Error message template */ protected $messageTemplates = array( - self::WIDTH_TOO_BIG => "Maximum allowed width for image '%value%' should be '%maxwidth%' but '%width%' detected", - self::WIDTH_TOO_SMALL => "Minimum expected width for image '%value%' should be '%minwidth%' but '%width%' detected", - self::HEIGHT_TOO_BIG => "Maximum allowed height for image '%value%' should be '%maxheight%' but '%height%' detected", - self::HEIGHT_TOO_SMALL => "Minimum expected height for image '%value%' should be '%minheight%' but '%height%' detected", - self::NOT_DETECTED => "The size of image '%value%' could not be detected", - self::NOT_READABLE => "File '%value%' is not readable or does not exist", + self::WIDTH_TOO_BIG => "Maximum allowed width for image should be '%maxwidth%' but '%width%' detected", + self::WIDTH_TOO_SMALL => "Minimum expected width for image should be '%minwidth%' but '%width%' detected", + self::HEIGHT_TOO_BIG => "Maximum allowed height for image should be '%maxheight%' but '%height%' detected", + self::HEIGHT_TOO_SMALL => "Minimum expected height for image should be '%minheight%' but '%height%' detected", + self::NOT_DETECTED => "The size of image could not be detected", + self::NOT_READABLE => "File is not readable or does not exist", ); /** @@ -322,46 +322,56 @@ public function setImageHeight($options) * Returns true if and only if the image size of $value is at least min and * not bigger than max * - * @param string $value Real file to check for image size - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Real file to check for image size * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_READABLE); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_READABLE); + return false; } ErrorHandler::start(); - $size = getimagesize($value); + $size = getimagesize($file); ErrorHandler::stop(); - $this->setValue($file); if (empty($size) or ($size[0] === 0) or ($size[1] === 0)) { - return $this->throwError($file, self::NOT_DETECTED); + $this->error(self::NOT_DETECTED); + return false; } $this->width = $size[0]; $this->height = $size[1]; if ($this->width < $this->getMinWidth()) { - $this->throwError($file, self::WIDTH_TOO_SMALL); + $this->error(self::WIDTH_TOO_SMALL); } if (($this->getMaxWidth() !== null) and ($this->getMaxWidth() < $this->width)) { - $this->throwError($file, self::WIDTH_TOO_BIG); + $this->error(self::WIDTH_TOO_BIG); } if ($this->height < $this->getMinHeight()) { - $this->throwError($file, self::HEIGHT_TOO_SMALL); + $this->error(self::HEIGHT_TOO_SMALL); } if (($this->getMaxHeight() !== null) and ($this->getMaxHeight() < $this->height)) { - $this->throwError($file, self::HEIGHT_TOO_BIG); + $this->error(self::HEIGHT_TOO_BIG); } if (count($this->getMessages()) > 0) { @@ -370,27 +380,4 @@ public function isValid($value, $file = null) return true; } - - /** - * Throws an error of the given type - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function throwError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $this->value = $file['name']; - } - } elseif (is_string($file)) { - $this->value = $file; - } - } - - $this->error($errorType); - return false; - } } diff --git a/library/Zend/Validator/File/IsCompressed.php b/library/Zend/Validator/File/IsCompressed.php index 3710b375a4c..ef2f243e1e2 100644 --- a/library/Zend/Validator/File/IsCompressed.php +++ b/library/Zend/Validator/File/IsCompressed.php @@ -32,9 +32,9 @@ class IsCompressed extends MimeType * @var array Error message templates */ protected $messageTemplates = array( - self::FALSE_TYPE => "File '%value%' is not compressed, '%type%' detected", - self::NOT_DETECTED => "The mimetype of file '%value%' could not be detected", - self::NOT_READABLE => "File '%value%' is not readable or does not exist", + self::FALSE_TYPE => "File is not compressed, '%type%' detected", + self::NOT_DETECTED => "The mimetype could not be detected from the file", + self::NOT_READABLE => "File is not readable or does not exist", ); /** @@ -89,42 +89,4 @@ public function __construct($options = array()) parent::__construct($options); } - - /** - * Throws an error of the given type - * Duplicates parent method due to OOP Problem with late static binding in PHP 5.2 - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function createError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $file = $file['name']; - } - } - - if (is_string($file)) { - $this->value = basename($file); - } - } - - switch ($errorType) { - case MimeType::FALSE_TYPE : - $errorType = self::FALSE_TYPE; - break; - case MimeType::NOT_DETECTED : - $errorType = self::NOT_DETECTED; - break; - case MimeType::NOT_READABLE : - $errorType = self::NOT_READABLE; - break; - } - - $this->error($errorType); - return false; - } } diff --git a/library/Zend/Validator/File/IsImage.php b/library/Zend/Validator/File/IsImage.php index 537ed44ed9c..214abe07bb7 100644 --- a/library/Zend/Validator/File/IsImage.php +++ b/library/Zend/Validator/File/IsImage.php @@ -32,9 +32,9 @@ class IsImage extends MimeType * @var array Error message templates */ protected $messageTemplates = array( - self::FALSE_TYPE => "File '%value%' is no image, '%type%' detected", - self::NOT_DETECTED => "The mimetype of file '%value%' could not be detected", - self::NOT_READABLE => "File '%value%' is not readable or does not exist", + self::FALSE_TYPE => "File is no image, '%type%' detected", + self::NOT_DETECTED => "The mimetype could not be detected from the file", + self::NOT_READABLE => "File is not readable or does not exist", ); /** @@ -114,42 +114,4 @@ public function __construct($options = array()) parent::__construct($options); } - - /** - * Throws an error of the given type - * Duplicates parent method due to OOP Problem with late static binding in PHP 5.2 - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function createError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $file = $file['name']; - } - } - - if (is_string($file)) { - $this->value = basename($file); - } - } - - switch ($errorType) { - case MimeType::FALSE_TYPE : - $errorType = self::FALSE_TYPE; - break; - case MimeType::NOT_DETECTED : - $errorType = self::NOT_DETECTED; - break; - case MimeType::NOT_READABLE : - $errorType = self::NOT_READABLE; - break; - } - - $this->error($errorType); - return false; - } } diff --git a/library/Zend/Validator/File/Md5.php b/library/Zend/Validator/File/Md5.php index b32ba53ea15..30f292cc3c1 100644 --- a/library/Zend/Validator/File/Md5.php +++ b/library/Zend/Validator/File/Md5.php @@ -10,6 +10,8 @@ namespace Zend\Validator\File; +use Zend\Validator\Exception; + /** * Validator for the md5 hash of given files * @@ -29,9 +31,9 @@ class Md5 extends Hash * @var array Error message templates */ protected $messageTemplates = array( - self::DOES_NOT_MATCH => "File '%value%' does not match the given md5 hashes", + self::DOES_NOT_MATCH => "File does not match the given md5 hashes", self::NOT_DETECTED => "A md5 hash could not be evaluated for the given file", - self::NOT_FOUND => "File '%value%' is not readable or does not exist", + self::NOT_FOUND => "File is not readable or does not exist", ); /** @@ -81,25 +83,36 @@ public function addMd5($options) /** * Returns true if and only if the given file confirms the set hash * - * @param string $value Filename to check for hash - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Filename to check for hash * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_FOUND); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_FOUND); + return false; } $hashes = array_unique(array_keys($this->getHash())); - $filehash = hash_file('md5', $value); + $filehash = hash_file('md5', $file); if ($filehash === false) { - return $this->throwError($file, self::NOT_DETECTED); + $this->error(self::NOT_DETECTED); + return false; } foreach ($hashes as $hash) { @@ -108,6 +121,7 @@ public function isValid($value, $file = null) } } - return $this->throwError($file, self::DOES_NOT_MATCH); + $this->error(self::DOES_NOT_MATCH); + return false; } } diff --git a/library/Zend/Validator/File/MimeType.php b/library/Zend/Validator/File/MimeType.php index 1f1a536995a..d343f5c457f 100644 --- a/library/Zend/Validator/File/MimeType.php +++ b/library/Zend/Validator/File/MimeType.php @@ -36,9 +36,9 @@ class MimeType extends AbstractValidator * @var array Error message templates */ protected $messageTemplates = array( - self::FALSE_TYPE => "File '%value%' has a false mimetype of '%type%'", - self::NOT_DETECTED => "The mimetype of file '%value%' could not be detected", - self::NOT_READABLE => "File '%value%' is not readable or does not exist", + self::FALSE_TYPE => "File has an incorrect mimetype of '%type%'", + self::NOT_DETECTED => "The mimetype could not be detected from the file", + self::NOT_READABLE => "File is not readable or does not exist", ); /** @@ -345,22 +345,31 @@ public function addMimeType($mimetype) * of mimetypes can be checked. If you give for example "image" all image * mime types will be accepted like "image/gif", "image/jpeg" and so on. * - * @param string $value Real file to check for mimetype - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Real file to check for mimetype * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array( - 'type' => null, - 'name' => $value, - ); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name']) || !isset($value['type'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + $filetype = $value['type']; + } else { + $file = $value; + $filename = basename($file); + $filetype = null; } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->createError($file, self::NOT_READABLE); + if (false === stream_resolve_include_path($file)) { + $this->error(static::NOT_READABLE); + return false; } $mimefile = $this->getMagicFile(); @@ -380,21 +389,22 @@ public function isValid($value, $file = null) $this->type = null; if (!empty($this->finfo)) { - $this->type = finfo_file($this->finfo, $value); + $this->type = finfo_file($this->finfo, $file); } } if (empty($this->type) && (function_exists('mime_content_type') && ini_get('mime_magic.magicfile'))) { - $this->type = mime_content_type($value); + $this->type = mime_content_type($file); } if (empty($this->type) && $this->getHeaderCheck()) { - $this->type = $file['type']; + $this->type = $filetype; } if (empty($this->type)) { - return $this->createError($file, self::NOT_DETECTED); + $this->error(static::NOT_DETECTED); + false; } $mimetype = $this->getMimeType(true); @@ -411,31 +421,7 @@ public function isValid($value, $file = null) } } - return $this->createError($file, self::FALSE_TYPE); - } - - /** - * Throws an error of the given type - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function createError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $file = $file['name']; - } - } - - if (is_string($file)) { - $this->value = basename($file); - } - } - - $this->error($errorType); + $this->error(static::FALSE_TYPE); return false; } } diff --git a/library/Zend/Validator/File/NotExists.php b/library/Zend/Validator/File/NotExists.php index ca40f46b874..48dd32bd7f9 100644 --- a/library/Zend/Validator/File/NotExists.php +++ b/library/Zend/Validator/File/NotExists.php @@ -10,6 +10,8 @@ namespace Zend\Validator\File; +use Zend\Validator\Exception; + /** * Validator which checks if the destination file does not exist * @@ -27,38 +29,57 @@ class NotExists extends Exists * @var array Error message templates */ protected $messageTemplates = array( - self::DOES_EXIST => "File '%value%' exists", + self::DOES_EXIST => "File exists", ); /** * Returns true if and only if the file does not exist in the set destinations * - * @param string $value Real file to check for - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value Real file to check for existence * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - $directories = $this->getDirectory(true); - if (($file !== null) and (!empty($file['destination']))) { - $directories[] = $file['destination']; - } elseif (!isset($file['name'])) { - $file['name'] = $value; + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = basename($file); + $this->setValue($value['name']); + } else { + $file = $value; + $filename = basename($file); + $this->setValue($filename); } - foreach ($directories as $directory) { - if (empty($directory)) { - continue; + $check = false; + $directories = $this->getDirectory(true); + if (!isset($directories)) { + $check = true; + if (file_exists($file)) { + $this->error(self::DOES_EXIST); + return false; } + } else { + foreach ($directories as $directory) { + if (!isset($directory) || '' === $directory) { + continue; + } - $check = true; - if (file_exists($directory . DIRECTORY_SEPARATOR . $file['name'])) { - return $this->throwError($file, self::DOES_EXIST); + $check = true; + if (file_exists($directory . DIRECTORY_SEPARATOR . $filename)) { + $this->error(self::DOES_EXIST); + return false; + } } } - if (!isset($check)) { - return $this->throwError($file, self::DOES_EXIST); + if (!$check) { + $this->error(self::DOES_EXIST); + return false; } return true; diff --git a/library/Zend/Validator/File/Sha1.php b/library/Zend/Validator/File/Sha1.php index 72e37f16e39..112f86561c3 100644 --- a/library/Zend/Validator/File/Sha1.php +++ b/library/Zend/Validator/File/Sha1.php @@ -30,9 +30,9 @@ class Sha1 extends Hash * @var array Error message templates */ protected $messageTemplates = array( - self::DOES_NOT_MATCH => "File '%value%' does not match the given sha1 hashes", + self::DOES_NOT_MATCH => "File does not match the given sha1 hashes", self::NOT_DETECTED => "A sha1 hash could not be evaluated for the given file", - self::NOT_FOUND => "File '%value%' is not readable or does not exist", + self::NOT_FOUND => "File is not readable or does not exist", ); /** @@ -82,25 +82,36 @@ public function addSha1($options) /** * Returns true if and only if the given file confirms the set hash * - * @param string $value Filename to check for hash - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string $value|array Filename to check for hash * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_FOUND); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_FOUND); + return false; } $hashes = array_unique(array_keys($this->getHash())); - $filehash = hash_file('sha1', $value); + $filehash = hash_file('sha1', $file); if ($filehash === false) { - return $this->throwError($file, self::NOT_DETECTED); + $this->error(self::NOT_DETECTED); + return false; } foreach ($hashes as $hash) { @@ -109,6 +120,7 @@ public function isValid($value, $file = null) } } - return $this->throwError($file, self::DOES_NOT_MATCH); + $this->error(self::DOES_NOT_MATCH); + return false; } } diff --git a/library/Zend/Validator/File/Size.php b/library/Zend/Validator/File/Size.php index 96aae168898..e8bb4521e0b 100644 --- a/library/Zend/Validator/File/Size.php +++ b/library/Zend/Validator/File/Size.php @@ -33,9 +33,9 @@ class Size extends AbstractValidator * @var array Error message templates */ protected $messageTemplates = array( - self::TOO_BIG => "Maximum allowed size for file '%value%' is '%max%' but '%size%' detected", - self::TOO_SMALL => "Minimum expected size for file '%value%' is '%min%' but '%size%' detected", - self::NOT_FOUND => "File '%value%' is not readable or does not exist", + self::TOO_BIG => "Maximum allowed size for file is '%max%' but '%size%' detected", + self::TOO_SMALL => "Minimum expected size for file is '%min%' but '%size%' detected", + self::NOT_FOUND => "File is not readable or does not exist", ); /** @@ -232,24 +232,34 @@ protected function setSize($size) * Returns true if and only if the file size of $value is at least min and * not bigger than max (when max is not null). * - * @param string $value Real file to check for size - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string|array $value File to check for size * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_FOUND); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_FOUND); + return false; } // limited to 4GB files ErrorHandler::start(); - $size = sprintf("%u", filesize($value)); + $size = sprintf("%u", filesize($file)); ErrorHandler::stop(); $this->size = $size; @@ -260,11 +270,11 @@ public function isValid($value, $file = null) if ($this->getByteString()) { $this->options['min'] = $this->toByteString($min); $this->size = $this->toByteString($size); - $this->throwError($file, self::TOO_SMALL); + $this->error(self::TOO_SMALL); $this->options['min'] = $min; $this->size = $size; } else { - $this->throwError($file, self::TOO_SMALL); + $this->error(self::TOO_SMALL); } } @@ -273,11 +283,11 @@ public function isValid($value, $file = null) if ($this->getByteString()) { $this->options['max'] = $this->toByteString($max); $this->size = $this->toByteString($size); - $this->throwError($file, self::TOO_BIG); + $this->error(self::TOO_BIG); $this->options['max'] = $max; $this->size = $size; } else { - $this->throwError($file, self::TOO_BIG); + $this->error(self::TOO_BIG); } } @@ -355,26 +365,5 @@ protected function fromByteString($size) return $value; } - /** - * Throws an error of the given type - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function throwError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $this->value = $file['name']; - } - } elseif (is_string($file)) { - $this->value = $file; - } - } - $this->error($errorType); - return false; - } } diff --git a/library/Zend/Validator/File/Upload.php b/library/Zend/Validator/File/Upload.php index dc9e55bf6de..a876811d872 100644 --- a/library/Zend/Validator/File/Upload.php +++ b/library/Zend/Validator/File/Upload.php @@ -39,169 +39,85 @@ class Upload extends AbstractValidator * @var array Error message templates */ protected $messageTemplates = array( - self::INI_SIZE => "File '%value%' exceeds the defined ini size", - self::FORM_SIZE => "File '%value%' exceeds the defined form size", - self::PARTIAL => "File '%value%' was only partially uploaded", - self::NO_FILE => "File '%value%' was not uploaded", - self::NO_TMP_DIR => "No temporary directory was found for file '%value%'", - self::CANT_WRITE => "File '%value%' can't be written", - self::EXTENSION => "A PHP extension returned an error while uploading the file '%value%'", - self::ATTACK => "File '%value%' was illegally uploaded. This could be a possible attack", - self::FILE_NOT_FOUND => "File '%value%' was not found", - self::UNKNOWN => "Unknown error while uploading file '%value%'" + self::INI_SIZE => "File exceeds the defined ini size", + self::FORM_SIZE => "File exceeds the defined form size", + self::PARTIAL => "File was only partially uploaded", + self::NO_FILE => "File was not uploaded", + self::NO_TMP_DIR => "No temporary directory was found for file", + self::CANT_WRITE => "File can't be written", + self::EXTENSION => "A PHP extension returned an error while uploading the file", + self::ATTACK => "File was illegally uploaded. This could be a possible attack", + self::FILE_NOT_FOUND => "File was not found", + self::UNKNOWN => "Unknown error while uploading file", ); - protected $options = array( - 'files' => array(), - ); - - /** - * Sets validator options - * - * The array $files must be given in syntax of Zend_File_Transfer to be checked - * If no files are given the $_FILES array will be used automatically. - * NOTE: This validator will only work with HTTP POST uploads! - * - * @param array|\Traversable $options Array of files in syntax of \Zend\File\Transfer\Transfer - */ - public function __construct($options = array()) - { - if (is_array($options) && !array_key_exists('files', $options)) { - $options = array('files' => $options); - } - - parent::__construct($options); - } - /** - * Returns the array of set files + * Returns true if and only if the file was uploaded without errors * - * @param string $file (Optional) The file to return in detail - * @return array - * @throws Exception\InvalidArgumentException If file is not found + * @param string $value File to check for upload errors + * @return boolean */ - public function getFiles($file = null) + public function isValid($value) { - if ($file !== null) { - $return = array(); - foreach ($this->options['files'] as $name => $content) { - if ($name === $file) { - $return[$file] = $this->options['files'][$name]; - } - - if ($content['name'] === $file) { - $return[$name] = $this->options['files'][$name]; - } - } - - if (count($return) === 0) { - throw new Exception\InvalidArgumentException("The file '$file' was not found"); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name']) || !isset($value['error'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); } + $file = $value['tmp_name']; + $filename = $value['name']; + $error = $value['error']; + } else { + $file = $value; + $filename = basename($file); + $error = 0; + } + $this->setValue($filename); - return $return; + if (false === stream_resolve_include_path($file)) { + $this->error(self::FILE_NOT_FOUND); + return false; } - return $this->options['files']; - } + switch ($error) { + case 0: + if (!is_uploaded_file($file)) { + $this->error(self::ATTACK); + } + break; - /** - * Sets the files to be checked - * - * @param array $files The files to check in syntax of \Zend\File\Transfer\Transfer - * @return Upload Provides a fluent interface - */ - public function setFiles($files = array()) - { - if (count($files) === 0) { - $this->options['files'] = $_FILES; - } else { - $this->options['files'] = $files; - } + case 1: + $this->error(self::INI_SIZE); + break; - if ($this->options['files'] === NULL) { - $this->options['files'] = array(); - } + case 2: + $this->error(self::FORM_SIZE); + break; - foreach ($this->options['files'] as $file => $content) { - if (!isset($content['error'])) { - unset($this->options['files'][$file]); - } - } + case 3: + $this->error(self::PARTIAL); + break; - return $this; - } + case 4: + $this->error(self::NO_FILE); + break; - /** - * Returns true if and only if the file was uploaded without errors - * - * @param string $value Single file to check for upload errors, when giving null the $_FILES array - * from initialization will be used - * @param mixed $file - * @return boolean - */ - public function isValid($value, $file = null) - { - $files = array(); - $this->setValue($value); - if (array_key_exists($value, $this->getFiles())) { - $files = array_merge($files, $this->getFiles($value)); - } else { - foreach ($this->getFiles() as $file => $content) { - if (isset($content['name']) && ($content['name'] === $value)) { - $files = array_merge($files, $this->getFiles($file)); - } + case 6: + $this->error(self::NO_TMP_DIR); + break; - if (isset($content['tmp_name']) && ($content['tmp_name'] === $value)) { - $files = array_merge($files, $this->getFiles($file)); - } - } - } + case 7: + $this->error(self::CANT_WRITE); + break; - if (empty($files)) { - return $this->throwError($file, self::FILE_NOT_FOUND); - } + case 8: + $this->error(self::EXTENSION); + break; - foreach ($files as $file => $content) { - $this->value = $file; - switch ($content['error']) { - case 0: - if (!is_uploaded_file($content['tmp_name'])) { - $this->throwError($file, self::ATTACK); - } - break; - - case 1: - $this->throwError($file, self::INI_SIZE); - break; - - case 2: - $this->throwError($file, self::FORM_SIZE); - break; - - case 3: - $this->throwError($file, self::PARTIAL); - break; - - case 4: - $this->throwError($file, self::NO_FILE); - break; - - case 6: - $this->throwError($file, self::NO_TMP_DIR); - break; - - case 7: - $this->throwError($file, self::CANT_WRITE); - break; - - case 8: - $this->throwError($file, self::EXTENSION); - break; - - default: - $this->throwError($file, self::UNKNOWN); - break; - } + default: + $this->error(self::UNKNOWN); + break; } if (count($this->getMessages()) > 0) { @@ -210,27 +126,4 @@ public function isValid($value, $file = null) return true; } } - - /** - * Throws an error of the given type - * - * @param string $file - * @param string $errorType - * @return false - */ - protected function throwError($file, $errorType) - { - if ($file !== null) { - if (is_array($file)) { - if (array_key_exists('name', $file)) { - $this->value = $file['name']; - } - } elseif (is_string($file)) { - $this->value = $file; - } - } - - $this->error($errorType); - return false; - } } diff --git a/library/Zend/Validator/File/WordCount.php b/library/Zend/Validator/File/WordCount.php index 4587d9ce9d7..35fe1174691 100644 --- a/library/Zend/Validator/File/WordCount.php +++ b/library/Zend/Validator/File/WordCount.php @@ -10,13 +10,16 @@ namespace Zend\Validator\File; +use Zend\Validator\AbstractValidator; +use Zend\Validator\Exception; + /** * Validator for counting all words in a file * * @category Zend * @package Zend_Validator */ -class WordCount extends Count +class WordCount extends AbstractValidator { /** * @const string Error constants @@ -31,36 +34,177 @@ class WordCount extends Count protected $messageTemplates = array( self::TOO_MUCH => "Too much words, maximum '%max%' are allowed but '%count%' were counted", self::TOO_LESS => "Too less words, minimum '%min%' are expected but '%count%' were counted", - self::NOT_FOUND => "File '%value%' is not readable or does not exist", + self::NOT_FOUND => "File is not readable or does not exist", + ); + + /** + * @var array Error message template variables + */ + protected $messageVariables = array( + 'min' => array('options' => 'min'), + 'max' => array('options' => 'max'), + 'count' => 'count' + ); + + /** + * Word count + * + * @var integer + */ + protected $count; + + /** + * Options for this validator + * + * @var array + */ + protected $options = array( + 'min' => null, // Minimum word count, if null there is no minimum word count + 'max' => null, // Maximum word count, if null there is no maximum word count ); + /** + * Sets validator options + * + * Min limits the word count, when used with max=null it is the maximum word count + * It also accepts an array with the keys 'min' and 'max' + * + * If $options is a integer, it will be used as maximum word count + * As Array is accepts the following keys: + * 'min': Minimum word count + * 'max': Maximum word count + * + * @param integer|array|\Traversable $options Options for the adapter + */ + public function __construct($options = null) + { + if (is_string($options) || is_numeric($options)) { + $options = array('max' => $options); + } + + if (1 < func_num_args()) { + $options['min'] = func_get_arg(0); + $options['max'] = func_get_arg(1); + } + + parent::__construct($options); + } + + /** + * Returns the minimum word count + * + * @return integer + */ + public function getMin() + { + return $this->options['min']; + } + + /** + * Sets the minimum word count + * + * @param integer|array $min The minimum word count + * @return WordCount Provides a fluent interface + * @throws Exception\InvalidArgumentException When min is greater than max + */ + public function setMin($min) + { + if (is_array($min) and isset($min['min'])) { + $min = $min['min']; + } + + if (!is_string($min) and !is_numeric($min)) { + throw new Exception\InvalidArgumentException('Invalid options to validator provided'); + } + + $min = (integer) $min; + if (($this->getMax() !== null) && ($min > $this->getMax())) { + throw new Exception\InvalidArgumentException( + "The minimum must be less than or equal to the maximum word count, but $min >" + . " {$this->getMax()}"); + } + + $this->options['min'] = $min; + return $this; + } + + /** + * Returns the maximum word count + * + * @return integer + */ + public function getMax() + { + return $this->options['max']; + } + + /** + * Sets the maximum file count + * + * @param integer|array $max The maximum word count + * @return WordCount Provides a fluent interface + * @throws Exception\InvalidArgumentException When max is smaller than min + */ + public function setMax($max) + { + if (is_array($max) and isset($max['max'])) { + $max = $max['max']; + } + + if (!is_string($max) and !is_numeric($max)) { + throw new Exception\InvalidArgumentException('Invalid options to validator provided'); + } + + $max = (integer) $max; + if (($this->getMin() !== null) && ($max < $this->getMin())) { + throw new Exception\InvalidArgumentException( + "The maximum must be greater than or equal to the minimum word count, but " + . "$max < {$this->getMin()}"); + } + + $this->options['max'] = $max; + return $this; + } + /** * Returns true if and only if the counted words are at least min and * not bigger than max (when max is not null). * - * @param string $value Filename to check for word count - * @param array $file File data from \Zend\File\Transfer\Transfer + * @param string $value|array Filename to check for word count * @return boolean */ - public function isValid($value, $file = null) + public function isValid($value) { - if ($file === null) { - $file = array('name' => basename($value)); + if (is_array($value)) { + if (!isset($value['tmp_name']) || !isset($value['name'])) { + throw new Exception\InvalidArgumentException( + 'Value array must be in $_FILES format' + ); + } + $file = $value['tmp_name']; + $filename = $value['name']; + } else { + $file = $value; + $filename = basename($file); } + $this->setValue($filename); // Is file readable ? - if (false === stream_resolve_include_path($value)) { - return $this->throwError($file, self::NOT_FOUND); + if (false === stream_resolve_include_path($file)) { + $this->error(self::NOT_FOUND); + return false; } - $content = file_get_contents($value); + $content = file_get_contents($file); $this->count = str_word_count($content); if (($this->getMax() !== null) && ($this->count > $this->getMax())) { - return $this->throwError($file, self::TOO_MUCH); + $this->error(self::TOO_MUCH); + return false; } if (($this->getMin() !== null) && ($this->count < $this->getMin())) { - return $this->throwError($file, self::TOO_LESS); + $this->error(self::TOO_LESS); + return false; } return true; diff --git a/library/Zend/Validator/ValidatorPluginManager.php b/library/Zend/Validator/ValidatorPluginManager.php index aef360a4131..745c8e557d5 100644 --- a/library/Zend/Validator/ValidatorPluginManager.php +++ b/library/Zend/Validator/ValidatorPluginManager.php @@ -67,13 +67,12 @@ class ValidatorPluginManager extends AbstractPluginManager 'digits' => 'Zend\Validator\Digits', 'emailaddress' => 'Zend\Validator\EmailAddress', 'explode' => 'Zend\Validator\Explode', - 'filecount' => 'Zend\Validator\File\Count', 'filecrc32' => 'Zend\Validator\File\Crc32', 'fileexcludeextension' => 'Zend\Validator\File\ExcludeExtension', 'fileexcludemimetype' => 'Zend\Validator\File\ExcludeMimeType', 'fileexists' => 'Zend\Validator\File\Exists', + 'fileexplode' => 'Zend\Validator\File\Explode', 'fileextension' => 'Zend\Validator\File\Extension', - 'filefilessize' => 'Zend\Validator\File\FilesSize', 'filehash' => 'Zend\Validator\File\Hash', 'fileimagesize' => 'Zend\Validator\File\ImageSize', 'fileiscompressed' => 'Zend\Validator\File\IsCompressed', diff --git a/tests/Bootstrap.php b/tests/Bootstrap.php index feb3a87da57..d84722980b7 100644 --- a/tests/Bootstrap.php +++ b/tests/Bootstrap.php @@ -93,3 +93,12 @@ * Unset global variables that are no longer needed. */ unset($zfRoot, $zfCoreLibrary, $zfCoreTests, $path); + +/** + * Internal PHP function mocks + * To be used with runkit_function_rename() + */ +function move_uploaded_file_mock($source, $dest) +{ + return rename($source, $dest); +} diff --git a/tests/ZendTest/File/Transfer/Adapter/AbstractAdapterTestMockAdapter.php b/tests/ZendTest/File/Transfer/Adapter/AbstractAdapterTestMockAdapter.php deleted file mode 100644 index a49119266e6..00000000000 --- a/tests/ZendTest/File/Transfer/Adapter/AbstractAdapterTestMockAdapter.php +++ /dev/null @@ -1,152 +0,0 @@ -files = array( - 'foo' => array( - 'name' => 'foo.jpg', - 'type' => 'image/jpeg', - 'size' => 126976, - 'tmp_name' => '/tmp/489127ba5c89c', - 'options' => array('ignoreNoFile' => false, 'useByteString' => true, 'detectInfos' => true), - 'validated' => false, - 'received' => false, - 'filtered' => false, - ), - 'bar' => array( - 'name' => 'bar.png', - 'type' => 'image/png', - 'size' => 91136, - 'tmp_name' => '/tmp/489128284b51f', - 'options' => array('ignoreNoFile' => false, 'useByteString' => true), - 'validated' => false, - 'received' => false, - 'filtered' => false, - ), - 'baz' => array( - 'name' => 'baz.text', - 'type' => 'text/plain', - 'size' => 1172, - 'tmp_name' => $testfile, - 'options' => array('ignoreNoFile' => false, 'useByteString' => true), - 'validated' => false, - 'received' => false, - 'filtered' => false, - ), - 'file_0_' => array( - 'name' => 'foo.jpg', - 'type' => 'image/jpeg', - 'size' => 126976, - 'tmp_name' => '/tmp/489127ba5c89c', - 'options' => array('ignoreNoFile' => false, 'useByteString' => true), - 'validated' => false, - 'received' => false, - 'filtered' => false, - ), - 'file_1_' => array( - 'name' => 'baz.text', - 'type' => 'text/plain', - 'size' => 1172, - 'tmp_name' => $testfile, - 'options' => array('ignoreNoFile' => false, 'useByteString' => true), - 'validated' => false, - 'received' => false, - 'filtered' => false, - ), - 'file' => array( - 'name' => 'foo.jpg', - 'multifiles' => array(0 => 'file_0_', 1 => 'file_1_') - ), - ); - } - - public function send($options = null) - { - return; - } - - public function receive($options = null) - { - $this->received = true; - return; - } - - public function isSent($file = null) - { - return false; - } - - public function isReceived($file = null) - { - return $this->received; - } - - public function isUploaded($files = null) - { - return true; - } - - public function isFiltered($files = null) - { - return true; - } - - public static function getProgress() - { - return; - } - - public function getTmpDir() - { - $this->tmpDir = parent::getTmpDir(); - } - - public function isPathWriteable($path) - { - return parent::isPathWriteable($path); - } - - public function addInvalidFile() - { - $this->files += array( - 'test' => array( - 'name' => 'test.txt', - 'type' => 'image/jpeg', - 'size' => 0, - 'tmp_name' => '', - 'options' => array('ignoreNoFile' => true, 'useByteString' => true), - 'validated' => false, - 'received' => false, - 'filtered' => false, - ) - ); - } - -} diff --git a/tests/ZendTest/File/Transfer/Adapter/AbstractTest.php b/tests/ZendTest/File/Transfer/Adapter/AbstractTest.php deleted file mode 100644 index 15f827923cc..00000000000 --- a/tests/ZendTest/File/Transfer/Adapter/AbstractTest.php +++ /dev/null @@ -1,670 +0,0 @@ -adapter = new AbstractAdapterTestMockAdapter(); - } - - /** - * Tears down the fixture, for example, close a network connection. - * This method is called after a test is executed. - * - * @return void - */ - public function tearDown() - { - } - - public function testAdapterShouldLazyLoadValidatorPluginManager() - { - $loader = $this->adapter->getValidatorManager(); - $this->assertInstanceOf('Zend\File\Transfer\Adapter\ValidatorPluginManager', $loader); - } - - public function testAdapterShouldAllowSettingFilterPluginManagerInstance() - { - $manager = new File\Transfer\Adapter\FilterPluginManager(); - $this->adapter->setFilterManager($manager); - $this->assertSame($manager, $this->adapter->getFilterManager()); - } - - public function testAdapterShouldAllowAddingValidatorInstance() - { - $validator = new FileValidator\Count(array('min' => 1, 'max' => 1)); - $this->adapter->addValidator($validator); - $test = $this->adapter->getValidator('Zend\Validator\File\Count'); - $this->assertSame($validator, $test); - } - - public function testAdapterShouldAllowAddingValidatorViaPluginManager() - { - $this->adapter->addValidator('Count', false, array('min' => 1, 'max' => 1)); - $test = $this->adapter->getValidator('Count'); - $this->assertTrue($test instanceof FileValidator\Count); - } - - public function testAdapterhShouldRaiseExceptionWhenAddingInvalidValidatorType() - { - $this->setExpectedException('Zend\File\Transfer\Exception\InvalidArgumentException', 'Invalid validator provided to addValidator'); - $this->adapter->addValidator(new Filter\BaseName); - } - - public function testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader() - { - $validators = array( - 'count' => array('min' => 1, 'max' => 1), - 'Exists' => 'C:\temp', - array( - 'validator' => 'Upload', - 'options' => array(realpath(__FILE__)) - ), - new FileValidator\Extension('jpg'), - ); - $this->adapter->addValidators($validators); - $test = $this->adapter->getValidators(); - $this->assertTrue(is_array($test)); - $this->assertEquals(4, count($test), var_export($test, 1)); - $count = array_shift($test); - $this->assertTrue($count instanceof FileValidator\Count); - $exists = array_shift($test); - $this->assertTrue($exists instanceof FileValidator\Exists); - $size = array_shift($test); - $this->assertTrue($size instanceof FileValidator\Upload); - $ext = array_shift($test); - $this->assertTrue($ext instanceof FileValidator\Extension); - $orig = array_pop($validators); - $this->assertSame($orig, $ext); - } - - public function testGetValidatorShouldReturnNullWhenNoMatchingIdentifierExists() - { - $this->assertNull($this->adapter->getValidator('Between')); - } - - public function testAdapterShouldAllowPullingValidatorsByFile() - { - $this->adapter->addValidator('Between', false, false, 'foo'); - $validators = $this->adapter->getValidators('foo'); - $this->assertEquals(1, count($validators)); - $validator = array_shift($validators); - $this->assertTrue($validator instanceof Validator\Between); - } - - public function testCallingSetValidatorsOnAdapterShouldOverwriteExistingValidators() - { - $this->testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader(); - $validators = array( - new FileValidator\Count(1), - new FileValidator\Extension('jpg'), - ); - $this->adapter->setValidators($validators); - $test = $this->adapter->getValidators(); - $this->assertSame($validators, array_values($test)); - } - - public function testAdapterShouldAllowRetrievingValidatorInstancesByClassName() - { - $this->testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader(); - $ext = $this->adapter->getValidator('Zend\Validator\File\Extension'); - $this->assertTrue($ext instanceof FileValidator\Extension); - } - - public function testAdapterShouldAllowRetrievingValidatorInstancesByPluginName() - { - $this->testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader(); - $count = $this->adapter->getValidator('Count'); - $this->assertTrue($count instanceof FileValidator\Count); - } - - public function testAdapterShouldAllowRetrievingAllValidatorsAtOnce() - { - $this->testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader(); - $validators = $this->adapter->getValidators(); - $this->assertTrue(is_array($validators)); - $this->assertEquals(4, count($validators)); - foreach ($validators as $validator) { - $this->assertTrue($validator instanceof Validator\ValidatorInterface); - } - } - - public function testAdapterShouldAllowRemovingValidatorInstancesByClassName() - { - $this->testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader(); - $this->assertTrue($this->adapter->hasValidator('Zend\Validator\File\Extension')); - $this->adapter->removeValidator('Zend\Validator\File\Extension'); - $this->assertFalse($this->adapter->hasValidator('Zend\Validator\File\Extension')); - } - - public function testAdapterShouldAllowRemovingValidatorInstancesByPluginName() - { - $this->testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader(); - $this->assertTrue($this->adapter->hasValidator('Count')); - $this->adapter->removeValidator('Count'); - $this->assertFalse($this->adapter->hasValidator('Count')); - } - - public function testRemovingNonexistentValidatorShouldDoNothing() - { - $this->testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader(); - $validators = $this->adapter->getValidators(); - $this->assertFalse($this->adapter->hasValidator('Between')); - $this->adapter->removeValidator('Between'); - $this->assertFalse($this->adapter->hasValidator('Between')); - $test = $this->adapter->getValidators(); - $this->assertSame($validators, $test); - } - - public function testAdapterShouldAllowRemovingAllValidatorsAtOnce() - { - $this->testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoader(); - $this->adapter->clearValidators(); - $validators = $this->adapter->getValidators(); - $this->assertTrue(is_array($validators)); - $this->assertEquals(0, count($validators)); - } - - public function testValidationShouldReturnTrueForValidTransfer() - { - $this->adapter->addValidator('Count', false, array(1, 3), 'foo'); - $this->assertTrue($this->adapter->isValid('foo')); - } - - public function testValidationShouldReturnTrueForValidTransferOfMultipleFiles() - { - $this->assertTrue($this->adapter->isValid(null)); - } - - public function testValidationShouldReturnFalseForInvalidTransfer() - { - $this->adapter->addValidator('Extension', false, 'png', 'foo'); - $this->assertFalse($this->adapter->isValid('foo')); - } - - public function testValidationShouldThrowExceptionForNonexistentFile() - { - $this->assertFalse($this->adapter->isValid('bogus')); - } - - public function testErrorMessagesShouldBeEmptyByDefault() - { - $messages = $this->adapter->getMessages(); - $this->assertTrue(is_array($messages)); - $this->assertEquals(0, count($messages)); - } - - public function testErrorMessagesShouldBePopulatedAfterInvalidTransfer() - { - $this->testValidationShouldReturnFalseForInvalidTransfer(); - $messages = $this->adapter->getMessages(); - $this->assertTrue(is_array($messages)); - $this->assertFalse(empty($messages)); - } - - public function testErrorCodesShouldBeNullByDefault() - { - $errors = $this->adapter->getErrors(); - $this->assertTrue(is_array($errors)); - $this->assertEquals(0, count($errors)); - } - - public function testErrorCodesShouldBePopulatedAfterInvalidTransfer() - { - $this->testValidationShouldReturnFalseForInvalidTransfer(); - $errors = $this->adapter->getErrors(); - $this->assertTrue(is_array($errors)); - $this->assertFalse(empty($errors)); - } - - public function testAdapterShouldLazyLoadFilterPluginManager() - { - $loader = $this->adapter->getFilterManager(); - $this->assertInstanceOf('Zend\File\Transfer\Adapter\FilterPluginManager', $loader); - } - - public function testAdapterShouldAllowAddingFilterInstance() - { - $filter = new Filter\StringToLower(); - $this->adapter->addFilter($filter); - $test = $this->adapter->getFilter('Zend\Filter\StringToLower'); - $this->assertSame($filter, $test); - } - - public function testAdapterShouldAllowAddingFilterViaPluginManager() - { - $this->adapter->addFilter('StringTrim'); - $test = $this->adapter->getFilter('StringTrim'); - $this->assertTrue($test instanceof Filter\StringTrim); - } - - - public function testAdapterhShouldRaiseExceptionWhenAddingInvalidFilterType() - { - $this->setExpectedException('Zend\File\Transfer\Exception\InvalidArgumentException', 'Invalid filter specified'); - $this->adapter->addFilter(new FileValidator\Extension('jpg')); - } - - public function testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader() - { - $filters = array( - 'Word\SeparatorToCamelCase' => array('separator' => ' '), - array( - 'filter' => 'Boolean', - 'casting' => true - ), - new Filter\BaseName(), - ); - $this->adapter->addFilters($filters); - $test = $this->adapter->getFilters(); - $this->assertTrue(is_array($test)); - $this->assertEquals(3, count($test), var_export($test, 1)); - $count = array_shift($test); - $this->assertTrue($count instanceof Word\SeparatorToCamelCase); - $size = array_shift($test); - $this->assertTrue($size instanceof Filter\Boolean); - $ext = array_shift($test); - $orig = array_pop($filters); - $this->assertSame($orig, $ext); - } - - public function testGetFilterShouldReturnNullWhenNoMatchingIdentifierExists() - { - $this->assertNull($this->adapter->getFilter('Boolean')); - } - - public function testAdapterShouldAllowPullingFiltersByFile() - { - $this->adapter->addFilter('Boolean', 1, 'foo'); - $filters = $this->adapter->getFilters('foo'); - $this->assertEquals(1, count($filters)); - $filter = array_shift($filters); - $this->assertTrue($filter instanceof Filter\Boolean); - } - - public function testCallingSetFiltersOnAdapterShouldOverwriteExistingFilters() - { - $this->testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader(); - $filters = array( - new Filter\StringToUpper(), - new Filter\Boolean(), - ); - $this->adapter->setFilters($filters); - $test = $this->adapter->getFilters(); - $this->assertSame($filters, array_values($test)); - } - - public function testAdapterShouldAllowRetrievingFilterInstancesByClassName() - { - $this->testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader(); - $ext = $this->adapter->getFilter('Zend\Filter\BaseName'); - $this->assertTrue($ext instanceof Filter\BaseName); - } - - public function testAdapterShouldAllowRetrievingFilterInstancesByPluginName() - { - $this->testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader(); - $count = $this->adapter->getFilter('Boolean'); - $this->assertTrue($count instanceof Filter\Boolean); - } - - public function testAdapterShouldAllowRetrievingAllFiltersAtOnce() - { - $this->testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader(); - $filters = $this->adapter->getFilters(); - $this->assertTrue(is_array($filters)); - $this->assertEquals(3, count($filters)); - foreach ($filters as $filter) { - $this->assertTrue($filter instanceof Filter\FilterInterface); - } - } - - public function testAdapterShouldAllowRemovingFilterInstancesByClassName() - { - $this->testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader(); - $this->assertTrue($this->adapter->hasFilter('Zend\Filter\BaseName')); - $this->adapter->removeFilter('Zend\Filter\BaseName'); - $this->assertFalse($this->adapter->hasFilter('Zend\Filter\BaseName')); - } - - public function testAdapterShouldAllowRemovingFilterInstancesByPluginName() - { - $this->testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader(); - $this->assertTrue($this->adapter->hasFilter('Boolean')); - $this->adapter->removeFilter('Boolean'); - $this->assertFalse($this->adapter->hasFilter('Boolean')); - } - - public function testRemovingNonexistentFilterShouldDoNothing() - { - $this->testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader(); - $filters = $this->adapter->getFilters(); - $this->assertFalse($this->adapter->hasFilter('Int')); - $this->adapter->removeFilter('Int'); - $this->assertFalse($this->adapter->hasFilter('Int')); - $test = $this->adapter->getFilters(); - $this->assertSame($filters, $test); - } - - public function testAdapterShouldAllowRemovingAllFiltersAtOnce() - { - $this->testAdapterShouldAllowAddingMultipleFiltersAtOnceUsingBothInstancesAndPluginLoader(); - $this->adapter->clearFilters(); - $filters = $this->adapter->getFilters(); - $this->assertTrue(is_array($filters)); - $this->assertEquals(0, count($filters)); - } - - public function testTransferDestinationShouldBeMutable() - { - $directory = __DIR__; - $this->adapter->setDestination($directory); - $destinations = $this->adapter->getDestination(); - $this->assertTrue(is_array($destinations)); - foreach ($destinations as $file => $destination) { - $this->assertEquals($directory, $destination); - } - - $newdirectory = __DIR__ - . DIRECTORY_SEPARATOR . '_files'; - $this->adapter->setDestination($newdirectory, 'foo'); - $this->assertEquals($newdirectory, $this->adapter->getDestination('foo')); - $this->assertEquals($directory, $this->adapter->getDestination('bar')); - } - - public function testAdapterShouldAllowRetrievingDestinationsForAnArrayOfSpecifiedFiles() - { - $this->adapter->setDestination(__DIR__); - $destinations = $this->adapter->getDestination(array('bar', 'baz')); - $this->assertTrue(is_array($destinations)); - $directory = __DIR__; - foreach ($destinations as $file => $destination) { - $this->assertTrue(in_array($file, array('bar', 'baz'))); - $this->assertEquals($directory, $destination); - } - } - - public function testSettingAndRetrievingOptions() - { - $this->assertEquals( - array( - 'bar' => array('ignoreNoFile' => false, 'useByteString' => true), - 'baz' => array('ignoreNoFile' => false, 'useByteString' => true), - 'foo' => array('ignoreNoFile' => false, 'useByteString' => true, 'detectInfos' => true), - 'file_0_' => array('ignoreNoFile' => false, 'useByteString' => true), - 'file_1_' => array('ignoreNoFile' => false, 'useByteString' => true), - ), $this->adapter->getOptions()); - - $this->adapter->setOptions(array('ignoreNoFile' => true)); - $this->assertEquals( - array( - 'bar' => array('ignoreNoFile' => true, 'useByteString' => true), - 'baz' => array('ignoreNoFile' => true, 'useByteString' => true), - 'foo' => array('ignoreNoFile' => true, 'useByteString' => true, 'detectInfos' => true), - 'file_0_' => array('ignoreNoFile' => true, 'useByteString' => true), - 'file_1_' => array('ignoreNoFile' => true, 'useByteString' => true), - ), $this->adapter->getOptions()); - - $this->adapter->setOptions(array('ignoreNoFile' => false), 'foo'); - $this->assertEquals( - array( - 'bar' => array('ignoreNoFile' => true, 'useByteString' => true), - 'baz' => array('ignoreNoFile' => true, 'useByteString' => true), - 'foo' => array('ignoreNoFile' => false, 'useByteString' => true, 'detectInfos' => true), - 'file_0_' => array('ignoreNoFile' => true, 'useByteString' => true), - 'file_1_' => array('ignoreNoFile' => true, 'useByteString' => true), - ), $this->adapter->getOptions()); - } - - public function testGetAllAdditionalFileInfos() - { - $files = $this->adapter->getFileInfo(); - $this->assertEquals(5, count($files)); - $this->assertEquals('baz.text', $files['baz']['name']); - } - - public function testGetAdditionalFileInfosForSingleFile() - { - $files = $this->adapter->getFileInfo('baz'); - $this->assertEquals(1, count($files)); - $this->assertEquals('baz.text', $files['baz']['name']); - } - - public function testGetAdditionalFileInfosForUnknownFile() - { - $this->setExpectedException('Zend\File\Transfer\Exception\RuntimeException', 'The file transfer adapter can not find "unknown"'); - $files = $this->adapter->getFileInfo('unknown'); - } - - public function testAdapterShouldAllowRetrievingFileName() - { - $path = __DIR__ - . DIRECTORY_SEPARATOR . '_files'; - $this->adapter->setDestination($path); - $this->assertEquals($path . DIRECTORY_SEPARATOR . 'foo.jpg', $this->adapter->getFileName('foo')); - } - - public function testAdapterShouldAllowRetrievingFileNameWithoutPath() - { - $path = __DIR__ - . DIRECTORY_SEPARATOR . '_files'; - $this->adapter->setDestination($path); - $this->assertEquals('foo.jpg', $this->adapter->getFileName('foo', false)); - } - - public function testAdapterShouldAllowRetrievingAllFileNames() - { - $path = __DIR__ - . DIRECTORY_SEPARATOR . '_files'; - $this->adapter->setDestination($path); - $files = $this->adapter->getFileName(); - $this->assertTrue(is_array($files)); - $this->assertEquals($path . DIRECTORY_SEPARATOR . 'bar.png', $files['bar']); - } - - public function testAdapterShouldAllowRetrievingAllFileNamesWithoutPath() - { - $path = __DIR__ - . DIRECTORY_SEPARATOR . '_files'; - $this->adapter->setDestination($path); - $files = $this->adapter->getFileName(null, false); - $this->assertTrue(is_array($files)); - $this->assertEquals('bar.png', $files['bar']); - } - - public function testExceptionForUnknownHashValue() - { - $this->setExpectedException('Zend\File\Transfer\Exception\InvalidArgumentException', 'Unknown hash algorithm'); - $this->adapter->getHash('foo', 'unknown_hash'); - } - - public function testIgnoreHashValue() - { - $this->adapter->addInvalidFile(); - $return = $this->adapter->getHash('crc32', 'test'); - $this->assertEquals(array(), $return); - } - - public function testEmptyTempDirectoryDetection() - { - $this->adapter->tmpDir = ""; - $this->assertTrue(empty($this->adapter->tmpDir), "Empty temporary directory"); - } - - public function testTempDirectoryDetection() - { - $this->adapter->getTmpDir(); - $this->assertTrue(!empty($this->adapter->tmpDir), "Temporary directory filled"); - } - - public function testTemporaryDirectoryAccessDetection() - { - $this->adapter->tmpDir = "."; - $path = "/NoPath/To/File"; - $this->assertFalse($this->adapter->isPathWriteable($path)); - $this->assertTrue($this->adapter->isPathWriteable($this->adapter->tmpDir)); - } - - public function testFileSizeButNoFileFound() - { - $this->setExpectedException('Zend\File\Transfer\Exception\InvalidArgumentException', 'does not exist'); - $this->assertEquals(10, $this->adapter->getFileSize()); - } - - public function testIgnoreFileSize() - { - $this->adapter->addInvalidFile(); - $return = $this->adapter->getFileSize('test'); - $this->assertEquals(array(), $return); - } - - public function testFileSizeByTmpName() - { - $expectedSize = sprintf("%.2fkB", 1.14); - $options = $this->adapter->getOptions(); - $this->assertTrue($options['baz']['useByteString']); - $this->assertEquals($expectedSize, $this->adapter->getFileSize('baz.text')); - $this->adapter->setOptions(array('useByteString' => false)); - $options = $this->adapter->getOptions(); - $this->assertFalse($options['baz']['useByteString']); - $this->assertEquals(1172, $this->adapter->getFileSize('baz.text')); - } - - public function testMimeTypeButNoFileFound() - { - $this->setExpectedException('Zend\File\Transfer\Exception\InvalidArgumentException', 'does not exist'); - $this->assertEquals('image/jpeg', $this->adapter->getMimeType()); - } - - public function testIgnoreMimeType() - { - $this->adapter->addInvalidFile(); - $return = $this->adapter->getMimeType('test'); - $this->assertEquals(array(), $return); - } - - public function testMimeTypeByTmpName() - { - $this->assertEquals('text/plain', $this->adapter->getMimeType('baz.text')); - } - - public function testSetOwnErrorMessage() - { - $this->adapter->addValidator('Count', false, array('min' => 5, 'max' => 5, 'messages' => array(FileValidator\Count::TOO_FEW => 'Zu wenige'))); - $this->assertFalse($this->adapter->isValid('foo')); - $message = $this->adapter->getMessages(); - $this->assertContains('Zu wenige', $message); - - $this->setExpectedException('Zend\File\Transfer\Exception\InvalidArgumentException', 'does not exist'); - $this->assertEquals('image/jpeg', $this->adapter->getMimeType()); - } - - public function testTransferDestinationAtNonExistingElement() - { - $directory = __DIR__; - $this->adapter->setDestination($directory, 'nonexisting'); - $this->assertEquals($directory, $this->adapter->getDestination('nonexisting')); - - $this->setExpectedException('Zend\File\Transfer\Exception\InvalidArgumentException', 'not find'); - $this->assertTrue(is_string($this->adapter->getDestination('reallynonexisting'))); - } - - /** - * @ZF-7376 - */ - public function testSettingMagicFile() - { - $this->adapter->setOptions(array('magicFile' => 'test/file')); - $this->assertEquals( - array( - 'bar' => array('magicFile' => 'test/file', 'ignoreNoFile' => false, 'useByteString' => true), - ), $this->adapter->getOptions('bar')); - } - - /** - * @ZF-8693 - */ - public function testAdapterShouldAllowAddingMultipleValidatorsAtOnceUsingBothInstancesAndPluginLoaderForDifferentFiles() - { - $validators = array( - array('MimeType', true, array('image/jpeg')), // no files - array('FilesSize', true, array('max' => '1MB', 'message' => 'файл больше 1MБ')), // no files - array('Count', true, array('min' => 1, 'max' => '1', 'message' => 'файл не 1'), 'bar'), // 'bar' from config - array('MimeType', true, array('image/jpeg'), 'bar'), // 'bar' from config - ); - - $this->adapter->addValidators($validators, 'foo'); // set validators to 'foo' - - $test = $this->adapter->getValidators(); - $this->assertEquals(3, count($test)); - - //test files specific validators - $test = $this->adapter->getValidators('foo'); - $this->assertEquals(2, count($test)); - $mimeType = array_shift($test); - $this->assertTrue($mimeType instanceof FileValidator\MimeType); - $filesSize = array_shift($test); - $this->assertTrue($filesSize instanceof FileValidator\FilesSize); - - $test = $this->adapter->getValidators('bar'); - $this->assertEquals(2, count($test)); - $filesSize = array_shift($test); - $this->assertTrue($filesSize instanceof FileValidator\Count); - $mimeType = array_shift($test); - $this->assertTrue($mimeType instanceof FileValidator\MimeType); - - $test = $this->adapter->getValidators('baz'); - $this->assertEquals(0, count($test)); - } - - /** - * @ZF-9132 - */ - public function testSettingAndRetrievingDetectInfosOption() - { - $this->assertEquals(array( - 'foo' => array( - 'ignoreNoFile' => false, - 'useByteString' => true, - 'detectInfos' => true)) - , $this->adapter->getOptions('foo')); - $this->adapter->setOptions(array('detectInfos' => false)); - $this->assertEquals(array( - 'foo' => array( - 'ignoreNoFile' => false, - 'useByteString' => true, - 'detectInfos' => false)) - , $this->adapter->getOptions('foo')); - } -} diff --git a/tests/ZendTest/File/Transfer/Adapter/HttpTest.php b/tests/ZendTest/File/Transfer/Adapter/HttpTest.php deleted file mode 100644 index 721fa264e33..00000000000 --- a/tests/ZendTest/File/Transfer/Adapter/HttpTest.php +++ /dev/null @@ -1,267 +0,0 @@ - array( - 'name' => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'test.txt', - 'type' => 'plain/text', - 'size' => 8, - 'tmp_name' => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'test.txt', - 'error' => 0)); - $this->adapter = new HttpTestMockAdapter(); - } - - /** - * Tears down the fixture, for example, close a network connection. - * This method is called after a test is executed. - * - * @return void - */ - public function tearDown() - { - } - - public function testEmptyAdapter() - { - $files = $this->adapter->getFileName(); - $this->assertContains('test.txt', $files); - } - - public function testAutoSetUploadValidator() - { - $validators = array( - new FileValidator\Count(1), - new FileValidator\Extension('jpg'), - ); - $this->adapter->setValidators($validators); - $test = $this->adapter->getValidator('Upload'); - $this->assertTrue($test instanceof FileValidator\Upload); - } - - public function testSendingFiles() - { - $this->setExpectedException('Zend\File\Transfer\Exception\BadMethodCallException', 'not implemented'); - $this->adapter->send(); - } - - public function testFileIsSent() - { - $this->setExpectedException('Zend\File\Transfer\Exception\BadMethodCallException', 'not implemented'); - $this->adapter->isSent(); - } - - public function testFileIsUploaded() - { - $this->assertTrue($this->adapter->isUploaded()); - } - - public function testFileIsNotUploaded() - { - $this->assertFalse($this->adapter->isUploaded('unknownFile')); - } - - public function testFileIsNotFiltered() - { - $this->assertFalse($this->adapter->isFiltered('unknownFile')); - $this->assertFalse($this->adapter->isFiltered()); - } - - public function testFileIsNotReceived() - { - $this->assertFalse($this->adapter->isReceived('unknownFile')); - $this->assertFalse($this->adapter->isReceived()); - } - - public function testReceiveUnknownFile() - { - try { - $this->assertFalse($this->adapter->receive('unknownFile')); - } catch (RuntimeException $e) { - $this->assertContains('not find', $e->getMessage()); - } - } - - public function testReceiveValidatedFile() - { - $_FILES = array( - 'txt' => array( - 'name' => 'unknown.txt', - 'type' => 'plain/text', - 'size' => 8, - 'tmp_name' => 'unknown.txt', - 'error' => 0)); - $adapter = new HttpTestMockAdapter(); - $this->assertFalse($adapter->receive()); - } - - public function testReceiveIgnoredFile() - { - $this->adapter->setOptions(array('ignoreNoFile' => true)); - $this->assertTrue($this->adapter->receive()); - } - - public function testReceiveWithRenameFilter() - { - $this->adapter->addFilter('Rename', array('target' => '/testdir')); - $this->adapter->setOptions(array('ignoreNoFile' => true)); - $this->assertTrue($this->adapter->receive()); - } - - public function testReceiveWithRenameFilterButWithoutDirectory() - { - $this->adapter->setDestination(__DIR__); - $this->adapter->addFilter('Rename', array('overwrite' => false)); - $this->adapter->setOptions(array('ignoreNoFile' => true)); - $this->assertTrue($this->adapter->receive()); - } - - public function testMultiFiles() - { - $_FILES = array( - 'txt' => array( - 'name' => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'test.txt', - 'type' => 'plain/text', - 'size' => 8, - 'tmp_name' => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'test.txt', - 'error' => 0), - 'exe' => array( - 'name' => array( - 0 => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'file1.txt', - 1 => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'file2.txt'), - 'type' => array( - 0 => 'plain/text', - 1 => 'plain/text'), - 'size' => array( - 0 => 8, - 1 => 8), - 'tmp_name' => array( - 0 => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'file1.txt', - 1 => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'file2.txt'), - 'error' => array( - 0 => 0, - 1 => 0))); - $adapter = new HttpTestMockAdapter(); - $adapter->setOptions(array('ignoreNoFile' => true)); - $this->assertTrue($adapter->receive('exe')); - $this->assertEquals( - array('exe_0_' => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'file1.txt', - 'exe_1_' => __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'file2.txt'), - $adapter->getFileName('exe', false)); - } - - public function testNoUploadInProgress() - { - if (!Adapter\Http::isApcAvailable() && !Adapter\Http::isUploadProgressAvailable()) { - $this->markTestSkipped('Whether APC nor UploadExtension available'); - } - - $status = HttpTestMockAdapter::getProgress(); - $this->assertContains('No upload in progress', $status); - } - - public function testUploadProgressFailure() - { - if (!Adapter\Http::isApcAvailable() && !Adapter\Http::isUploadProgressAvailable()) { - $this->markTestSkipped('Whether APC nor UploadExtension available'); - } - - $_GET['progress_key'] = 'mykey'; - $status = HttpTestMockAdapter::getProgress(); - $this->assertEquals(array( - 'total' => 100, - 'current' => 100, - 'rate' => 10, - 'id' => 'mykey', - 'done' => false, - 'message' => '100B - 100B' - ), $status); - - $this->adapter->switchApcToUP(); - $status = HttpTestMockAdapter::getProgress($status); - $this->assertEquals(array( - 'total' => 100, - 'bytes_total' => 100, - 'current' => 100, - 'bytes_uploaded' => 100, - 'rate' => 10, - 'speed_average' => 10, - 'cancel_upload' => true, - 'message' => 'The upload has been canceled', - 'done' => true, - 'id' => 'mykey' - ), $status); - } - - public function testUploadProgressAdapter() - { - if (!Adapter\Http::isApcAvailable() && !Adapter\Http::isUploadProgressAvailable()) { - $this->markTestSkipped('Whether APC nor UploadExtension available'); - } - - $_GET['progress_key'] = 'mykey'; - $adapter = new AdapterProgressBar\Console(); - $status = array('progress' => $adapter, 'session' => 'upload'); - $status = HttpTestMockAdapter::getProgress($status); - $this->assertTrue(array_key_exists('total', $status)); - $this->assertTrue(array_key_exists('current', $status)); - $this->assertTrue(array_key_exists('rate', $status)); - $this->assertTrue(array_key_exists('id', $status)); - $this->assertTrue(array_key_exists('message', $status)); - $this->assertTrue(array_key_exists('progress', $status)); - $this->assertTrue($status['progress'] instanceof ProgressBar\ProgressBar); - - $this->adapter->switchApcToUP(); - $status = HttpTestMockAdapter::getProgress($status); - $this->assertTrue(array_key_exists('total', $status)); - $this->assertTrue(array_key_exists('current', $status)); - $this->assertTrue(array_key_exists('rate', $status)); - $this->assertTrue(array_key_exists('id', $status)); - $this->assertTrue(array_key_exists('message', $status)); - $this->assertTrue(array_key_exists('progress', $status)); - $this->assertTrue($status['progress'] instanceof ProgressBar\ProgressBar); - } - - public function testValidationOfPhpExtendsFormError() - { - $_SERVER['CONTENT_LENGTH'] = 10; - - $_FILES = array(); - $adapter = new HttpTestMockAdapter(); - $this->assertFalse($adapter->isValidParent()); - $this->assertContains('exceeds the defined ini size', current($adapter->getMessages())); - } -} diff --git a/tests/ZendTest/File/Transfer/Adapter/HttpTestMockAdapter.php b/tests/ZendTest/File/Transfer/Adapter/HttpTestMockAdapter.php deleted file mode 100644 index c6472add4d6..00000000000 --- a/tests/ZendTest/File/Transfer/Adapter/HttpTestMockAdapter.php +++ /dev/null @@ -1,61 +0,0 @@ - 100, 'current' => 100, 'rate' => 10); - } - - public static function uPTest($id) - { - return array('bytes_total' => 100, 'bytes_uploaded' => 100, 'speed_average' => 10, 'cancel_upload' => true); - } - - public function switchApcToUP() - { - self::$callbackApc = null; - self::$callbackUploadProgress = array('ZendTest\File\Transfer\Adapter\HttpTestMockAdapter', 'uPTest'); - } -} diff --git a/tests/ZendTest/File/Transfer/Adapter/_files/file1.txt b/tests/ZendTest/File/Transfer/Adapter/_files/file1.txt deleted file mode 100644 index e7cbb71a0d5..00000000000 --- a/tests/ZendTest/File/Transfer/Adapter/_files/file1.txt +++ /dev/null @@ -1 +0,0 @@ -testfile \ No newline at end of file diff --git a/tests/ZendTest/File/Transfer/Adapter/_files/file2.txt b/tests/ZendTest/File/Transfer/Adapter/_files/file2.txt deleted file mode 100644 index e7cbb71a0d5..00000000000 --- a/tests/ZendTest/File/Transfer/Adapter/_files/file2.txt +++ /dev/null @@ -1 +0,0 @@ -testfile \ No newline at end of file diff --git a/tests/ZendTest/File/Transfer/Adapter/_files/test.txt b/tests/ZendTest/File/Transfer/Adapter/_files/test.txt deleted file mode 100644 index e7cbb71a0d5..00000000000 --- a/tests/ZendTest/File/Transfer/Adapter/_files/test.txt +++ /dev/null @@ -1 +0,0 @@ -testfile \ No newline at end of file diff --git a/tests/ZendTest/Filter/File/RenameTest.php b/tests/ZendTest/Filter/File/RenameTest.php index e28ebee1025..bf2f457f4f7 100644 --- a/tests/ZendTest/Filter/File/RenameTest.php +++ b/tests/ZendTest/Filter/File/RenameTest.php @@ -411,7 +411,7 @@ public function testAddFileWithInvalidOption() /** * @return void */ - public function testInvalidContruction() + public function testInvalidConstruction() { $this->setExpectedException('\Zend\Filter\Exception\InvalidArgumentException', 'Invalid options'); $filter = new FileRename(1234); diff --git a/tests/ZendTest/Filter/File/RenameUploadTest.php b/tests/ZendTest/Filter/File/RenameUploadTest.php new file mode 100644 index 00000000000..421b126d2a3 --- /dev/null +++ b/tests/ZendTest/Filter/File/RenameUploadTest.php @@ -0,0 +1,491 @@ +_filesPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR; + $this->_origFile = $this->_filesPath . 'original.file'; + $this->_oldFile = $this->_filesPath . 'testfile.txt'; + $this->_newFile = $this->_filesPath . 'newfile.xml'; + $this->_newDir = $this->_filesPath . DIRECTORY_SEPARATOR . '_testDir2'; + $this->_newDirFile = $this->_newDir . DIRECTORY_SEPARATOR . 'testfile.txt'; + + if (file_exists($this->_origFile)) { + unlink($this->_origFile); + } + + if (file_exists($this->_newFile)) { + unlink($this->_newFile); + } + + if (file_exists($this->_newDirFile)) { + unlink($this->_newDirFile); + } + + copy($this->_oldFile, $this->_origFile); + } + + /** + * Sets the path to test files + * + * @return void + */ + public function tearDown() + { + if (!file_exists($this->_oldFile)) { + copy($this->_origFile, $this->_oldFile); + } + + if (file_exists($this->_origFile)) { + unlink($this->_origFile); + } + + if (file_exists($this->_newFile)) { + unlink($this->_newFile); + } + + if (file_exists($this->_newDirFile)) { + unlink($this->_newDirFile); + } + + if (function_exists("runkit_function_rename") + && function_exists('move_uploaded_file_orig') + ) { + runkit_function_rename('move_uploaded_file', 'move_uploaded_file_mock'); + runkit_function_rename('move_uploaded_file_orig', 'move_uploaded_file'); + } + } + + /** + * Test single parameter filter + * + * @return void + */ + public function testThrowsExceptionWithNonUploadedFile() + { + $filter = new FileRenameUpload($this->_newFile); + + $this->assertEquals(array(0 => + array('source' => '*', + 'target' => $this->_newFile, + 'overwrite' => false)), + $filter->getFile() + ); + $this->assertEquals('falsefile', $filter('falsefile')); + $this->setExpectedException( + 'Zend\Filter\Exception\RuntimeException', 'could not be renamed' + ); + $this->assertEquals($this->_newFile, $filter($this->_oldFile)); + } + + /** + * Mock the move_uploaded_file() function with rename() functionality + * + * @return void + */ + protected function setUpMockMoveUploadedFile() + { + if (!function_exists("runkit_function_rename") + || !ini_get('runkit.internal_override') + ) { + $this->markTestSkipped( + 'move_uploaded_file cannot be unit tested without runkit module' + ); + return; + } + runkit_function_rename('move_uploaded_file', 'move_uploaded_file_orig'); + runkit_function_rename('move_uploaded_file_mock', 'move_uploaded_file'); + } + + /** + * Test single parameter filter + * + * @return void + */ + public function testConstructSingleValue() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload($this->_newFile); + + $this->assertEquals(array(0 => + array('source' => '*', + 'target' => $this->_newFile, + 'overwrite' => false)), + $filter->getFile() + ); + + $this->assertEquals($this->_newFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test single array parameter filter + * + * @return void + */ + public function testConstructSingleArray() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload(array( + 'source' => $this->_oldFile, + 'target' => $this->_newFile)); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newFile, + 'overwrite' => false)), $filter->getFile()); + $this->assertEquals($this->_newFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test full array parameter filter + * + * @return void + */ + public function testConstructFullOptionsArray() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload(array( + 'source' => $this->_oldFile, + 'target' => $this->_newFile, + 'overwrite' => true, + 'unknown' => false)); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newFile, + 'overwrite' => true)), $filter->getFile()); + $this->assertEquals($this->_newFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test single array parameter filter + * + * @return void + */ + public function testConstructDoubleArray() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload(array( + 0 => array( + 'source' => $this->_oldFile, + 'target' => $this->_newFile))); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newFile, + 'overwrite' => false)), $filter->getFile()); + $this->assertEquals($this->_newFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test single array parameter filter + * + * @return void + */ + public function testConstructTruncatedTarget() + { + $filter = new FileRenameUpload(array( + 'source' => $this->_oldFile)); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => '*', + 'overwrite' => false)), $filter->getFile()); + + $this->assertEquals($this->_oldFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test single array parameter filter + * + * @return void + */ + public function testConstructTruncatedSource() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload(array( + 'target' => $this->_newFile)); + + $this->assertEquals(array(0 => + array('source' => '*', + 'target' => $this->_newFile, + 'overwrite' => false)), $filter->getFile()); + + $this->assertEquals($this->_newFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test single parameter filter by using directory only + * + * @return void + */ + public function testConstructSingleDirectory() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload($this->_newDir); + + $this->assertEquals(array(0 => + array('source' => '*', + 'target' => $this->_newDir, + 'overwrite' => false)), $filter->getFile()); + $this->assertEquals($this->_newDirFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test single array parameter filter by using directory only + * + * @return void + */ + public function testConstructSingleArrayDirectory() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload(array( + 'source' => $this->_oldFile, + 'target' => $this->_newDir)); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newDir, + 'overwrite' => false)), $filter->getFile()); + $this->assertEquals($this->_newDirFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test single array parameter filter by using directory only + * + * @return void + */ + public function testConstructDoubleArrayDirectory() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload(array( + 0 => array( + 'source' => $this->_oldFile, + 'target' => $this->_newDir))); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newDir, + 'overwrite' => false)), $filter->getFile()); + $this->assertEquals($this->_newDirFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * Test single array parameter filter by using directory only + * + * @return void + */ + public function testConstructTruncatedSourceDirectory() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload(array( + 'target' => $this->_newDir)); + + $this->assertEquals(array(0 => + array('source' => '*', + 'target' => $this->_newDir, + 'overwrite' => false)), $filter->getFile()); + + $this->assertEquals($this->_newDirFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * @return void + */ + public function testAddSameFileAgainAndOverwriteExistingTarget() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload(array( + 'source' => $this->_oldFile, + 'target' => $this->_newDir)); + + $filter->addFile(array( + 'source' => $this->_oldFile, + 'target' => $this->_newFile)); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newFile, + 'overwrite' => false)), $filter->getFile()); + $this->assertEquals($this->_newFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * @return void + */ + public function testGetNewName() + { + $filter = new FileRenameUpload(array( + 'source' => $this->_oldFile, + 'target' => $this->_newDir)); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newDir, + 'overwrite' => false)), $filter->getFile()); + $this->assertEquals($this->_newDirFile, $filter->getNewName($this->_oldFile)); + } + + /** + * @return void + */ + public function testGetNewNameExceptionWithExistingFile() + { + $filter = new FileRenameUpload(array( + 'source' => $this->_oldFile, + 'target' => $this->_newFile)); + + copy($this->_oldFile, $this->_newFile); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newFile, + 'overwrite' => false)), $filter->getFile()); + + $this->setExpectedException('\Zend\Filter\Exception\InvalidArgumentException', 'could not be renamed'); + $this->assertEquals($this->_newFile, $filter->getNewName($this->_oldFile)); + } + + /** + * @return void + */ + public function testGetNewNameOverwriteWithExistingFile() + { + $filter = new FileRenameUpload(array( + 'source' => $this->_oldFile, + 'target' => $this->_newFile, + 'overwrite' => true)); + + copy($this->_oldFile, $this->_newFile); + + $this->assertEquals(array(0 => + array('source' => $this->_oldFile, + 'target' => $this->_newFile, + 'overwrite' => true)), $filter->getFile()); + $this->assertEquals($this->_newFile, $filter->getNewName($this->_oldFile)); + } + + /** + * @return void + */ + public function testAddFileWithString() + { + $this->setUpMockMoveUploadedFile(); + + $filter = new FileRenameUpload($this->_oldFile); + $filter->addFile($this->_newFile); + + $this->assertEquals(array(0 => + array('source' => '*', + 'target' => $this->_newFile, + 'overwrite' => false)), $filter->getFile()); + $this->assertEquals($this->_newFile, $filter($this->_oldFile)); + $this->assertEquals('falsefile', $filter('falsefile')); + } + + /** + * @return void + */ + public function testAddFileWithInvalidOption() + { + $filter = new FileRenameUpload($this->_oldFile); + $this->setExpectedException('\Zend\Filter\Exception\InvalidArgumentException', 'Invalid options'); + $filter->addFile(1234); + } + + /** + * @return void + */ + public function testInvalidConstruction() + { + $this->setExpectedException('\Zend\Filter\Exception\InvalidArgumentException', 'Invalid options'); + $filter = new FileRenameUpload(1234); + } +} diff --git a/tests/ZendTest/Form/Element/File/ApcProgressTest.php b/tests/ZendTest/Form/Element/File/ApcProgressTest.php new file mode 100644 index 00000000000..3f44b5dc1ac --- /dev/null +++ b/tests/ZendTest/Form/Element/File/ApcProgressTest.php @@ -0,0 +1,44 @@ +markTestSkipped('APC module is not active'); + } + } + + public function testAlwaysReturnsApcName() + { + $name = ini_get('apc.rfc1867_name'); + $element = new ApcProgressElement('foo'); + $this->assertEquals($name, $element->getName()); + $element->setName('bar'); + $this->assertEquals($name, $element->getName()); + } + + public function testValueIsPopulatedWithUniqueId() + { + $element = new ApcProgressElement(); + $value1 = $element->getValue(); + $this->assertNotEmpty($value1); + $element->setValue(null); + $value2 = $element->getValue(); + $this->assertNotEmpty($value2); + $this->assertNotEquals($value2, $value1); + } +} diff --git a/tests/ZendTest/Form/Element/File/SessionProgressTest.php b/tests/ZendTest/Form/Element/File/SessionProgressTest.php new file mode 100644 index 00000000000..0b2a8460890 --- /dev/null +++ b/tests/ZendTest/Form/Element/File/SessionProgressTest.php @@ -0,0 +1,44 @@ +markTestSkipped('Session Upload Progress feature is not active'); + } + } + + public function testAlwaysReturnsSessionName() + { + $name = ini_get('session.upload_progress.name'); + $element = new SessionProgressElement('foo'); + $this->assertEquals($name, $element->getName()); + $element->setName('bar'); + $this->assertEquals($name, $element->getName()); + } + + public function testValueIsPopulatedWithUniqueId() + { + $element = new SessionProgressElement(); + $value1 = $element->getValue(); + $this->assertNotEmpty($value1); + $element->setValue(null); + $value2 = $element->getValue(); + $this->assertNotEmpty($value2); + $this->assertNotEquals($value2, $value1); + } +} diff --git a/tests/ZendTest/Form/Element/File/UploadProgressTest.php b/tests/ZendTest/Form/Element/File/UploadProgressTest.php new file mode 100644 index 00000000000..21210e7e882 --- /dev/null +++ b/tests/ZendTest/Form/Element/File/UploadProgressTest.php @@ -0,0 +1,37 @@ +assertEquals($name, $element->getName()); + $element->setName('bar'); + $this->assertEquals($name, $element->getName()); + } + + public function testValueIsPopulatedWithUniqueId() + { + $element = new UploadProgressElement(); + $value1 = $element->getValue(); + $this->assertNotEmpty($value1); + $element->setValue(null); + $value2 = $element->getValue(); + $this->assertNotEmpty($value2); + $this->assertNotEquals($value2, $value1); + } +} diff --git a/tests/ZendTest/Form/Element/FileTest.php b/tests/ZendTest/Form/Element/FileTest.php new file mode 100644 index 00000000000..f1cc055c6e1 --- /dev/null +++ b/tests/ZendTest/Form/Element/FileTest.php @@ -0,0 +1,62 @@ +assertEquals('file', $element->getAttribute('type')); + + $inputSpec = $element->getInputSpecification(); + $factory = new InputFilterFactory(); + $input = $factory->createInput($inputSpec); + $this->assertInstanceOf('Zend\InputFilter\FileInput', $input); + + $validators = $input->getValidatorChain()->getValidators(); + $this->assertNotEmpty($validators); + $this->assertInstanceOf('Zend\Validator\File\Upload', $validators[0]['instance']); + } + + public function testProvidesDefaultInputSpecificationForMultiple() + { + $element = new FileElement('foo'); + $element->setAttribute('multiple', true); + $this->assertEquals('file', $element->getAttribute('type')); + + $inputSpec = $element->getInputSpecification(); + $factory = new InputFilterFactory(); + $input = $factory->createInput($inputSpec); + $this->assertInstanceOf('Zend\InputFilter\FileInput', $input); + + $validators = $input->getValidatorChain()->getValidators(); + $this->assertNotEmpty($validators); + $validator = $validators[0]['instance']; + $this->assertInstanceOf('Zend\Validator\File\Explode', $validator); + $this->assertInstanceOf('Zend\Validator\File\Upload', $validator->getValidator()); + } + + public function testWillAddFileEnctypeAttributeToForm() + { + $file = new FileElement('foo'); + $formMock = $this->getMock('Zend\Form\Form'); + $formMock->expects($this->exactly(1)) + ->method('setAttribute') + ->with($this->stringContains('enctype'), + $this->stringContains('multipart/form-data')); + $file->prepareElement($formMock); + } +} diff --git a/tests/ZendTest/Form/View/Helper/FormFileTest.php b/tests/ZendTest/Form/View/Helper/FormFileTest.php index 193155fd90f..e88aac2287f 100644 --- a/tests/ZendTest/Form/View/Helper/FormFileTest.php +++ b/tests/ZendTest/Form/View/Helper/FormFileTest.php @@ -20,36 +20,70 @@ */ class FormFileTest extends CommonTestCase { + /** + * @return void + */ public function setUp() { $this->helper = new FormFileHelper(); parent::setUp(); } + /** + * @return void + */ public function testRaisesExceptionWhenNameIsNotPresentInElement() { - $element = new Element(); + $element = new Element\File(); $this->setExpectedException('Zend\Form\Exception\DomainException', 'name'); $this->helper->render($element); } + /** + * @return void + */ public function testGeneratesFileInputTagWithElement() { - $element = new Element('foo'); + $element = new Element\File('foo'); $markup = $this->helper->render($element); $this->assertContains('assertContains('type="file"', $markup); } + /** + * @return void + */ public function testGeneratesFileInputTagRegardlessOfElementType() { - $element = new Element('foo'); + $element = new Element\File('foo'); $element->setAttribute('type', 'email'); $markup = $this->helper->render($element); $this->assertContains('assertContains('type="file"', $markup); } + /** + * @return void + */ + public function testRendersElementWithFileArrayValue() + { + $element = new Element\File('foo'); + $element->setValue(array( + 'tmp_name' => '/tmp/foofile', + 'name' => 'foofile', + 'type' => 'text', + 'size' => 200, + 'error' => 2, + )); + $markup = $this->helper->render($element); + $this->assertContains('assertContains('type="file"', $markup); + $this->assertContains('value="foofile"', $markup); + } + + /** + * @return array + */ public function validAttributes() { return array( @@ -72,7 +106,7 @@ public function validAttributes() array('max', 'assertNotContains'), array('maxlength', 'assertNotContains'), array('min', 'assertNotContains'), - array('multiple', 'assertContains'), + array('multiple', 'assertNotContains'), array('pattern', 'assertNotContains'), array('placeholder', 'assertNotContains'), array('readonly', 'assertNotContains'), @@ -85,9 +119,12 @@ public function validAttributes() ); } + /** + * @return Element\File + */ public function getCompleteElement() { - $element = new Element('foo'); + $element = new Element\File('foo'); $element->setAttributes(array( 'accept' => 'value', 'alt' => 'value', @@ -108,7 +145,7 @@ public function getCompleteElement() 'max' => 'value', 'maxlength' => 'value', 'min' => 'value', - 'multiple' => 'multiple', + 'multiple' => false, 'name' => 'value', 'pattern' => 'value', 'placeholder' => 'value', @@ -141,15 +178,32 @@ public function testAllValidFormMarkupAttributesPresentInElementAreRendered($att $this->$assertion($expect, $markup); } + /** + * @return void + */ + public function testNameShouldHaveArrayNotationWhenMultipleIsSpecified() + { + $element = new Element\File('foo'); + $element->setAttribute('multiple', true); + $markup = $this->helper->render($element); + $this->assertRegexp('#]*?(name="foo\[\]")#', $markup); + } + + /** + * @return void + */ public function testInvokeProxiesToRender() { - $element = new Element('foo'); + $element = new Element\File('foo'); $markup = $this->helper->__invoke($element); $this->assertContains('assertContains('name="foo"', $markup); $this->assertContains('type="file"', $markup); } + /** + * @return void + */ public function testInvokeWithNoElementChainsHelper() { $this->assertSame($this->helper, $this->helper->__invoke()); diff --git a/tests/ZendTest/InputFilter/BaseInputFilterTest.php b/tests/ZendTest/InputFilter/BaseInputFilterTest.php index 2187e9e01e5..59fceab2f0b 100644 --- a/tests/ZendTest/InputFilter/BaseInputFilterTest.php +++ b/tests/ZendTest/InputFilter/BaseInputFilterTest.php @@ -13,6 +13,7 @@ use PHPUnit_Framework_TestCase as TestCase; use stdClass; use Zend\InputFilter\Input; +use Zend\InputFilter\FileInput; use Zend\InputFilter\BaseInputFilter as InputFilter; use Zend\Filter; use Zend\Validator; @@ -414,6 +415,65 @@ public function testValidationSkipsFieldsMarkedNotRequiredWhenNoDataPresent() $this->assertTrue($filter->isValid()); } + public function testValidationSkipsFileInputsMarkedNotRequiredWhenNoFileDataIsPresent() + { + $filter = new InputFilter(); + + $foo = new FileInput(); + $foo->getValidatorChain()->addValidator(new Validator\File\Upload()); + $foo->setRequired(false); + + $filter->add($foo, 'foo'); + + $data = array( + 'foo' => array( + 'tmp_name' => '/tmp/barfile', + 'name' => 'barfile', + 'type' => 'text', + 'size' => 0, + 'error' => 4, // UPLOAD_ERR_NO_FILE + ) + ); + $filter->setData($data); + $this->assertTrue($filter->isValid()); + + // Negative test + $foo->setRequired(true); + $filter->setData($data); + $this->assertFalse($filter->isValid()); + } + + public function testValidationSkipsFileInputsMarkedNotRequiredWhenNoMultiFileDataIsPresent() + { + $filter = new InputFilter(); + + $explode = new Validator\File\Explode(); + $explode->setValidator(new Validator\File\Upload()); + + $foo = new FileInput(); + $foo->getValidatorChain()->addValidator($explode); + $foo->setRequired(false); + + $filter->add($foo, 'foo'); + + $data = array( + 'foo' => array(array( + 'tmp_name' => '/tmp/barfile', + 'name' => 'barfile', + 'type' => 'text', + 'size' => 0, + 'error' => 4, // UPLOAD_ERR_NO_FILE + )), + ); + $filter->setData($data); + $this->assertTrue($filter->isValid()); + + // Negative test + $foo->setRequired(true); + $filter->setData($data); + $this->assertFalse($filter->isValid()); + } + public function testValidationAllowsEmptyValuesToRequiredInputWhenAllowEmptyFlagIsTrue() { $filter = new InputFilter(); diff --git a/tests/ZendTest/InputFilter/FileInputTest.php b/tests/ZendTest/InputFilter/FileInputTest.php new file mode 100644 index 00000000000..8748ba9c708 --- /dev/null +++ b/tests/ZendTest/InputFilter/FileInputTest.php @@ -0,0 +1,242 @@ +assertEquals('foo', $input->getName()); + } + + public function testInputHasEmptyFilterChainByDefault() + { + $input = new FileInput('foo'); + $filters = $input->getFilterChain(); + $this->assertInstanceOf('Zend\Filter\FilterChain', $filters); + $this->assertEquals(0, count($filters)); + } + + public function testInputHasEmptyValidatorChainByDefault() + { + $input = new FileInput('foo'); + $validators = $input->getValidatorChain(); + $this->assertInstanceOf('Zend\Validator\ValidatorChain', $validators); + $this->assertEquals(0, count($validators)); + } + + public function testCanInjectFilterChain() + { + $input = new FileInput('foo'); + $chain = new Filter\FilterChain(); + $input->setFilterChain($chain); + $this->assertSame($chain, $input->getFilterChain()); + } + + public function testCanInjectValidatorChain() + { + $input = new FileInput('foo'); + $chain = new Validator\ValidatorChain(); + $input->setValidatorChain($chain); + $this->assertSame($chain, $input->getValidatorChain()); + } + + public function testInputIsMarkedAsRequiredByDefault() + { + $input = new FileInput('foo'); + $this->assertTrue($input->isRequired()); + } + + public function testRequiredFlagIsMutable() + { + $input = new FileInput('foo'); + $input->setRequired(false); + $this->assertFalse($input->isRequired()); + } + + public function testInputDoesNotAllowEmptyValuesByDefault() + { + $input = new FileInput('foo'); + $this->assertFalse($input->allowEmpty()); + } + + public function testAllowEmptyFlagIsMutable() + { + $input = new FileInput('foo'); + $input->setAllowEmpty(true); + $this->assertTrue($input->allowEmpty()); + } + + public function testValueIsNullByDefault() + { + $input = new FileInput('foo'); + $this->assertNull($input->getValue()); + } + + public function testValueMayBeInjected() + { + $input = new FileInput('foo'); + $input->setValue('bar'); + $this->assertEquals('bar', $input->getValue()); + } + + public function testRetrievingValueFiltersTheValueOnlyAfterValidating() + { + $input = new FileInput('foo'); + $input->setValue('bar'); + $filter = new Filter\StringToUpper(); + $input->getFilterChain()->attach($filter); + $this->assertEquals('bar', $input->getValue()); + $this->assertTrue($input->isValid()); + $this->assertEquals('BAR', $input->getValue()); + } + + public function testCanRetrieveRawValue() + { + $input = new FileInput('foo'); + $input->setValue('bar'); + $filter = new Filter\StringToUpper(); + $input->getFilterChain()->attach($filter); + $this->assertEquals('bar', $input->getRawValue()); + } + + public function testIsValidReturnsFalseIfValidationChainFails() + { + $input = new FileInput('foo'); + $input->setValue('bar'); + $validator = new Validator\Digits(); + $input->getValidatorChain()->addValidator($validator); + $this->assertFalse($input->isValid()); + } + + public function testIsValidReturnsTrueIfValidationChainSucceeds() + { + $input = new FileInput('foo'); + $input->setValue('123'); + $validator = new Validator\Digits(); + $input->getValidatorChain()->addValidator($validator); + $this->assertTrue($input->isValid()); + } + + public function testValidationOperatesBeforeFiltering() + { + $input = new FileInput('foo'); + $input->setValue(' 123 '); + $filter = new Filter\StringTrim(); + $input->getFilterChain()->attach($filter); + $validator = new Validator\Digits(); + $input->getValidatorChain()->addValidator($validator); + $this->assertFalse($input->isValid()); + $input->setValue('123'); + $this->assertTrue($input->isValid()); + } + + public function testGetMessagesReturnsValidationMessages() + { + $input = new FileInput('foo'); + $input->setValue('bar'); + $validator = new Validator\Digits(); + $input->getValidatorChain()->addValidator($validator); + $this->assertFalse($input->isValid()); + $messages = $input->getMessages(); + $this->assertArrayHasKey(Validator\Digits::NOT_DIGITS, $messages); + } + + public function testSpecifyingMessagesToInputReturnsThoseOnFailedValidation() + { + $input = new FileInput('foo'); + $input->setValue('bar'); + $validator = new Validator\Digits(); + $input->getValidatorChain()->addValidator($validator); + $input->setErrorMessage('Please enter only digits'); + $this->assertFalse($input->isValid()); + $messages = $input->getMessages(); + $this->assertArrayNotHasKey(Validator\Digits::NOT_DIGITS, $messages); + $this->assertContains('Please enter only digits', $messages); + } + + public function testBreakOnFailureFlagIsOffByDefault() + { + $input = new FileInput('foo'); + $this->assertFalse($input->breakOnFailure()); + } + + public function testBreakOnFailureFlagIsMutable() + { + $input = new FileInput('foo'); + $input->setBreakOnFailure(true); + $this->assertTrue($input->breakOnFailure()); + } + + public function testNotEmptyValidatorIsNotAddedWhenIsValidIsCalled() + { + $input = new FileInput('foo'); + $this->assertTrue($input->isRequired()); + $input->setValue(''); + $validatorChain = $input->getValidatorChain(); + $this->assertEquals(0, count($validatorChain->getValidators())); + + $this->assertTrue($input->isValid()); + $messages = $input->getMessages(); + $this->assertEquals(0, count($validatorChain->getValidators())); + } + + public function testRequiredNotEmptyValidatorNotAddedWhenOneExists() + { + $input = new FileInput('foo'); + $this->assertTrue($input->isRequired()); + $input->setValue(''); + + $notEmptyMock = $this->getMock('Zend\Validator\NotEmpty', array('isValid')); + $notEmptyMock->expects($this->exactly(1)) + ->method('isValid') + ->will($this->returnValue(false)); + + $validatorChain = $input->getValidatorChain(); + $validatorChain->prependValidator($notEmptyMock); + $this->assertFalse($input->isValid()); + + $validators = $validatorChain->getValidators(); + $this->assertEquals(1, count($validators)); + $this->assertEquals($notEmptyMock, $validators[0]['instance']); + } + + public function testMerge() + { + $input = new FileInput('foo'); + $input->setValue(' 123 '); + $filter = new Filter\StringTrim(); + $input->getFilterChain()->attach($filter); + $validator = new Validator\Digits(); + $input->getValidatorChain()->addValidator($validator); + + $input2 = new FileInput('bar'); + $input2->merge($input); + $validatorChain = $input->getValidatorChain(); + $filterChain = $input->getFilterChain(); + + $this->assertEquals(' 123 ', $input2->getRawValue()); + $this->assertEquals(1, $validatorChain->count()); + $this->assertEquals(1, $filterChain->count()); + + $validators = $validatorChain->getValidators(); + $this->assertInstanceOf('Zend\Validator\Digits', $validators[0]['instance']); + + $filters = $filterChain->getFilters()->toArray(); + $this->assertInstanceOf('Zend\Filter\StringTrim', $filters[0]); + } +} diff --git a/tests/ZendTest/Mvc/Controller/Plugin/FilePostRedirectGetTest.php b/tests/ZendTest/Mvc/Controller/Plugin/FilePostRedirectGetTest.php new file mode 100644 index 00000000000..bc84cad82ce --- /dev/null +++ b/tests/ZendTest/Mvc/Controller/Plugin/FilePostRedirectGetTest.php @@ -0,0 +1,232 @@ +form = new Form(); + + $router = new SimpleRouteStack; + $router->addRoute('home', LiteralRoute::factory(array( + 'route' => '/', + 'defaults' => array( + 'controller' => 'ZendTest\Mvc\Controller\TestAsset\SampleController', + ) + ))); + + $router->addRoute('sub', SegmentRoute::factory(array( + 'route' => '/foo/:param', + 'defaults' => array( + 'param' => 1 + ) + ))); + + $this->controller = new SampleController(); + $this->request = new Request(); + $this->event = new MvcEvent(); + $this->routeMatch = new RouteMatch(array('controller' => 'controller-sample', 'action' => 'postPage')); + + $this->event->setRequest($this->request); + $this->event->setRouteMatch($this->routeMatch); + $this->event->setRouter($router); + + $this->sessionManager = new SessionManager(); + $this->sessionManager->destroy(); + + $this->controller->setEvent($this->event); + $this->controller->flashMessenger()->setSessionManager($this->sessionManager); + } + + public function testReturnsFalseOnIntialGet() + { + $result = $this->controller->dispatch($this->request, $this->response); + $prgResult = $this->controller->fileprg($this->form, 'home'); + + $this->assertFalse($prgResult); + } + + public function testRedirectsToUrlOnPost() + { + $this->request->setMethod('POST'); + $this->request->setPost(new Parameters(array( + 'postval1' => 'value' + ))); + + $this->controller->dispatch($this->request, $this->response); + $prgResultUrl = $this->controller->fileprg($this->form, '/test/getPage', true); + + $this->assertInstanceOf('Zend\Http\Response', $prgResultUrl); + $this->assertTrue($prgResultUrl->getHeaders()->has('Location')); + $this->assertEquals('/test/getPage', $prgResultUrl->getHeaders()->get('Location')->getUri()); + $this->assertEquals(303, $prgResultUrl->getStatusCode()); + } + + public function testRedirectsToRouteOnPost() + { + $this->request->setMethod('POST'); + $this->request->setPost(new Parameters(array( + 'postval1' => 'value1' + ))); + + $this->controller->dispatch($this->request, $this->response); + $prgResultRoute = $this->controller->fileprg($this->form, 'home'); + + $this->assertInstanceOf('Zend\Http\Response', $prgResultRoute); + $this->assertTrue($prgResultRoute->getHeaders()->has('Location')); + $this->assertEquals('/', $prgResultRoute->getHeaders()->get('Location')->getUri()); + $this->assertEquals(303, $prgResultRoute->getStatusCode()); + } + + /** + * @expectedException Zend\Mvc\Exception\RuntimeException + */ + public function testThrowsExceptionOnRouteWithoutRouter() + { + $controller = $this->controller; + $controller = $controller->getEvent()->setRouter(new SimpleRouteStack); + + $this->request->setMethod('POST'); + $this->request->setPost(new Parameters(array( + 'postval1' => 'value' + ))); + + $this->controller->dispatch($this->request, $this->response); + $this->controller->fileprg($this->form, 'some/route'); + } + + public function testNullRouteUsesMatchedRouteName() + { + $this->controller->getEvent()->getRouteMatch()->setMatchedRouteName('home'); + + $this->request->setMethod('POST'); + $this->request->setPost(new Parameters(array( + 'postval1' => 'value1' + ))); + + $this->controller->dispatch($this->request, $this->response); + $prgResultRoute = $this->controller->fileprg($this->form); + + $this->assertInstanceOf('Zend\Http\Response', $prgResultRoute); + $this->assertTrue($prgResultRoute->getHeaders()->has('Location')); + $this->assertEquals('/', $prgResultRoute->getHeaders()->get('Location')->getUri()); + $this->assertEquals(303, $prgResultRoute->getStatusCode()); + } + + public function testReuseMatchedParameters() + { + $this->controller->getEvent()->getRouteMatch()->setMatchedRouteName('sub'); + + $this->request->setMethod('POST'); + $this->request->setPost(new Parameters(array( + 'postval1' => 'value1' + ))); + + $this->controller->dispatch($this->request, $this->response); + $prgResultRoute = $this->controller->fileprg($this->form); + + $this->assertInstanceOf('Zend\Http\Response', $prgResultRoute); + $this->assertTrue($prgResultRoute->getHeaders()->has('Location')); + $this->assertEquals('/foo/1', $prgResultRoute->getHeaders()->get('Location')->getUri()); + $this->assertEquals(303, $prgResultRoute->getStatusCode()); + } + + public function testReturnsPostOnRedirectGet() + { + // Do POST + $params = array( + 'postval1' => 'value' + ); + $this->request->setMethod('POST'); + $this->request->setPost(new Parameters($params)); + + $this->form->add(array( + 'name' => 'postval1' + )); + + $this->controller->dispatch($this->request, $this->response); + $prgResultUrl = $this->controller->fileprg($this->form, '/test/getPage', true); + + $this->assertInstanceOf('Zend\Http\Response', $prgResultUrl); + $this->assertTrue($prgResultUrl->getHeaders()->has('Location')); + $this->assertEquals('/test/getPage', $prgResultUrl->getHeaders()->get('Location')->getUri()); + $this->assertEquals(303, $prgResultUrl->getStatusCode()); + + // Do GET + $this->request = new Request(); + $this->controller->dispatch($this->request, $this->response); + $prgResult = $this->controller->fileprg($this->form, '/test/getPage', true); + + $this->assertEquals($params, $prgResult); + $this->assertEquals($params['postval1'], $this->form->get('postval1')->getValue()); + } + + public function testAppliesFormErrorsOnPostRedirectGet() + { + // Do POST + $params = array(); + $this->request->setMethod('POST'); + $this->request->setPost(new Parameters($params)); + + $this->form->add(array( + 'name' => 'postval1' + )); + $inputFilter = new InputFilter(); + $inputFilter->add(array( + 'name' => 'postval1', + 'required' => true, + )); + $this->form->setInputFilter($inputFilter); + + $this->controller->dispatch($this->request, $this->response); + $prgResultUrl = $this->controller->fileprg($this->form, '/test/getPage', true); + $this->assertInstanceOf('Zend\Http\Response', $prgResultUrl); + $this->assertTrue($prgResultUrl->getHeaders()->has('Location')); + $this->assertEquals('/test/getPage', $prgResultUrl->getHeaders()->get('Location')->getUri()); + $this->assertEquals(303, $prgResultUrl->getStatusCode()); + + // Do GET + $this->request = new Request(); + $this->controller->dispatch($this->request, $this->response); + $prgResult = $this->controller->fileprg($this->form, '/test/getPage', true); + $messages = $this->form->getMessages(); + + $this->assertEquals($params, $prgResult); + $this->assertNotEmpty($messages['postval1']['isEmpty']); + } +} diff --git a/tests/ZendTest/ProgressBar/Upload/AbstractUploadHandlerTest.php b/tests/ZendTest/ProgressBar/Upload/AbstractUploadHandlerTest.php new file mode 100644 index 00000000000..a10a61f1723 --- /dev/null +++ b/tests/ZendTest/ProgressBar/Upload/AbstractUploadHandlerTest.php @@ -0,0 +1,171 @@ + 1000, + 'current' => 500, + 'rate' => 0, + 'message' => '', + 'done' => false, + ); + $stub = $this->getMockForAbstractClass( + 'Zend\ProgressBar\Upload\AbstractUploadHandler' + ); + $stub->expects($this->any()) + ->method('getUploadProgress') + ->will($this->returnValue($progressData)); + + $progressData['id'] = '123'; + $progressData['message'] = '500B - 1000B'; + $this->assertEquals($progressData, $stub->getProgress('123')); + } + + /** + * @return void + */ + public function testGetNoFileInProgress() + { + $status = array( + 'total' => 0, + 'current' => 0, + 'rate' => 0, + 'message' => 'No upload in progress', + 'done' => true + ); + $stub = $this->getMockForAbstractClass( + 'Zend\ProgressBar\Upload\AbstractUploadHandler' + ); + $stub->expects($this->any()) + ->method('getUploadProgress') + ->will($this->returnValue(false)); + $this->assertEquals($status, $stub->getProgress('123')); + } + + /** + * @return array + */ + public function progressDataProvider() + { + return array( + array(array( + 'total' => 1000, + 'current' => 200, + 'rate' => 0, + 'message' => '', + 'done' => false, + )), + array(array( + 'total' => 1000, + 'current' => 600, + 'rate' => 300, + 'message' => '', + 'done' => false, + )), + array(array( + 'total' => 1000, + 'current' => 1000, + 'rate' => 500, + 'message' => '', + 'done' => true, + )), + ); + } + + /** + * @dataProvider progressDataProvider + * @param array $progressData + * @return void + */ + public function testProgressAdapterNotify($progressData) + { + $adapterStub = $this->getMockForAbstractClass( + 'Zend\ProgressBar\Adapter\AbstractAdapter' + ); + if ($progressData['done']) { + $adapterStub->expects($this->once()) + ->method('finish'); + } else { + $adapterStub->expects($this->once()) + ->method('notify'); + } + + $stub = $this->getMockForAbstractClass( + 'Zend\ProgressBar\Upload\AbstractUploadHandler' + ); + $stub->expects($this->once()) + ->method('getUploadProgress') + ->will($this->returnValue($progressData)); + $stub->setOptions(array( + 'session_namespace' => 'testSession', + 'progress_adapter' => $adapterStub, + )); + + $this->assertEquals('testSession', $stub->getSessionNamespace()); + $this->assertEquals($adapterStub, $stub->getProgressAdapter()); + + $this->assertNotEmpty($stub->getProgress('123')); + } + + /** + * @dataProvider progressDataProvider + * @param array $progressData + * @return void + */ + public function testProgressBarUpdate($progressData) + { + $adapterStub = $this->getMockForAbstractClass( + 'Zend\ProgressBar\Adapter\AbstractAdapter' + ); + if ($progressData['done']) { + $adapterStub->expects($this->once()) + ->method('finish'); + } else { + $adapterStub->expects($this->once()) + ->method('notify'); + } + $progressBar = new ProgressBar( + $adapterStub, 0, $progressData['total'], 'testSession' + ); + + + $stub = $this->getMockForAbstractClass( + 'Zend\ProgressBar\Upload\AbstractUploadHandler' + ); + $stub->expects($this->once()) + ->method('getUploadProgress') + ->will($this->returnValue($progressData)); + $stub->setOptions(array( + 'session_namespace' => 'testSession', + 'progress_adapter' => $progressBar, + )); + + $this->assertEquals('testSession', $stub->getSessionNamespace()); + $this->assertEquals($progressBar, $stub->getProgressAdapter()); + + $this->assertNotEmpty($stub->getProgress('123')); + } +} diff --git a/tests/ZendTest/Validator/File/CountTest.php b/tests/ZendTest/Validator/File/CountTest.php deleted file mode 100644 index 8442e682daa..00000000000 --- a/tests/ZendTest/Validator/File/CountTest.php +++ /dev/null @@ -1,124 +0,0 @@ - 0, 'max' => 3), true, true, true, false), - array(array('min' => 2, 'max' => 3), false, true, true, false), - array(array('min' => 2), false, true, true, true), - array(array('max' => 5), true, true, true, true), - ); - - foreach ($valuesExpected as $element) { - $validator = new File\Count($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/testsize.mo'), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[2], - $validator->isValid(__DIR__ . '/_files/testsize2.mo'), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[3], - $validator->isValid(__DIR__ . '/_files/testsize3.mo'), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[4], - $validator->isValid(__DIR__ . '/_files/testsize4.mo'), - "Tested with " . var_export($element, 1) - ); - } - } - - /** - * Ensures that getMin() returns expected value - * - * @return void - */ - public function testGetMin() - { - $validator = new File\Count(array('min' => 1, 'max' => 5)); - $this->assertEquals(1, $validator->getMin()); - } - - public function testGetMinGreaterThanOrEqualThrowsException() - { - $this->setExpectedException('Zend\Validator\Exception\InvalidArgumentException', 'greater than or equal'); - $validator = new File\Count(array('min' => 5, 'max' => 1)); - } - - /** - * Ensures that setMin() returns expected value - * - * @return void - */ - public function testSetMin() - { - $validator = new File\Count(array('min' => 1000, 'max' => 10000)); - $validator->setMin(100); - $this->assertEquals(100, $validator->getMin()); - - $this->setExpectedException('Zend\Validator\Exception\InvalidArgumentException', 'less than or equal'); - $validator->setMin(20000); - } - - /** - * Ensures that getMax() returns expected value - * - * @return void - */ - public function testGetMax() - { - $validator = new File\Count(array('min' => 1, 'max' => 100)); - $this->assertEquals(100, $validator->getMax()); - - $this->setExpectedException('Zend\Validator\Exception\InvalidArgumentException', 'greater than or equal'); - $validator = new File\Count(array('min' => 5, 'max' => 1)); - } - - /** - * Ensures that setMax() returns expected value - * - * @return void - */ - public function testSetMax() - { - $validator = new File\Count(array('min' => 1000, 'max' => 10000)); - $validator->setMax(1000000); - $this->assertEquals(1000000, $validator->getMax()); - - $validator->setMin(100); - $this->assertEquals(1000000, $validator->getMax()); - } -} diff --git a/tests/ZendTest/Validator/File/Crc32Test.php b/tests/ZendTest/Validator/File/Crc32Test.php index 45c9aa29e4d..b50cd2fa3ec 100644 --- a/tests/ZendTest/Validator/File/Crc32Test.php +++ b/tests/ZendTest/Validator/File/Crc32Test.php @@ -21,63 +21,57 @@ class Crc32Test extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array('3f8d07e2', true), - array('9f8d07e2', false), - array(array('9f8d07e2', '3f8d07e2'), true), - array(array('9f8d07e2', '7f8d07e2'), false), + $testFile = __DIR__ . '/_files/picture.jpg'; + $pictureTests = array( + // Options, isValid Param, Expected value, Expected message + array('3f8d07e2', $testFile, true, ''), + array('9f8d07e2', $testFile, false, 'fileCrc32DoesNotMatch'), + array(array('9f8d07e2', '3f8d07e2'), $testFile, true, ''), + array(array('9f8d07e2', '7f8d07e2'), $testFile, false, 'fileCrc32DoesNotMatch'), ); - foreach ($valuesExpected as $element) { - $validator = new File\Crc32($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/picture.jpg'), - "Tested with " . var_export($element, 1) - ); - } - - $validator = new File\Crc32('3f8d07e2'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); - $this->assertTrue(array_key_exists('fileCrc32NotFound', $validator->getMessages())); - - $files = array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0 + $testFile = __DIR__ . '/_files/nofile.mo'; + $noFileTests = array( + // Options, isValid Param, Expected value, message + array('3f8d07e2', $testFile, false, 'fileCrc32NotFound'), ); - $validator = new File\Crc32('3f8d07e2'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo', $files)); - $this->assertTrue(array_key_exists('fileCrc32NotFound', $validator->getMessages())); - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\Crc32('3f8d07e2'); - $this->assertTrue($validator->isValid(__DIR__ . '/_files/picture.jpg', $files)); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 + $testFile = __DIR__ . '/_files/testsize.mo'; + $sizeFileTests = array( + // Options, isValid Param, Expected value, message + array('ffeb8d5d', $testFile, true, ''), + array('9f8d07e2', $testFile, false, 'fileCrc32DoesNotMatch'), ); - $validator = new File\Crc32('9f8d07e2'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/picture.jpg', $files)); - $this->assertTrue(array_key_exists('fileCrc32DoesNotMatch', $validator->getMessages())); + + // Dupe data in File Upload format + $testData = array_merge($pictureTests, $noFileTests, $sizeFileTests); + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' + ); + $testData[] = array($data[0], $fileUpload, $data[2], $data[3]); + } + return $testData; + } + + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected, $messageKey) + { + $validator = new File\Crc32($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); + if (!$expected) { + $this->assertTrue(array_key_exists($messageKey, $validator->getMessages())); + } } /** @@ -176,6 +170,6 @@ public function testZF11258() $validator = new File\Crc32('3f8d07e2'); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileCrc32NotFound', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/ExcludeExtensionTest.php b/tests/ZendTest/Validator/File/ExcludeExtensionTest.php index 93cf692ad4e..04b401c3cca 100644 --- a/tests/ZendTest/Validator/File/ExcludeExtensionTest.php +++ b/tests/ZendTest/Validator/File/ExcludeExtensionTest.php @@ -21,65 +21,52 @@ class ExcludeExtensionTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array('mo', false), - array('gif', true), - array(array('mo'), false), - array(array('gif'), true), - array(array('gif', 'pdf', 'mo', 'pict'), false), - array(array('gif', 'gz', 'hint'), true), + $testFile = __DIR__ . '/_files/testsize.mo'; + $pictureTests = array( + // Options, isValid Param, Expected value, Expected message + array('mo', $testFile, false, 'fileExcludeExtensionFalse'), + array('gif', $testFile, true, ''), + array(array('mo'), $testFile, false, 'fileExcludeExtensionFalse'), + array(array('gif'), $testFile, true, ''), + array(array('gif', 'mo', 'pict'), $testFile, false, 'fileExcludeExtensionFalse'), + array(array('gif', 'gz', 'hint'), $testFile, true, ''), ); - foreach ($valuesExpected as $element) { - $validator = new File\ExcludeExtension($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/testsize.mo'), - "Tested with " . var_export($element, 1) - ); - } - - $validator = new File\ExcludeExtension('mo'); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/nofile.mo')); - $this->assertTrue(array_key_exists('fileExcludeExtensionNotFound', $validator->getMessages())); - - $files = array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0 + $testFile = __DIR__ . '/_files/nofile.mo'; + $noFileTests = array( + // Options, isValid Param, Expected value, message + array('mo', $testFile, false, 'fileExcludeExtensionNotFound'), ); - $validator = new File\ExcludeExtension('mo'); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/nofile.mo', $files)); - $this->assertTrue(array_key_exists('fileExcludeExtensionNotFound', $validator->getMessages())); - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\ExcludeExtension('mo'); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/testsize.mo', $files)); - $this->assertTrue(array_key_exists('fileExcludeExtensionFalse', $validator->getMessages())); + // Dupe data in File Upload format + $testData = array_merge($pictureTests, $noFileTests); + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' + ); + $testData[] = array($data[0], $fileUpload, $data[2], $data[3]); + } + return $testData; + } - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\ExcludeExtension('gif'); - $this->assertEquals(true, $validator->isValid(__DIR__ . '/_files/testsize.mo', $files)); + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected, $messageKey) + { + $validator = new File\ExcludeExtension($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); + if (!$expected) { + $this->assertTrue(array_key_exists($messageKey, $validator->getMessages())); + } } public function testCaseTesting() @@ -159,6 +146,6 @@ public function testZF11258() $validator = new File\ExcludeExtension('mo'); $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileExcludeExtensionNotFound', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/ExcludeMimeTypeTest.php b/tests/ZendTest/Validator/File/ExcludeMimeTypeTest.php index ac1cbb252e4..9d902a587ce 100644 --- a/tests/ZendTest/Validator/File/ExcludeMimeTypeTest.php +++ b/tests/ZendTest/Validator/File/ExcludeMimeTypeTest.php @@ -22,41 +22,39 @@ */ class ExcludeMimeTypeTest extends \PHPUnit_Framework_TestCase { - public static function basicValues() + /** + * @return array + */ + public function basicBehaviorDataProvider() { + $testFile = __DIR__ . '/_files/picture.jpg'; + $fileUpload = array( + 'tmp_name' => $testFile, 'name' => basename($testFile), + 'size' => 200, 'error' => 0, 'type' => 'image/jpeg' + ); return array( - array('image/gif', true), - array('image', false), - array('test/notype', true), - array('image/gif, image/jpeg', false), - array(array('image/vasa', 'image/gif'), true), - array(array('image/gif', 'jpeg'), false), - array(array('image/gif', 'gif'), true), + // Options, isValid Param, Expected value + array('image/gif', $fileUpload, true), + array('image', $fileUpload, false), + array('test/notype', $fileUpload, true), + array('image/gif, image/jpeg', $fileUpload, false), + array(array('image/vasa', 'image/gif'), $fileUpload, true), + array(array('image/gif', 'jpeg'), $fileUpload, false), + array(array('image/gif', 'gif'), $fileUpload, true), ); } /** * Ensures that the validator follows expected behavior * - * @group fml - * @dataProvider basicValues + * @dataProvider basicBehaviorDataProvider + * @return void */ - public function testBasic($input, $expected) + public function testBasic($options, $isValidParam, $expected) { - $files = array( - 'name' => 'picture.jpg', - 'type' => 'image/jpeg', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/picture.jpg', - 'error' => 0 - ); - - $validator = new ExcludeMimeType($input); + $validator = new ExcludeMimeType($options); $validator->enableHeaderCheck(); - $this->assertEquals( - $expected, - $validator->isValid(__DIR__ . '/_files/picture.jpg', $files) - ); + $this->assertEquals($expected, $validator->isValid($isValidParam)); } /** diff --git a/tests/ZendTest/Validator/File/ExistsTest.php b/tests/ZendTest/Validator/File/ExistsTest.php index 74cbaa585f8..22f29bc8b78 100644 --- a/tests/ZendTest/Validator/File/ExistsTest.php +++ b/tests/ZendTest/Validator/File/ExistsTest.php @@ -21,86 +21,37 @@ class ExistsTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $baseDir = __DIR__; - $valuesExpected = array( - array($baseDir, 'testsize.mo', false), - array($baseDir . '/_files', 'testsize.mo', true) - ); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 + $testFile = __DIR__ . '/_files/testsize.mo'; + $baseDir = dirname($testFile); + $baseName = basename($testFile); + $fileUpload = array( + 'tmp_name' => $testFile, 'name' => basename($testFile), + 'size' => 200, 'error' => 0, 'type' => 'text' ); - - foreach ($valuesExpected as $element) { - $validator = new File\Exists($element[0]); - $this->assertEquals( - $element[2], - $validator->isValid($element[1]), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[2], - $validator->isValid($element[1], $files), - "Tested with " . var_export($element, 1) - ); - } - - $valuesExpected = array( - array($baseDir, 'testsize.mo', false), - array($baseDir . '/_files', 'testsize.mo', true) - ); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0, - 'destination' => __DIR__ . '/_files' - ); - - foreach ($valuesExpected as $element) { - $validator = new File\Exists($element[0]); - $this->assertEquals( - $element[2], - $validator->isValid($element[1]), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[2], - $validator->isValid($element[1], $files), - "Tested with " . var_export($element, 1) - ); - } - - $valuesExpected = array( - array($baseDir, 'testsize.mo', false, true), - array($baseDir . '/_files', 'testsize.mo', false, true) + return array( + // Options, isValid Param, Expected value + array(dirname($baseDir), $baseName, false), + array($baseDir, $baseName, true), + array($baseDir, $testFile, true), + array(dirname($baseDir), $fileUpload, false), + array($baseDir, $fileUpload, true), ); + } - foreach ($valuesExpected as $element) { - $validator = new File\Exists(); - $this->assertEquals( - $element[2], - $validator->isValid($element[1]), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[3], - $validator->isValid($element[1], $files), - "Tested with " . var_export($element, 1) - ); - } + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected) + { + $validator = new File\Exists($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); } /** @@ -174,6 +125,6 @@ public function testZF11258() $validator = new File\Exists(__DIR__); $this->assertFalse($validator->isValid('nofile.mo')); $this->assertTrue(array_key_exists('fileExistsDoesNotExist', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/ExplodeTest.php b/tests/ZendTest/Validator/File/ExplodeTest.php new file mode 100644 index 00000000000..aaa65a5f6d9 --- /dev/null +++ b/tests/ZendTest/Validator/File/ExplodeTest.php @@ -0,0 +1,103 @@ +setExpectedException('Zend\Validator\Exception\RuntimeException', 'validator'); + + $file = array(array( + 'name' => "test.jpg", + 'type' => 'image/jpeg', + 'tmp_name' => "/private/tmp/php0Pnzdi", + 'error' => 0, + 'size' => 344215, + )); + $validator->isValid($file); + } + + public function getExpectedData() + { + $files = array(); + for ($i = 0; $i < 3; $i++) { + $files[] = array( + 'name' => "test_$i.jpg", + 'type' => 'image/jpeg', + 'tmp_name' => "/private/tmp/php0Pnzdi$i", + 'error' => 0, + 'size' => 344215, + ); + } + $file = array($files[0]); + + return array( + // value break N valid messages expects + array($files, false, 3, true, array(), true), + array($files, true, 1, false, array('X'), false), + array($files, false, 3, false, array('X', 'X', 'X'), false), + array($file, false, 1, true, array(), true), + array($file, false, 1, false, array('X'), false), + array($file, true, 1, false, array('X'), false), + array('foo', false, 0, true, array(FileExplode::INVALID => 'Invalid'), false), + array(1, false, 0, true, array(FileExplode::INVALID => 'Invalid'), false), + ); + } + + /** + * @dataProvider getExpectedData + */ + public function testExpectedBehavior($value, $breakOnFirst, $numIsValidCalls, $isValidReturn, $messages, $expects) + { + $mockValidator = $this->getMock('Zend\Validator\ValidatorInterface'); + $mockValidator->expects($this->exactly($numIsValidCalls))->method('isValid')->will($this->returnValue($isValidReturn)); + $mockValidator->expects($this->any())->method('getMessages')->will($this->returnValue('X')); + + $validator = new FileExplode(array( + 'validator' => $mockValidator, + 'breakOnFirstFailure' => $breakOnFirst, + )); + $validator->setMessage('Invalid', FileExplode::INVALID); + + $this->assertEquals($expects, $validator->isValid($value)); + $this->assertEquals($messages, $validator->getMessages()); + } + + public function testGetMessagesReturnsDefaultValue() + { + $validator = new FileExplode(); + $this->assertEquals(array(), $validator->getMessages()); + } + + public function testEqualsMessageTemplates() + { + $validator = new FileExplode(array()); + $this->assertAttributeEquals($validator->getOption('messageTemplates'), + 'messageTemplates', $validator); + } + + public function testEqualsMessageVariables() + { + $validator = new FileExplode(array()); + $this->assertAttributeEquals($validator->getOption('messageVariables'), + 'messageVariables', $validator); + } +} diff --git a/tests/ZendTest/Validator/File/ExtensionTest.php b/tests/ZendTest/Validator/File/ExtensionTest.php index 88189ee145a..cefa54b1e2a 100644 --- a/tests/ZendTest/Validator/File/ExtensionTest.php +++ b/tests/ZendTest/Validator/File/ExtensionTest.php @@ -21,67 +21,57 @@ class ExtensionTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array('mo', true), - array('gif', false), - array(array('mo'), true), - array(array('gif'), false), - array(array('gif', 'pdf', 'mo', 'pict'), true), - array(array('gif', 'gz', 'hint'), false), + $testFile = __DIR__ . '/_files/testsize.mo'; + $pictureTests = array( + // Options, isValid Param, Expected value, Expected message + array('mo', $testFile, true, ''), + array('gif', $testFile, false, 'fileExtensionFalse'), + array(array('mo'), $testFile, true, ''), + array(array('gif'), $testFile, false, 'fileExtensionFalse'), + array(array('gif', 'mo', 'pict'), $testFile, true, ''), + array(array('gif', 'gz', 'hint'), $testFile, false, 'fileExtensionFalse'), ); - foreach ($valuesExpected as $element) { - $validator = new File\Extension($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/testsize.mo'), - "Tested with " . var_export($element, 1) - ); - } - - $validator = new File\Extension('mo'); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/nofile.mo')); - $this->assertTrue(array_key_exists('fileExtensionNotFound', $validator->getMessages())); - - $files = array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0 + $testFile = __DIR__ . '/_files/nofile.mo'; + $noFileTests = array( + // Options, isValid Param, Expected value, message + array('mo', $testFile, false, 'fileExtensionNotFound'), ); - $validator = new File\Extension('mo'); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/nofile.mo', $files)); - $this->assertTrue(array_key_exists('fileExtensionNotFound', $validator->getMessages())); - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\Extension('mo'); - $this->assertEquals(true, $validator->isValid(__DIR__ . '/_files/testsize.mo', $files)); + // Dupe data in File Upload format + $testData = array_merge($pictureTests, $noFileTests); + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' + ); + $testData[] = array($data[0], $fileUpload, $data[2], $data[3]); + } + return $testData; + } - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\Extension('gif'); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/testsize.mo', $files)); - $this->assertTrue(array_key_exists('fileExtensionFalse', $validator->getMessages())); + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected, $messageKey) + { + $validator = new File\Extension($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); + if (!$expected) { + $this->assertTrue(array_key_exists($messageKey, $validator->getMessages())); + } } + /** + * @return void + */ public function testZF3891() { $files = array( @@ -159,6 +149,6 @@ public function testZF11258() $validator = new File\Extension('gif'); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileExtensionNotFound', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/FilesSizeTest.php b/tests/ZendTest/Validator/File/FilesSizeTest.php deleted file mode 100644 index 8e5e13bb370..00000000000 --- a/tests/ZendTest/Validator/File/FilesSizeTest.php +++ /dev/null @@ -1,190 +0,0 @@ -multipleOptionsDetected = false; - } - - /** - * Ensures that the validator follows expected behavior - * - * @return void - */ - public function testBasic() - { - $valuesExpected = array( - array(array('min' => 0, 'max' => 2000), true, true, false), - array(array('min' => 0, 'max' => '2 MB'), true, true, true), - array(array('min' => 0, 'max' => '2MB'), true, true, true), - array(array('min' => 0, 'max' => '2 MB'), true, true, true), - array(2000, true, true, false), - array(array('min' => 0, 'max' => 500), false, false, false), - array(500, false, false, false) - ); - - foreach ($valuesExpected as $element) { - $validator = new File\FilesSize($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/testsize.mo'), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[2], - $validator->isValid(__DIR__ . '/_files/testsize2.mo'), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[3], - $validator->isValid(__DIR__ . '/_files/testsize3.mo'), - "Tested with " . var_export($element, 1) - ); - } - - $validator = new File\FilesSize(array('min' => 0, 'max' => 200)); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/nofile.mo')); - $this->assertTrue(array_key_exists('fileFilesSizeNotReadable', $validator->getMessages())); - - $validator = new File\FilesSize(array('min' => 0, 'max' => 500000)); - $this->assertEquals(true, $validator->isValid(array( - __DIR__ . '/_files/testsize.mo', - __DIR__ . '/_files/testsize.mo', - __DIR__ . '/_files/testsize2.mo'))); - $this->assertEquals(true, $validator->isValid(__DIR__ . '/_files/testsize.mo')); - } - - /** - * Ensures that getMin() returns expected value - * - * @return void - */ - public function testGetMin() - { - $validator = new File\FilesSize(array('min' => 1, 'max' => 100)); - $this->assertEquals('1B', $validator->getMin()); - - $validator = new File\FilesSize(array('min' => 1, 'max' => 100)); - $this->assertEquals('1B', $validator->getMin()); - - $this->setExpectedException('Zend\Validator\Exception\InvalidArgumentException', 'greater than or equal'); - $validator = new File\FilesSize(array('min' => 100, 'max' => 1)); - } - - /** - * Ensures that setMin() returns expected value - * - * @return void - */ - public function testSetMin() - { - $validator = new File\FilesSize(array('min' => 1000, 'max' => 10000)); - $validator->setMin(100); - $this->assertEquals('100B', $validator->getMin()); - - $this->setExpectedException('Zend\Validator\Exception\InvalidArgumentException', 'less than or equal'); - $validator->setMin(20000); - } - - /** - * Ensures that getMax() returns expected value - * - * @return void - */ - public function testGetMax() - { - $validator = new File\FilesSize(array('min' => 1, 'max' => 100)); - $this->assertEquals('100B', $validator->getMax()); - - $validator = new File\FilesSize(array('min' => 1, 'max' => 100000)); - $this->assertEquals('97.66kB', $validator->getMax()); - - $validator = new File\FilesSize(2000); - $validator->useByteString(false); - $test = $validator->getMax(); - $this->assertEquals('2000', $test); - - $this->setExpectedException('Zend\Validator\Exception\InvalidArgumentException', 'greater than or equal'); - $validator = new File\FilesSize(array('min' => 100, 'max' => 1)); - } - - /** - * Ensures that setMax() returns expected value - * - * @return void - */ - public function testSetMax() - { - $validator = new File\FilesSize(array('min' => 1000, 'max' => 10000)); - $validator->setMax(1000000); - $this->assertEquals('976.56kB', $validator->getMax()); - - $validator->setMin(100); - $this->assertEquals('976.56kB', $validator->getMax()); - } - - public function testConstructorShouldRaiseErrorWhenPassedMultipleOptions() - { - $handler = set_error_handler(array($this, 'errorHandler'), E_USER_NOTICE); - $validator = new File\FilesSize(1000, 10000); - restore_error_handler(); - } - - /** - * Ensures that the validator returns size infos - * - * @return void - */ - public function testFailureMessage() - { - $validator = new File\FilesSize(array('min' => 9999, 'max' => 10000)); - $this->assertFalse($validator->isValid(array( - __DIR__ . '/_files/testsize.mo', - __DIR__ . '/_files/testsize.mo', - __DIR__ . '/_files/testsize2.mo')) - ); - $messages = $validator->getMessages(); - $this->assertContains('9.76kB', current($messages)); - $this->assertContains('1.55kB', current($messages)); - - $validator = new File\FilesSize(array('min' => 9999, 'max' => 10000, 'useByteString' => false)); - $this->assertFalse($validator->isValid(array( - __DIR__ . '/_files/testsize.mo', - __DIR__ . '/_files/testsize.mo', - __DIR__ . '/_files/testsize2.mo')) - ); - $messages = $validator->getMessages(); - $this->assertContains('9999', current($messages)); - $this->assertContains('1588', current($messages)); - } - - public function errorHandler($errno, $errstr) - { - if (strstr($errstr, 'deprecated')) { - $this->multipleOptionsDetected = true; - } - } -} diff --git a/tests/ZendTest/Validator/File/HashTest.php b/tests/ZendTest/Validator/File/HashTest.php index 45233a4eb42..195887899ed 100644 --- a/tests/ZendTest/Validator/File/HashTest.php +++ b/tests/ZendTest/Validator/File/HashTest.php @@ -23,79 +23,73 @@ class HashTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array('3f8d07e2', true), - array('9f8d07e2', false), - array(array('9f8d07e2', '3f8d07e2'), true), - array(array('9f8d07e2', '7f8d07e2'), false), + $testFile = __DIR__ . '/_files/picture.jpg'; + $pictureTests = array( + // Options, isValid Param, Expected value, Expected message + array('3f8d07e2', $testFile, true, ''), + array('9f8d07e2', $testFile, false, 'fileHashDoesNotMatch'), + array(array('9f8d07e2', '3f8d07e2'), $testFile, true, ''), + array(array('9f8d07e2', '7f8d07e2'), $testFile, false, 'fileHashDoesNotMatch'), + array( + array('ed74c22109fe9f110579f77b053b8bc3', 'algorithm' => 'md5'), + $testFile, true, '' + ), + array( + array('4d74c22109fe9f110579f77b053b8bc3', 'algorithm' => 'md5'), + $testFile, false, 'fileHashDoesNotMatch' + ), + array( + array('4d74c22109fe9f110579f77b053b8bc3', 'ed74c22109fe9f110579f77b053b8bc3', 'algorithm' => 'md5'), + $testFile, true, '' + ), + array( + array('4d74c22109fe9f110579f77b053b8bc3', '7d74c22109fe9f110579f77b053b8bc3', 'algorithm' => 'md5'), + $testFile, false, 'fileHashDoesNotMatch' + ), ); - foreach ($valuesExpected as $element) { - $validator = new File\Hash($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/picture.jpg'), - "Tested with " . var_export($element, 1) - ); - } + $testFile = __DIR__ . '/_files/nofile.mo'; + $noFileTests = array( + // Options, isValid Param, Expected value, message + array('3f8d07e2', $testFile, false, 'fileHashNotFound'), + ); - $valuesExpected = array( - array(array('ed74c22109fe9f110579f77b053b8bc3', 'algorithm' => 'md5'), true), - array(array('4d74c22109fe9f110579f77b053b8bc3', 'algorithm' => 'md5'), false), - array(array('4d74c22109fe9f110579f77b053b8bc3', 'ed74c22109fe9f110579f77b053b8bc3', 'algorithm' => 'md5'), true), - array(array('1d74c22109fe9f110579f77b053b8bc3', '4d74c22109fe9f110579f77b053b8bc3', 'algorithm' => 'md5'), false), + $testFile = __DIR__ . '/_files/testsize.mo'; + $sizeFileTests = array( + // Options, isValid Param, Expected value, message + array('ffeb8d5d', $testFile, true, ''), + array('9f8d07e2', $testFile, false, 'fileHashDoesNotMatch'), ); - foreach ($valuesExpected as $element) { - $validator = new File\Hash($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/picture.jpg'), - "Tested with " . var_export($element, 1) + // Dupe data in File Upload format + $testData = array_merge($pictureTests, $noFileTests, $sizeFileTests); + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' ); + $testData[] = array($data[0], $fileUpload, $data[2], $data[3]); } + return $testData; + } - $validator = new File\Hash('3f8d07e2'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); - $this->assertTrue(array_key_exists('fileHashNotFound', $validator->getMessages())); - - $files = array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0 - ); - $validator = new File\Hash('3f8d07e2'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo', $files)); - $this->assertTrue(array_key_exists('fileHashNotFound', $validator->getMessages())); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\Hash('3f8d07e2'); - $this->assertTrue($validator->isValid(__DIR__ . '/_files/picture.jpg', $files)); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\Hash('9f8d07e2'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/picture.jpg', $files)); - $this->assertTrue(array_key_exists('fileHashDoesNotMatch', $validator->getMessages())); + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected, $messageKey) + { + $validator = new File\Hash($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); + if (!$expected) { + $this->assertTrue(array_key_exists($messageKey, $validator->getMessages())); + } } /** @@ -150,6 +144,6 @@ public function testZF11258() $validator = new File\Hash('3f8d07e2'); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileHashNotFound', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/ImageSizeTest.php b/tests/ZendTest/Validator/File/ImageSizeTest.php index c3e277d5de8..eb5180d087f 100644 --- a/tests/ZendTest/Validator/File/ImageSizeTest.php +++ b/tests/ZendTest/Validator/File/ImageSizeTest.php @@ -21,47 +21,95 @@ class ImageSizeTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array(array('minWidth' => 0, 'minHeight' => 10, 'maxWidth' => 1000, 'maxHeight' => 2000), true), - array(array('minWidth' => 0, 'minHeight' => 0, 'maxWidth' => 200, 'maxHeight' => 200), true), - array(array('minWidth' => 150, 'minHeight' => 150, 'maxWidth' => 200, 'maxHeight' => 200), false), - array(array('minWidth' => 80, 'minHeight' => 0, 'maxWidth' => 80, 'maxHeight' => 200), true), - array(array('minWidth' => 0, 'minHeight' => 0, 'maxWidth' => 60, 'maxHeight' => 200), false), - array(array('minWidth' => 90, 'minHeight' => 0, 'maxWidth' => 200, 'maxHeight' => 200), false), - array(array('minWidth' => 0, 'minHeight' => 0, 'maxWidth' => 200, 'maxHeight' => 80), false), - array(array('minWidth' => 0, 'minHeight' => 110, 'maxWidth' => 200, 'maxHeight' => 140), false) + $testFile = __DIR__ . '/_files/picture.jpg'; + $pictureTests = array( + // Options, isValid Param, Expected value, Expected message + array( + array('minWidth' => 0, 'minHeight' => 10, 'maxWidth' => 1000, 'maxHeight' => 2000), + $testFile, true, '' + ), + array( + array('minWidth' => 0, 'minHeight' => 0, 'maxWidth' => 200, 'maxHeight' => 200), + $testFile, true, '' + ), + array( + array('minWidth' => 150, 'minHeight' => 150, 'maxWidth' => 200, 'maxHeight' => 200), + $testFile, false, array('fileImageSizeWidthTooSmall', 'fileImageSizeHeightTooSmall') + ), + array( + array('minWidth' => 80, 'minHeight' => 0, 'maxWidth' => 80, 'maxHeight' => 200), + $testFile, true, '' + ), + array( + array('minWidth' => 0, 'minHeight' => 0, 'maxWidth' => 60, 'maxHeight' => 200), + $testFile, false, 'fileImageSizeWidthTooBig' + ), + array( + array('minWidth' => 90, 'minHeight' => 0, 'maxWidth' => 200, 'maxHeight' => 200), + $testFile, false, 'fileImageSizeWidthTooSmall' + ), + array( + array('minWidth' => 0, 'minHeight' => 0, 'maxWidth' => 200, 'maxHeight' => 80), + $testFile, false, 'fileImageSizeHeightTooBig' + ), + array( + array('minWidth' => 0, 'minHeight' => 110, 'maxWidth' => 200, 'maxHeight' => 140), + $testFile, false, 'fileImageSizeHeightTooSmall' + ), + ); + + $testFile = __DIR__ . '/_files/nofile.mo'; + $noFileTests = array( + // Options, isValid Param, Expected value, message + array( + array('minWidth' => 0, 'minHeight' => 10, 'maxWidth' => 1000, 'maxHeight' => 2000), + $testFile, false, 'fileImageSizeNotReadable' + ), + ); + + $testFile = __DIR__ . '/_files/badpicture.jpg'; + $badPicTests = array( + // Options, isValid Param, Expected value, message + array( + array('minWidth' => 0, 'minHeight' => 10, 'maxWidth' => 1000, 'maxHeight' => 2000), + $testFile, false, 'fileImageSizeNotDetected' + ), ); - foreach ($valuesExpected as $element) { - $validator = new File\ImageSize($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/picture.jpg'), - "Tested with " . var_export($element, 1) + // Dupe data in File Upload format + $testData = array_merge($pictureTests, $noFileTests, $badPicTests); + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' ); + $testData[] = array($data[0], $fileUpload, $data[2], $data[3]); } + return $testData; + } - $validator = new File\ImageSize(array('minWidth' => 0, 'minHeight' => 10, 'maxWidth' => 1000, 'maxHeight' => 2000)); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/nofile.jpg')); - $failures = $validator->getMessages(); - $this->assertContains('is not readable', $failures['fileImageSizeNotReadable']); - - $file['name'] = 'TestName'; - $validator = new File\ImageSize(array('minWidth' => 0, 'minHeight' => 10, 'maxWidth' => 1000, 'maxHeight' => 2000)); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/nofile.jpg', $file)); - $failures = $validator->getMessages(); - $this->assertContains('TestName', $failures['fileImageSizeNotReadable']); - - $validator = new File\ImageSize(array('minWidth' => 0, 'minHeight' => 10, 'maxWidth' => 1000, 'maxHeight' => 2000)); - $this->assertEquals(false, $validator->isValid(__DIR__ . '/_files/badpicture.jpg')); - $failures = $validator->getMessages(); - $this->assertContains('could not be detected', $failures['fileImageSizeNotDetected']); + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected, $messageKeys) + { + $validator = new File\ImageSize($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); + if (!$expected) { + if (!is_array($messageKeys)) { + $messageKeys = array($messageKeys); + } + foreach ($messageKeys as $messageKey) { + $this->assertTrue(array_key_exists($messageKey, $validator->getMessages())); + } + } } /** @@ -194,6 +242,6 @@ public function testZF11258() $validator = new File\ImageSize(array('minWidth' => 100, 'minHeight' => 1000, 'maxWidth' => 10000, 'maxHeight' => 100000)); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileImageSizeNotReadable', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/IsCompressedTest.php b/tests/ZendTest/Validator/File/IsCompressedTest.php index 50b4cdac6cb..6627322d4da 100644 --- a/tests/ZendTest/Validator/File/IsCompressedTest.php +++ b/tests/ZendTest/Validator/File/IsCompressedTest.php @@ -26,57 +26,59 @@ protected function getMagicMime() { // As of PHP >= 5.3.11 and >= 5.4.1 the magic database format has changed. // http://doc.php.net/downloads/pdf/split/de/File-Information.pdf (page 11) - if (version_compare(PHP_VERSION, '5.3.10', '<=') || (version_compare(PHP_VERSION, '5.4', '>=') && - version_compare(PHP_VERSION, '5.4.1', '<'))) { + if (version_compare(PHP_VERSION, '5.3.10', '<=') + || (version_compare(PHP_VERSION, '5.4', '>=') + && version_compare(PHP_VERSION, '5.4.1', '<')) + ) { return __DIR__ . '/_files/magic.lte.5.3.10.mime'; } return __DIR__ . '/_files/magic.mime'; } + /** + * @return array + */ + public function basicBehaviorDataProvider() + { + $testFile = __DIR__ . '/_files/test.zip'; + $fileUpload = array( + 'tmp_name' => $testFile, 'name' => basename($testFile), + 'size' => 200, 'error' => 0, 'type' => 'application/zip' + ); + return array( + // Options, isValid Param, Expected value + array(null, $fileUpload, true), + array('zip', $fileUpload, true), + array('test/notype', $fileUpload, false), + array('application/zip, application/x-tar', $fileUpload, true), + array(array('application/zip', 'application/x-tar'), $fileUpload, true), + array(array('zip', 'tar'), $fileUpload, true), + array(array('tar', 'arj'), $fileUpload, false), + ); + } + /** * Ensures that the validator follows expected behavior * + * @dataProvider basicBehaviorDataProvider * @return void */ - public function testBasic() + public function testBasic($options, $isValidParam, $expected) { if (!extension_loaded('fileinfo') && function_exists('mime_content_type') && ini_get('mime_magic.magicfile') && (mime_content_type(__DIR__ . '/_files/test.zip') == 'text/plain') - ) { - $this->markTestSkipped('This PHP Version has no finfo, has mime_content_type, ' - . ' but mime_content_type exhibits buggy behavior on this system.' - ); - } - - $valuesExpected = array( - array(null, true), - array('zip', true), - array('test/notype', false), - array('application/zip, application/x-tar', true), - array(array('application/zip', 'application/x-tar'), true), - array(array('zip', 'tar'), true), - array(array('tar', 'arj'), false), - ); - - $files = array( - 'name' => 'test.zip', - 'type' => 'application/zip', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/test.zip', - 'error' => 0 - ); - - foreach ($valuesExpected as $element) { - $validator = new File\IsCompressed($element[0]); - $validator->enableHeaderCheck(); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/test.zip', $files), - "Tested with " . var_export($element, 1) + ) { + $this->markTestSkipped( + 'This PHP Version has no finfo, has mime_content_type, ' . + ' but mime_content_type exhibits buggy behavior on this system.' ); } + + $validator = new File\IsCompressed($options); + $validator->enableHeaderCheck(); + $this->assertEquals($expected, $validator->isValid($isValidParam)); } /** @@ -188,6 +190,6 @@ public function testZF11258() $validator = new File\IsCompressed(); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileIsCompressedNotReadable', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/IsImageTest.php b/tests/ZendTest/Validator/File/IsImageTest.php index 0b3b4799dde..cf079a38c0a 100644 --- a/tests/ZendTest/Validator/File/IsImageTest.php +++ b/tests/ZendTest/Validator/File/IsImageTest.php @@ -35,39 +35,41 @@ protected function getMagicMime() } /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array(null, true), - array('jpeg', true), - array('test/notype', false), - array('image/gif, image/jpeg', true), - array(array('image/vasa', 'image/jpeg'), true), - array(array('image/jpeg', 'gif'), true), - array(array('image/gif', 'gif'), false), + $testFile = __DIR__ . '/_files/picture.jpg'; + $fileUpload = array( + 'tmp_name' => $testFile, 'name' => basename($testFile), + 'size' => 200, 'error' => 0, 'type' => 'image/jpeg' ); - - $files = array( - 'name' => 'picture.jpg', - 'type' => 'image/jpeg', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/picture.jpg', - 'error' => 0 + return array( + // Options, isValid Param, Expected value + array(null, $fileUpload, true), + array('jpeg', $fileUpload, true), + array('test/notype', $fileUpload, false), + array('image/gif, image/jpeg', $fileUpload, true), + array(array('image/vasa', 'image/jpeg'), $fileUpload, true), + array(array('image/jpeg', 'gif'), $fileUpload, true), + array(array('image/gif', 'gif'), $fileUpload, false), + array('image/jp', $fileUpload, false), + array('image/jpg2000', $fileUpload, false), + array('image/jpeg2000', $fileUpload, false), ); + } - foreach ($valuesExpected as $element) { - $validator = new File\IsImage($element[0]); - $validator->enableHeaderCheck(); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/picture.jpg', $files), - "Tested with " . var_export($element, 1) - ); - } + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected) + { + $validator = new File\IsImage($options); + $validator->enableHeaderCheck(); + $this->assertEquals($expected, $validator->isValid($isValidParam)); } /** @@ -179,6 +181,6 @@ public function testZF11258() $validator = new File\IsImage(); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileIsImageNotReadable', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/Md5Test.php b/tests/ZendTest/Validator/File/Md5Test.php index 5094cdf5d27..f8edcfdf8c1 100644 --- a/tests/ZendTest/Validator/File/Md5Test.php +++ b/tests/ZendTest/Validator/File/Md5Test.php @@ -23,63 +23,69 @@ class Md5Test extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array('ed74c22109fe9f110579f77b053b8bc3', true), - array('4d74c22109fe9f110579f77b053b8bc3', false), - array(array('4d74c22109fe9f110579f77b053b8bc3', 'ed74c22109fe9f110579f77b053b8bc3'), true), - array(array('4d74c22109fe9f110579f77b053b8bc3', '7d74c22109fe9f110579f77b053b8bc3'), false), + $testFile = __DIR__ . '/_files/picture.jpg'; + $pictureTests = array( + // Options, isValid Param, Expected value, Expected message + array( + 'ed74c22109fe9f110579f77b053b8bc3', + $testFile, true, '' + ), + array( + '4d74c22109fe9f110579f77b053b8bc3', + $testFile, false, 'fileMd5DoesNotMatch' + ), + array( + array('4d74c22109fe9f110579f77b053b8bc3', 'ed74c22109fe9f110579f77b053b8bc3'), + $testFile, true, '' + ), + array( + array('4d74c22109fe9f110579f77b053b8bc3', '7d74c22109fe9f110579f77b053b8bc3'), + $testFile, false, 'fileMd5DoesNotMatch' + ), ); - foreach ($valuesExpected as $element) { - $validator = new File\Md5($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/picture.jpg'), - "Tested with " . var_export($element, 1) - ); - } - - $validator = new File\Md5('ed74c22109fe9f110579f77b053b8bc3'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); - $this->assertTrue(array_key_exists('fileMd5NotFound', $validator->getMessages())); - - $files = array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0 + $testFile = __DIR__ . '/_files/nofile.mo'; + $noFileTests = array( + // Options, isValid Param, Expected value, message + array('ed74c22109fe9f110579f77b053b8bc3', $testFile, false, 'fileMd5NotFound'), ); - $validator = new File\Md5('ed74c22109fe9f110579f77b053b8bc3'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo', $files)); - $this->assertTrue(array_key_exists('fileMd5NotFound', $validator->getMessages())); - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\Md5('ed74c22109fe9f110579f77b053b8bc3'); - $this->assertTrue($validator->isValid(__DIR__ . '/_files/picture.jpg', $files)); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 + $testFile = __DIR__ . '/_files/testsize.mo'; + $sizeFileTests = array( + // Options, isValid Param, Expected value, message + array('ec441f84a2944405baa22873cda22370', $testFile, true, ''), + array('7d74c22109fe9f110579f77b053b8bc3', $testFile, false, 'fileMd5DoesNotMatch'), ); - $validator = new File\Md5('7d74c22109fe9f110579f77b053b8bc3'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/picture.jpg', $files)); - $this->assertTrue(array_key_exists('fileMd5DoesNotMatch', $validator->getMessages())); + + // Dupe data in File Upload format + $testData = array_merge($pictureTests, $noFileTests, $sizeFileTests); + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' + ); + $testData[] = array($data[0], $fileUpload, $data[2], $data[3]); + } + return $testData; + } + + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected, $messageKey) + { + $validator = new File\Md5($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); + if (!$expected) { + $this->assertTrue(array_key_exists($messageKey, $validator->getMessages())); + } } /** @@ -178,6 +184,6 @@ public function testZF11258() $validator = new File\Md5('12345'); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileMd5NotFound', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/MimeTypeTest.php b/tests/ZendTest/Validator/File/MimeTypeTest.php index 16dbf793286..d8b67d928bb 100644 --- a/tests/ZendTest/Validator/File/MimeTypeTest.php +++ b/tests/ZendTest/Validator/File/MimeTypeTest.php @@ -24,46 +24,41 @@ class MimeTypeTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array(array('image/jpg', 'image/jpeg'), true), - array('image', true), - array('test/notype', false), - array('image/gif, image/jpg, image/jpeg', true), - array(array('image/vasa', 'image/jpg', 'image/jpeg'), true), - array(array('image/jpg', 'image/jpeg', 'gif'), true), - array(array('image/gif', 'gif'), false), - array('image/jp', false), - array('image/jpg2000', false), - array('image/jpeg2000', false), + $testFile = __DIR__ . '/_files/picture.jpg'; + $fileUpload = array( + 'tmp_name' => $testFile, 'name' => basename($testFile), + 'size' => 200, 'error' => 0, 'type' => 'image/jpg' ); - - $filetest = __DIR__ . '/_files/picture.jpg'; - $files = array( - 'name' => 'picture.jpg', - 'type' => 'image/jpg', - 'size' => 200, - 'tmp_name' => $filetest, - 'error' => 0 + return array( + // Options, isValid Param, Expected value + array(array('image/jpg', 'image/jpeg'), $fileUpload, true), + array('image', $fileUpload, true), + array('test/notype', $fileUpload, false), + array('image/gif, image/jpg, image/jpeg', $fileUpload, true), + array(array('image/vasa', 'image/jpg', 'image/jpeg'), $fileUpload, true), + array(array('image/jpg', 'image/jpeg', 'gif'), $fileUpload, true), + array(array('image/gif', 'gif'), $fileUpload, false), + array('image/jp', $fileUpload, false), + array('image/jpg2000', $fileUpload, false), + array('image/jpeg2000', $fileUpload, false), ); + } - foreach ($valuesExpected as $element) { - $options = array_shift($element); - $expected = array_shift($element); - $validator = new File\MimeType($options); - $validator->enableHeaderCheck(); - $this->assertEquals( - $expected, - $validator->isValid($filetest, $files), - "Test expected " . var_export($expected, 1) . " with " . var_export($options, 1) - . "\nMessages: " . var_export($validator->getMessages(), 1) - ); - } + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected) + { + $validator = new File\MimeType($options); + $validator->enableHeaderCheck(); + $this->assertEquals($expected, $validator->isValid($isValidParam)); } /** @@ -167,47 +162,6 @@ public function testOptionsAtConstructor() $this->assertEquals('image/gif,image/jpg', $validator->getMimeType()); } - /** - * @group ZF-9686 - */ - public function testDualValidation() - { - $valuesExpected = array( - array('image', true), - ); - - $filetest = __DIR__ . '/_files/picture.jpg'; - $files = array( - 'name' => 'picture.jpg', - 'type' => 'image/jpg', - 'size' => 200, - 'tmp_name' => $filetest, - 'error' => 0 - ); - - foreach ($valuesExpected as $element) { - $options = array_shift($element); - $expected = array_shift($element); - $validator = new File\MimeType($options); - $validator->enableHeaderCheck(); - $this->assertEquals( - $expected, - $validator->isValid($filetest, $files), - "Test expected " . var_export($expected, 1) . " with " . var_export($options, 1) - . "\nMessages: " . var_export($validator->getMessages(), 1) - ); - - $validator = new File\MimeType($options); - $validator->enableHeaderCheck(); - $this->assertEquals( - $expected, - $validator->isValid($filetest, $files), - "Test expected " . var_export($expected, 1) . " with " . var_export($options, 1) - . "\nMessages: " . var_export($validator->getMessages(), 1) - ); - } - } - /** * @group ZF-11258 */ @@ -219,7 +173,7 @@ public function testZF11258() 'headerCheck' => true)); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileMimeTypeNotReadable', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } public function testDisableMagicFile() diff --git a/tests/ZendTest/Validator/File/NotExistsTest.php b/tests/ZendTest/Validator/File/NotExistsTest.php index 9be6d0798f2..2863f42ad10 100644 --- a/tests/ZendTest/Validator/File/NotExistsTest.php +++ b/tests/ZendTest/Validator/File/NotExistsTest.php @@ -23,86 +23,37 @@ class NotExistsTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $baseDir = __DIR__; - $valuesExpected = array( - array($baseDir, 'testsize.mo', true), - array($baseDir . '/_files', 'testsize.mo', false) - ); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 + $testFile = __DIR__ . '/_files/testsize.mo'; + $baseDir = dirname($testFile); + $baseName = basename($testFile); + $fileUpload = array( + 'tmp_name' => $testFile, 'name' => basename($testFile), + 'size' => 200, 'error' => 0, 'type' => 'text' ); - - foreach ($valuesExpected as $element) { - $validator = new File\NotExists($element[0]); - $this->assertEquals( - $element[2], - $validator->isValid($element[1]), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[2], - $validator->isValid($element[1], $files), - "Tested with " . var_export($element, 1) - ); - } - - $valuesExpected = array( - array($baseDir, 'testsize.mo', true, false), - array($baseDir . '/_files', 'testsize.mo', false, false) - ); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0, - 'destination' => __DIR__ . '/_files' - ); - - foreach ($valuesExpected as $element) { - $validator = new File\NotExists($element[0]); - $this->assertEquals( - $element[2], - $validator->isValid($element[1]), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[3], - $validator->isValid($element[1], $files), - "Tested with " . var_export($element, 1) - ); - } - - $valuesExpected = array( - array($baseDir, 'testsize.mo', false, false), - array($baseDir . '/_files', 'testsize.mo', false, false) + return array( + // Options, isValid Param, Expected value + array(dirname($baseDir), $baseName, true), + array($baseDir, $baseName, false), + array($baseDir, $testFile, false), + array(dirname($baseDir), $fileUpload, true), + array($baseDir, $fileUpload, false), ); + } - foreach ($valuesExpected as $element) { - $validator = new File\NotExists(); - $this->assertEquals( - $element[2], - $validator->isValid($element[1]), - "Tested with " . var_export($element, 1) - ); - $this->assertEquals( - $element[3], - $validator->isValid($element[1], $files), - "Tested with " . var_export($element, 1) - ); - } + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected) + { + $validator = new File\NotExists($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); } /** @@ -176,6 +127,6 @@ public function testZF11258() $validator = new File\NotExists(); $this->assertFalse($validator->isValid(__DIR__ . '/_files/testsize.mo')); $this->assertTrue(array_key_exists('fileNotExistsDoesExist', $validator->getMessages())); - $this->assertContains("'testsize.mo'", current($validator->getMessages())); + $this->assertContains("File exists", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/Sha1Test.php b/tests/ZendTest/Validator/File/Sha1Test.php index 3c7b491668e..b690d81d933 100644 --- a/tests/ZendTest/Validator/File/Sha1Test.php +++ b/tests/ZendTest/Validator/File/Sha1Test.php @@ -23,63 +23,56 @@ class Sha1Test extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array('b2a5334847b4328e7d19d9b41fd874dffa911c98', true), - array('52a5334847b4328e7d19d9b41fd874dffa911c98', false), - array(array('42a5334847b4328e7d19d9b41fd874dffa911c98', 'b2a5334847b4328e7d19d9b41fd874dffa911c98'), true), - array(array('42a5334847b4328e7d19d9b41fd874dffa911c98', '72a5334847b4328e7d19d9b41fd874dffa911c98'), false), + $testFile = __DIR__ . '/_files/picture.jpg'; + $pictureTests = array( + // Options, isValid Param, Expected value, Expected message + array('b2a5334847b4328e7d19d9b41fd874dffa911c98', $testFile, true, ''), + array('52a5334847b4328e7d19d9b41fd874dffa911c98', $testFile, false, 'fileSha1DoesNotMatch'), + array( + array('42a5334847b4328e7d19d9b41fd874dffa911c98', 'b2a5334847b4328e7d19d9b41fd874dffa911c98'), + $testFile, true, '' + ), + array( + array('42a5334847b4328e7d19d9b41fd874dffa911c98', '72a5334847b4328e7d19d9b41fd874dffa911c98'), + $testFile, false, 'fileSha1DoesNotMatch' + ), ); - foreach ($valuesExpected as $element) { - $validator = new File\Sha1($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/picture.jpg'), - "Tested with " . var_export($element, 1) + $testFile = __DIR__ . '/_files/nofile.mo'; + $noFileTests = array( + // Options, isValid Param, Expected value, message + array('b2a5334847b4328e7d19d9b41fd874dffa911c98', $testFile, false, 'fileSha1NotFound'), + ); + + // Dupe data in File Upload format + $testData = array_merge($pictureTests, $noFileTests); + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' ); + $testData[] = array($data[0], $fileUpload, $data[2], $data[3]); } + return $testData; + } - $validator = new File\Sha1('b2a5334847b4328e7d19d9b41fd874dffa911c98'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); - $this->assertTrue(array_key_exists('fileSha1NotFound', $validator->getMessages())); - - $files = array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0 - ); - $validator = new File\Sha1('b2a5334847b4328e7d19d9b41fd874dffa911c98'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo', $files)); - $this->assertTrue(array_key_exists('fileSha1NotFound', $validator->getMessages())); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\Sha1('b2a5334847b4328e7d19d9b41fd874dffa911c98'); - $this->assertTrue($validator->isValid(__DIR__ . '/_files/picture.jpg', $files)); - - $files = array( - 'name' => 'testsize.mo', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => __DIR__ . '/_files/testsize.mo', - 'error' => 0 - ); - $validator = new File\Sha1('42a5334847b4328e7d19d9b41fd874dffa911c98'); - $this->assertFalse($validator->isValid(__DIR__ . '/_files/picture.jpg', $files)); - $this->assertTrue(array_key_exists('fileSha1DoesNotMatch', $validator->getMessages())); + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected, $messageKey) + { + $validator = new File\Sha1($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); + if (!$expected) { + $this->assertTrue(array_key_exists($messageKey, $validator->getMessages())); + } } /** @@ -178,6 +171,6 @@ public function testZF11258() $validator = new File\Sha1('12345'); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileSha1NotFound', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/SizeTest.php b/tests/ZendTest/Validator/File/SizeTest.php index 0d99ed7f308..b7746c77f3a 100644 --- a/tests/ZendTest/Validator/File/SizeTest.php +++ b/tests/ZendTest/Validator/File/SizeTest.php @@ -22,34 +22,45 @@ class SizeTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array(array('min' => 0, 'max' => 10000), true), - array(array('min' => 0, 'max' => '10 MB'), true), - array(array('min' => '4B', 'max' => '10 MB'), true), - array(array('min' => 0, 'max' => '10MB'), true), - array(array('min' => 0, 'max' => '10 MB'), true), - array(794, true), - array(array('min' => 794), true), - array(array('min' => 0, 'max' => 500), false), - array(500, false), + $testFile = __DIR__ . '/_files/testsize.mo'; + $testData = array( + // Options, isValid Param, Expected value + array(794, $testFile, true), + array(500, $testFile, false), + array(array('min' => 0, 'max' => 10000), $testFile, true), + array(array('min' => 0, 'max' => '10 MB'), $testFile, true), + array(array('min' => '4B', 'max' => '10 MB'), $testFile, true), + array(array('min' => 0, 'max' => '10MB'), $testFile, true), + array(array('min' => 0, 'max' => '10 MB'), $testFile, true), + array(array('min' => 794), $testFile, true), + array(array('min' => 0, 'max' => 500), $testFile, false), ); - foreach ($valuesExpected as $element) { - $options = array_shift($element); - $value = array_shift($element); - $validator = new File\Size($options); - $this->assertEquals( - $value, - $validator->isValid(__DIR__ . '/_files/testsize.mo'), - "Tested " . var_export($value, 1) . " against options " . var_export($options, 1) + // Dupe data in File Upload format + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' ); + $testData[] = array($data[0], $fileUpload, $data[2]); } + return $testData; + } + + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected) + { + $validator = new File\Size($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); } /** @@ -180,6 +191,6 @@ public function testZF11258() $validator = new File\Size(array('min' => 1, 'max' => 10000)); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileSizeNotFound', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/UploadTest.php b/tests/ZendTest/Validator/File/UploadTest.php index 3e3123ea23d..682bf042606 100644 --- a/tests/ZendTest/Validator/File/UploadTest.php +++ b/tests/ZendTest/Validator/File/UploadTest.php @@ -20,223 +20,61 @@ */ class UploadTest extends \PHPUnit_Framework_TestCase { - /** - * Ensures that the validator follows expected behavior - * - * @return void - */ - public function testBasic() + public function uploadErrorsTestDataProvider() { - $_FILES = array( - 'test' => array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0), - 'test2' => array( - 'name' => 'test2', - 'type' => 'text2', - 'size' => 202, - 'tmp_name' => 'tmp_test2', - 'error' => 1), - 'test3' => array( - 'name' => 'test3', - 'type' => 'text3', - 'size' => 203, - 'tmp_name' => 'tmp_test3', - 'error' => 2), - 'test4' => array( - 'name' => 'test4', - 'type' => 'text4', - 'size' => 204, - 'tmp_name' => 'tmp_test4', - 'error' => 3), - 'test5' => array( - 'name' => 'test5', - 'type' => 'text5', - 'size' => 205, - 'tmp_name' => 'tmp_test5', - 'error' => 4), - 'test6' => array( - 'name' => 'test6', - 'type' => 'text6', - 'size' => 206, - 'tmp_name' => 'tmp_test6', - 'error' => 5), - 'test7' => array( - 'name' => 'test7', - 'type' => 'text7', - 'size' => 207, - 'tmp_name' => 'tmp_test7', - 'error' => 6), - 'test8' => array( - 'name' => 'test8', - 'type' => 'text8', - 'size' => 208, - 'tmp_name' => 'tmp_test8', - 'error' => 7), - 'test9' => array( - 'name' => 'test9', - 'type' => 'text9', - 'size' => 209, - 'tmp_name' => 'tmp_test9', - 'error' => 8) + $data = array(); + $errorTypes = array( + 0 => 'fileUploadErrorAttack', + 1 => 'fileUploadErrorIniSize', + 2 => 'fileUploadErrorFormSize', + 3 => 'fileUploadErrorPartial', + 4 => 'fileUploadErrorNoFile', + 5 => 'fileUploadErrorUnknown', + 6 => 'fileUploadErrorNoTmpDir', + 7 => 'fileUploadErrorCantWrite', + 8 => 'fileUploadErrorExtension', + 9 => 'fileUploadErrorUnknown', ); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test')); - $this->assertTrue(array_key_exists('fileUploadErrorAttack', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test2')); - $this->assertTrue(array_key_exists('fileUploadErrorIniSize', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test3')); - $this->assertTrue(array_key_exists('fileUploadErrorFormSize', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test4')); - $this->assertTrue(array_key_exists('fileUploadErrorPartial', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test5')); - $this->assertTrue(array_key_exists('fileUploadErrorNoFile', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test6')); - $this->assertTrue(array_key_exists('fileUploadErrorUnknown', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test7')); - $this->assertTrue(array_key_exists('fileUploadErrorNoTmpDir', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test8')); - $this->assertTrue(array_key_exists('fileUploadErrorCantWrite', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test9')); - $this->assertTrue(array_key_exists('fileUploadErrorExtension', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test1')); - $this->assertTrue(array_key_exists('fileUploadErrorAttack', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('tmp_test1')); - $this->assertTrue(array_key_exists('fileUploadErrorAttack', $validator->getMessages())); - - $validator = new File\Upload(); - $this->assertFalse($validator->isValid('test000')); - $this->assertTrue(array_key_exists('fileUploadErrorFileNotFound', $validator->getMessages())); + $testSizeFile = __DIR__ . '/_files/testsize.mo'; + + foreach ($errorTypes as $errorCode => $errorType) { + $data[] = array( + // fileInfo + array( + 'name' => 'test' . $errorCode, + 'type' => 'text', + 'size' => 200 + $errorCode, + 'tmp_name' => $testSizeFile, + 'error' => $errorCode, + ), + // messageKey + $errorType, + ); + } + return $data; } /** - * Ensures that getFiles() returns expected value + * Ensures that the validator follows expected behavior * + * @dataProvider uploadErrorsTestDataProvider * @return void */ - public function testGetFiles() + public function testBasic($fileInfo, $messageKey) { - $_FILES = array( - 'test' => array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0), - 'test2' => array( - 'name' => 'test3', - 'type' => 'text2', - 'size' => 202, - 'tmp_name' => 'tmp_test2', - 'error' => 1)); - - $files = array( - 'test' => array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0)); - - $files1 = array( - 'test2' => array( - 'name' => 'test3', - 'type' => 'text2', - 'size' => 202, - 'tmp_name' => 'tmp_test2', - 'error' => 1)); - $validator = new File\Upload(); - $this->assertEquals($files, $validator->getFiles('test')); - $this->assertEquals($files, $validator->getFiles('test1')); - $this->assertEquals($files1, $validator->getFiles('test3')); - - $this->setExpectedException('Zend\Validator\Exception\InvalidArgumentException', 'was not found'); - $this->assertEquals(array(), $validator->getFiles('test5')); + $this->assertFalse($validator->isValid($fileInfo)); + $this->assertTrue(array_key_exists($messageKey, $validator->getMessages())); } /** - * Ensures that setFiles() returns expected value - * * @return void */ - public function testSetFiles() - { - $files = array( - 'test' => array( - 'name' => 'test1', - 'type' => 'text', - 'size' => 200, - 'tmp_name' => 'tmp_test1', - 'error' => 0), - 'test2' => array( - 'name' => 'test2', - 'type' => 'text2', - 'size' => 202, - 'tmp_name' => 'tmp_test2', - 'error' => 1)); - - $_FILES = array( - 'test' => array( - 'name' => 'test3', - 'type' => 'text3', - 'size' => 203, - 'tmp_name' => 'tmp_test3', - 'error' => 2)); - - - $validator = new File\Upload(); - $validator->setFiles(array()); - $this->assertEquals($_FILES, $validator->getFiles()); - $validator->setFiles(); - $this->assertEquals($_FILES, $validator->getFiles()); - $validator->setFiles($files); - $this->assertEquals($files, $validator->getFiles()); - } - - /** - * @group ZF-10738 - */ - public function testGetFilesReturnsEmptyArrayWhenFilesSuperglobalIsNull() - { - $_FILES = NULL; - $validator = new File\Upload(); - $validator->setFiles(); - $this->assertEquals(array(), $validator->getFiles()); - } - - /** - * @group ZF-10738 - */ - public function testGetFilesReturnsEmptyArrayAfterSetFilesIsCalledWithNull() + public function testRaisesExceptionWhenValueArrayIsBad() { $validator = new File\Upload(); - $validator->setFiles(NULL); - $this->assertEquals(array(), $validator->getFiles()); + $this->setExpectedException('Zend\Validator\Exception\InvalidArgumentException', '$_FILES format'); + $validator->isValid(array('foo', 'bar')); } /** @@ -247,6 +85,6 @@ public function testZF11258() $validator = new File\Upload(); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileUploadErrorFileNotFound', $validator->getMessages())); - $this->assertContains("nofile.mo'", current($validator->getMessages())); + $this->assertContains("not found", current($validator->getMessages())); } } diff --git a/tests/ZendTest/Validator/File/WordCountTest.php b/tests/ZendTest/Validator/File/WordCountTest.php index 35ba84b065d..8fc4b2b6a9c 100644 --- a/tests/ZendTest/Validator/File/WordCountTest.php +++ b/tests/ZendTest/Validator/File/WordCountTest.php @@ -22,27 +22,40 @@ class WordCountTest extends \PHPUnit_Framework_TestCase { /** - * Ensures that the validator follows expected behavior - * - * @return void + * @return array */ - public function testBasic() + public function basicBehaviorDataProvider() { - $valuesExpected = array( - array(15, true), - array(4, false), - array(array('min' => 0, 'max' => 10), true), - array(array('min' => 10, 'max' => 15), false), - ); + $testFile = __DIR__ . '/_files/wordcount.txt'; + $testData = array( + // Options, isValid Param, Expected value + array(15, $testFile, true), + array(4, $testFile, false), + array(array('min' => 0, 'max' => 10), $testFile, true), + array(array('min' => 10, 'max' => 15), $testFile, false), + ); - foreach ($valuesExpected as $element) { - $validator = new File\WordCount($element[0]); - $this->assertEquals( - $element[1], - $validator->isValid(__DIR__ . '/_files/wordcount.txt'), - "Tested with " . var_export($element, 1) + // Dupe data in File Upload format + foreach ($testData as $data) { + $fileUpload = array( + 'tmp_name' => $data[1], 'name' => basename($data[1]), + 'size' => 200, 'error' => 0, 'type' => 'text' ); + $testData[] = array($data[0], $fileUpload, $data[2]); } + return $testData; + } + + /** + * Ensures that the validator follows expected behavior + * + * @dataProvider basicBehaviorDataProvider + * @return void + */ + public function testBasic($options, $isValidParam, $expected) + { + $validator = new File\WordCount($options); + $this->assertEquals($expected, $validator->isValid($isValidParam)); } /** @@ -111,6 +124,6 @@ public function testZF11258() $validator = new File\WordCount(array('min' => 1, 'max' => 10000)); $this->assertFalse($validator->isValid(__DIR__ . '/_files/nofile.mo')); $this->assertTrue(array_key_exists('fileWordCountNotFound', $validator->getMessages())); - $this->assertContains("'nofile.mo'", current($validator->getMessages())); + $this->assertContains("does not exist", current($validator->getMessages())); } }