/app/Widget/FileUpload5/FileUpload.php
PHP | 327 lines | 210 code | 36 blank | 81 comment | 81 complexity | a483648424210e41e1b689a9ac90fe8a MD5 | raw file
- <?php
- namespace cs\Widget\FileUpload5;
- use cs\services\File;
- use cs\services\SitePath;
- use Imagine\Image\Box;
- use Yii;
- use yii\base\InvalidConfigException;
- use yii\helpers\ArrayHelper;
- use yii\helpers\Url;
- use yii\helpers\Html;
- use yii\helpers\Json;
- use yii\helpers\VarDumper;
- use yii\widgets\InputWidget;
- use yii\web\UploadedFile;
- use yii\imagine\Image;
- use Imagine\Image\ManipulatorInterface;
- use cs\base\BaseForm;
- use cs\services\UploadFolderDispatcher;
- /**
- * Не понял зачем сделал но пока оставлю
- * Виджет который загружает файл по указанному с компьютера или указзаному по ссылке
- * Если указаны оба то приоритет отдается указанному с компьютера.
- *
- * поведение и содержание значения поля $model->$attribute
- * после ::load() происходит загрузка
- * [
- * 'value' => название файла в файловой системе, если был загружен файл
- * 'url' => url к файлу, если был указан url
- * 'file' => \yii\web\UploadedFile
- * ]
- * после ::loadDb() происходит загрузка
- * [
- * 'value' => путь к файлу
- * 'url' => null
- * 'file' => null
- * ]
- * https://drive.google.com/file/d/0BzHYNoEyPNTXdEVyR2NqZkRJR2c/view?usp=sharing
- *
- */
- class FileUpload extends InputWidget
- {
- /**
- * @var array опции виджета
- */
- public $options;
- private $fieldIdName;
- private $actionIdName;
- private $actionNameAttribute;
- private $isDeleteNameAttribute;
- private $isDeleteIdName;
- private $valueNameAttribute;
- private $valueIdName;
- private $attrId;
- private $attrName;
- public $widgetOptions;
- public $isExpandSmall = true;
- public $value = [
- 'file' => null,
- 'url' => '',
- 'db' => '',
- ];
- /**
- * Initializes the widget.
- */
- public function init()
- {
- parent::init();
- $this->attrName = $this->model->formName() . '[' . $this->attribute . ']';
- $this->attrId = strtolower($this->model->formName() . '-' . $this->attribute);
- $this->valueNameAttribute = $this->model->formName() . '[' . $this->attribute . '-value' . ']';
- $this->valueIdName = strtolower($this->model->formName() . '-' . $this->attribute) . '-value';
- $this->actionNameAttribute = $this->model->formName() . '[' . $this->attribute . '-action' . ']';
- $this->actionIdName = strtolower($this->model->formName() . '-' . $this->attribute) . '-action';
- $this->fieldIdName = strtolower($this->model->formName() . '-' . $this->attribute);
- $this->isDeleteNameAttribute = $this->model->formName() . '[' . $this->attribute . '-is-delete' . ']';
- $this->isDeleteIdName = strtolower($this->model->formName() . '-' . $this->attribute) . '-is-delete';
- }
- /**
- * Renders the widget.
- */
- public function run()
- {
- $this->registerClientScript();
- if ($this->hasModel()) {
- $fieldName = $this->attribute;
- $value = $this->model->$fieldName;
- return $this->render('@csRoot/Widget/FileUpload5/template', [
- 'value' => $value,
- 'attribute' => $this->attribute,
- 'formName' => $this->model->formName(),
- 'model' => $this->model,
- 'attrId' => $this->attrId,
- 'attrName' => $this->attrName,
- 'widgetOptions' => $this->widgetOptions,
- ]);
- }
- }
- /**
- * Registers the needed JavaScript.
- */
- public function registerClientScript()
- {
- $this->getView()->registerJs("FileUpload3.init('#{$this->attrId}');");
- Asset::register($this->getView());
- }
- /**
- * Returns the options for the captcha JS widget.
- *
- * @return array the options
- */
- protected function getClientOptions()
- {
- return [];
- }
- /**
- * @param array $field
- * @param \yii\base\Model $model
- *
- * @return bool
- */
- public static function onDelete($field, $model)
- {
- $fieldName = $field[BaseForm::POS_DB_NAME];
- $value = $model->$fieldName;
- $value = $value['value'];
- if (!is_null($value)) {
- if ($value != '') {
- (new SitePath($value))->deleteFile();
- (new SitePath(self::getOriginalLocal($value)))->deleteFile();
- }
- }
- return true;
- }
- /**
- * @param array $field
- * @param \yii\base\Model $model
- *
- * @return bool
- */
- public static function onLoad($field, $model)
- {
- $fieldName = $field[BaseForm::POS_DB_NAME];
- $modelName = $model->formName();
- $valueUrl = ArrayHelper::getValue(Yii::$app->request->post(), $modelName . '.' . $fieldName . '-url', '');
- $value = ArrayHelper::getValue(Yii::$app->request->post(), $modelName . '.' . $fieldName . '-value', '');
- $isDelete = ArrayHelper::getValue(Yii::$app->request->post(), $modelName . '.' . $fieldName . '-is_delete', 0);
- $model->$fieldName = [
- 'url' => $valueUrl,
- 'file' => UploadedFile::getInstance($model, $fieldName),
- 'value' => $value,
- 'isDelete' => $isDelete,
- ];
- return true;
- }
- /**
- * @param array $field
- * @param \cs\base\BaseForm $model
- *
- * @return bool
- */
- public static function onLoadDb($field, $model)
- {
- $fieldName = $field[BaseForm::POS_DB_NAME];
- $row = $model->getRow();
- $model->$fieldName = [
- 'url' => '',
- 'file' => null,
- 'value' => $row[$fieldName],
- ];
- return true;
- }
- /**
- * @param array $field
- * @param \cs\base\BaseForm $model
- *
- * @return array поля для обновления в БД
- */
- public static function onUpdate($field, $model)
- {
- $fieldName = $field[BaseForm::POS_DB_NAME];
- $v = $model->$fieldName;
- $isDelete = false;
- $hasFile = false;
- $hasUrl = false;
- if ($v['isDelete'] == 1) {
- $isDelete = true;
- }
- $fileModel = $v['file'];
- if (!is_null($fileModel)) {
- if ($fileModel->error == 0) $hasFile = true;
- }
- if ($v['url'] != '') {
- $hasUrl = true;
- }
- $choose = '';
- if ($isDelete == false && $hasUrl == false && $hasFile == true) {
- $choose = 'file';
- }
- if ($isDelete == false && $hasUrl == true && $hasFile == false) {
- $choose = 'url';
- }
- if ($isDelete == false && $hasUrl == true && $hasFile == true) {
- $choose = 'file';
- }
- if ($isDelete == true && $hasUrl == false && $hasFile == false) {
- $choose = 'delete';
- }
- if ($isDelete == true && $hasUrl == false && $hasFile == true) {
- $choose = 'file';
- }
- if ($isDelete == true && $hasUrl == true && $hasFile == false) {
- $choose = 'url';
- }
- if ($isDelete == true && $hasUrl == true && $hasFile == true) {
- $choose = 'file';
- }
- if ($isDelete == false && $hasUrl == false && $hasFile == true) {
- $choose = 'file';
- }
- if ($isDelete == false && $hasUrl == true && $hasFile == false) {
- $choose = 'url';
- }
- if ($isDelete == false && $hasUrl == true && $hasFile == true) {
- $choose = 'file';
- }
- if ($choose == 'delete') {
- $row = $model->getRow();
- $dbValue = ArrayHelper::getValue($row, $fieldName, '');
- if ($dbValue != '') {
- // удалить старые файлы
- $f = new SitePath($dbValue);
- $f->deleteFile();
- }
- return [
- $fieldName => '',
- ];
- }
- if ($choose == 'url') {
- try {
- $data = file_get_contents($v['url']);
- } catch (\Exception $e) {
- $data = '';
- }
- if ($data == '') return [];
- $file = File::content($data);
- $url = new \cs\services\Url($v['url']);
- $extension = $url->getExtension('torrent');
- return self::save($file, $extension, $field, $model);
- }
- if ($choose == 'file') {
- $file = File::path($fileModel->tempName);
- $extension = $fileModel->extension;
- return self::save($file, $extension, $field, $model);
- }
- return [];
- }
- /**
- * Сохраняет файл
- *
- * @param \cs\services\File $file
- * @param string $extension
- * @param array $field
- * @param \cs\base\BaseForm $model
- *
- * @return array
- */
- public static function save($file, $extension, $field, $model)
- {
- $fieldName = $field[BaseForm::POS_DB_NAME];
- $path = self::getFolderPath($field, $model);
- $fileName = $fieldName . '.' . $extension;
- $path->add($fileName)->deleteFile();
- $file->save($path->getPathFull());
- return [
- $fieldName => $path->getPath()
- ];
- }
- /**
- * Создает папку для загрузки
- *
- * @param array $field
- * @param \cs\base\BaseForm $model
- *
- * @return \cs\services\SitePath
- */
- protected static function getFolderPath($field, $model)
- {
- $folder = ArrayHelper::getValue($field, 'type.1.folder', $model->getTableName());
- return UploadFolderDispatcher::createFolder('FileUpload5', $folder, $model->id);
- }
- }