name) { if (isset($options['oldValue']) && $options['oldValue']) { $this->_removeOldImage($options['oldValue']); } $data = array( 'nodeId' => $options['nodeId'], 'imageId' => null, 'name' => $file->name, 'filenameOriginal' => $file->name, 'filenameFs' => $this->_prepareFileName($file->name), 'display' => 'y', 'sorter' => null ); $filename = Yii::getAlias(ThumbGenerator::FS_FILE_ALIAS) . '/' . $data['filenameFs']; $this->_fileModel->setAttributes($data, false); $this->_fileModel->file = $file; if ($this->_fileModel->validate()) { $this->_fileModel->save(false); $this->_imageId = $this->_fileModel->getAttribute('imageId'); parent::saveAs($filename, $deleteTempFile); $this->_resize($filename, $options); return $this->_fileModel->getAttribute('imageId'); } else { foreach ($this->_fileModel->getErrors() as $msg) { $this->addError($msg); } } } else { $this->addError('Wrong filename'); } return null; } protected function _removeOldImage($file) { $this->_fileModel = new Image(); $this->_fileModel->deleteByFsName($file); return true; } protected function _resize($filename, $options) { if (isset($options['image']['width']) && isset($options['image']['height'])) { $thumb = new ThumbGenerator(); if (isset($options['image']['crop']) && $options['image']['crop'] == 'inner') { $thumb->adaptiveResize($filename, $filename, $options['image']); } else if (isset($options['image']['crop']) && $options['image']['crop'] == 'cropCenter') { $thumb->cropFromCenter($filename, $filename, $options['image']); } else { $thumb->resize($filename, $filename, $options['image']); } } return $this; } protected function _prepareFileName($filename) { if ($this->_nameFs === null) { $this->_fileModel = new Image(); /*$query = $this->_fileModel->createQuery()->where('name LIKE ' . yii::$app->db->quoteValue($filename)); $names = ArrayHelper::getColumn($query->createCommand()->queryAll(), 'filenameFs');*/ $names = ArrayHelper::getColumn($this->_fileModel->find()->where(['LIKE','name', $filename])->asArray()->all(), 'filenameFs'); if (empty($names)) { $index = 1; } else { sort($names, SORT_NATURAL); $nameForIndex = $names[count($names) - 1]; $startPosition = strrpos($nameForIndex, '(') + 1; $nameForIndex = $names[count($names) - 1]; $endPosition = strrpos($nameForIndex, ')') + 1; $index = intval(substr($nameForIndex, $startPosition, $endPosition - $startPosition - 1)) + 1; } $fileParts = pathinfo($filename); $this->_nameFs = $fileParts['filename'] . '(' . $index . ').' . $fileParts['extension']; } return $this->_nameFs; } /** * @return string */ public function getNameFs() { return $this->_nameFs; } public function getErrors() { return $this->_errors === null ? [] : $this->_errors; } public function addError($error = '') { $this->_errors[] = $error; } public function clearErrors() { $this->_errors = []; } }