<?php
namespace Moto\Application\Util\UniqueDuplicator; use Moto\Validator\Db\NoRecordExists; use Zend\Db\Sql\Select; use Moto; class Db extends AbstractUniqueDuplicator { protected $_adapter; protected $_table; protected $_field; protected $_select; protected $_where; public function __construct(array $options = array()) { parent::__construct($options); if (empty($this->_adapter)) { $this->setAdapter(); } } public function setAdapter($adapter = null) { $this->_adapter = empty($adapter) ? Moto\Config::get('databaseAdapter') : $adapter; return $this; } public function setTable($table) { $this->_table = $table; return $this; } public function setField($field) { $this->_field = $field; return $this; } public function setWhere($where) { $this->_where = $where; return $this; } public function setSelect(Select $select) { $this->_select = $select; return $this; } public function getSelect() { return $this->_select; } public function generate($value) { if (!is_string($value)) { return $value; } $isUnique = false; $name = $value; $index = $this->_startIndex; $getMaxLength = function($maxLength, $suffix, $index) { return $maxLength - strlen($suffix) - strlen($index); }; $suffix = $this->_suffix; $maxLength = $getMaxLength($this->_maxLength, $suffix, $index); $value = trim($value, $suffix); if (strlen($value) > $maxLength) { $value = trim(substr($value, 0, $maxLength), $suffix); } $params = $this->getSelect(); if (!($params instanceof Select)) { $params = array( 'table' => $this->_table, 'field' => $this->_field, 'adapter' => $this->_adapter, 'where' => $this->_where ); } $notExistsValidator = new NoRecordExists($params); $notExistsValidator->setAdapter($this->_adapter); while (!$isUnique) { $name = $value . $suffix . $index; if (strlen($name) > $this->_maxLength) { $maxLength = $getMaxLength($this->_maxLength, $suffix, $index); $name = substr($name, 0, $maxLength) . $suffix . $index; } $isUnique = $notExistsValidator->isValid($name); $this->_lastIndex = $index; $index++; if ($index > 500) { throw new \OverflowException('Stack overflow', 400); } } return $name; } }