<?php
namespace Moto\Application\FileManager\Filter; use Moto\Filter\AbstractFilter; use Zend\Filter\Exception; class GenerateUniqueName extends AbstractFilter { protected $_options = array( 'suffix' => '-', 'maxLength' => 300 ); function __construct($options = array()) { parent::setOptions($options); } public function filter($value) { if (!is_string($value) || is_dir($value) || !is_writable($value) || !file_exists($value)) { return $value; } list( $dirname, $basename, $extension, $filename ) = array_values(pathinfo($value)); $extLength = strlen($extension); $isUnique = false; $index = 2; $getMaxLength = function($maxLength, $suffix, $index, $extLength) { return $maxLength - strlen($suffix) - strlen($index) - $extLength; }; $suffix = $this->getOption('suffix'); $maxLength = $getMaxLength($this->getOption('maxLength'), $suffix, $index, $extLength); $filename = trim($filename, $suffix); if (strlen($filename) > $maxLength) { $filename = trim(substr($filename, 0, $maxLength), $suffix); } while (!$isUnique) { $name = $filename . $suffix . $index; if (strlen($name) > $this->getOption('maxLength') - $extLength) { $maxLength = $getMaxLength($this->getOption('maxLength'), $suffix, $index, $extLength); $name = substr($name, 0, $maxLength) . $suffix . $index; } $value = $dirname . '/' . $name . '.' . $extension; $isUnique = !file_exists($value); $index++; if ($index > 500) { throw new \OverflowException('Stack overflow', 400); } } return $value; } public function setSuffix($suffix) { if (is_string($suffix) && strlen($suffix) < 4) { $this->_options['suffix'] = $suffix; } } public function setMaxLength($maxLength) { if (is_numeric($maxLength) && $maxLength > 6) { $this->_options['maxLength'] = $maxLength; } } }