<?php
namespace Moto\Application\Util\UniqueDuplicator; class File extends AbstractUniqueDuplicator { protected $_path = ''; protected $_suffix = '-'; public function setPath($value = '') { if (is_dir($value) && is_readable($value)) { if (substr($value, -1) != DIRECTORY_SEPARATOR) { $value .= DIRECTORY_SEPARATOR; } $this->_path = $value; } else { throw new \InvalidArgumentException(__CLASS__ . ' - ' . __METHOD__ . ' :: Path not exists'); } return $this; } public function generate($value) { if (empty($this->_path)) { $this->setPath(); } if (!is_string($value)) { return $value; } $extension = pathinfo($value, PATHINFO_EXTENSION); $filename = pathinfo($value, PATHINFO_FILENAME); $extLength = strlen($extension) + (empty($extension) ? 0 : 1); $isUnique = false; $name = $value; $index = $this->_startIndex; $getMaxLength = function($maxLength, $suffix, $index, $extLength) { return $maxLength - strlen($suffix) - strlen($index) - $extLength; }; $suffix = $this->_suffix; $maxLength = $getMaxLength($this->_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->_maxLength - $extLength) { $maxLength = $getMaxLength($this->_maxLength, $suffix, $index, $extLength); $name = substr($name, 0, $maxLength) . $suffix . $index; } $name .= empty($extension) ? '' : '.' . $extension; $value = $this->_path . $name; $isUnique = !file_exists($value); $this->_lastIndex = $index; $index++; if ($index > 500) { throw new \OverflowException('Stack overflow', 400); } } return $name; } public function setMaxLength($maxLength) { if (is_numeric($maxLength) && $maxLength > 6) { $this->_maxLength = $maxLength; } return $this; } public function setSuffix($suffix) { $suffix = str_replace(' ', '-', $suffix); if (is_string($suffix) && strlen($suffix) < 4) { $this->_suffix = $suffix; } return $this; } } 