PageRenderTime 66ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/app/Widget/FileUpload5/FileUpload.php

https://gitlab.com/dram1008/galaxysss
PHP | 327 lines | 210 code | 36 blank | 81 comment | 81 complexity | a483648424210e41e1b689a9ac90fe8a MD5 | raw file
  1. <?php
  2. namespace cs\Widget\FileUpload5;
  3. use cs\services\File;
  4. use cs\services\SitePath;
  5. use Imagine\Image\Box;
  6. use Yii;
  7. use yii\base\InvalidConfigException;
  8. use yii\helpers\ArrayHelper;
  9. use yii\helpers\Url;
  10. use yii\helpers\Html;
  11. use yii\helpers\Json;
  12. use yii\helpers\VarDumper;
  13. use yii\widgets\InputWidget;
  14. use yii\web\UploadedFile;
  15. use yii\imagine\Image;
  16. use Imagine\Image\ManipulatorInterface;
  17. use cs\base\BaseForm;
  18. use cs\services\UploadFolderDispatcher;
  19. /**
  20. * Не понял зачем сделал но пока оставлю
  21. * Виджет который загружает файл по указанному с компьютера или указзаному по ссылке
  22. * Если указаны оба то приоритет отдается указанному с компьютера.
  23. *
  24. * поведение и содержание значения поля $model->$attribute
  25. * после ::load() происходит загрузка
  26. * [
  27. * 'value' => название файла в файловой системе, если был загружен файл
  28. * 'url' => url к файлу, если был указан url
  29. * 'file' => \yii\web\UploadedFile
  30. * ]
  31. * после ::loadDb() происходит загрузка
  32. * [
  33. * 'value' => путь к файлу
  34. * 'url' => null
  35. * 'file' => null
  36. * ]
  37. * https://drive.google.com/file/d/0BzHYNoEyPNTXdEVyR2NqZkRJR2c/view?usp=sharing
  38. *
  39. */
  40. class FileUpload extends InputWidget
  41. {
  42. /**
  43. * @var array опции виджета
  44. */
  45. public $options;
  46. private $fieldIdName;
  47. private $actionIdName;
  48. private $actionNameAttribute;
  49. private $isDeleteNameAttribute;
  50. private $isDeleteIdName;
  51. private $valueNameAttribute;
  52. private $valueIdName;
  53. private $attrId;
  54. private $attrName;
  55. public $widgetOptions;
  56. public $isExpandSmall = true;
  57. public $value = [
  58. 'file' => null,
  59. 'url' => '',
  60. 'db' => '',
  61. ];
  62. /**
  63. * Initializes the widget.
  64. */
  65. public function init()
  66. {
  67. parent::init();
  68. $this->attrName = $this->model->formName() . '[' . $this->attribute . ']';
  69. $this->attrId = strtolower($this->model->formName() . '-' . $this->attribute);
  70. $this->valueNameAttribute = $this->model->formName() . '[' . $this->attribute . '-value' . ']';
  71. $this->valueIdName = strtolower($this->model->formName() . '-' . $this->attribute) . '-value';
  72. $this->actionNameAttribute = $this->model->formName() . '[' . $this->attribute . '-action' . ']';
  73. $this->actionIdName = strtolower($this->model->formName() . '-' . $this->attribute) . '-action';
  74. $this->fieldIdName = strtolower($this->model->formName() . '-' . $this->attribute);
  75. $this->isDeleteNameAttribute = $this->model->formName() . '[' . $this->attribute . '-is-delete' . ']';
  76. $this->isDeleteIdName = strtolower($this->model->formName() . '-' . $this->attribute) . '-is-delete';
  77. }
  78. /**
  79. * Renders the widget.
  80. */
  81. public function run()
  82. {
  83. $this->registerClientScript();
  84. if ($this->hasModel()) {
  85. $fieldName = $this->attribute;
  86. $value = $this->model->$fieldName;
  87. return $this->render('@csRoot/Widget/FileUpload5/template', [
  88. 'value' => $value,
  89. 'attribute' => $this->attribute,
  90. 'formName' => $this->model->formName(),
  91. 'model' => $this->model,
  92. 'attrId' => $this->attrId,
  93. 'attrName' => $this->attrName,
  94. 'widgetOptions' => $this->widgetOptions,
  95. ]);
  96. }
  97. }
  98. /**
  99. * Registers the needed JavaScript.
  100. */
  101. public function registerClientScript()
  102. {
  103. $this->getView()->registerJs("FileUpload3.init('#{$this->attrId}');");
  104. Asset::register($this->getView());
  105. }
  106. /**
  107. * Returns the options for the captcha JS widget.
  108. *
  109. * @return array the options
  110. */
  111. protected function getClientOptions()
  112. {
  113. return [];
  114. }
  115. /**
  116. * @param array $field
  117. * @param \yii\base\Model $model
  118. *
  119. * @return bool
  120. */
  121. public static function onDelete($field, $model)
  122. {
  123. $fieldName = $field[BaseForm::POS_DB_NAME];
  124. $value = $model->$fieldName;
  125. $value = $value['value'];
  126. if (!is_null($value)) {
  127. if ($value != '') {
  128. (new SitePath($value))->deleteFile();
  129. (new SitePath(self::getOriginalLocal($value)))->deleteFile();
  130. }
  131. }
  132. return true;
  133. }
  134. /**
  135. * @param array $field
  136. * @param \yii\base\Model $model
  137. *
  138. * @return bool
  139. */
  140. public static function onLoad($field, $model)
  141. {
  142. $fieldName = $field[BaseForm::POS_DB_NAME];
  143. $modelName = $model->formName();
  144. $valueUrl = ArrayHelper::getValue(Yii::$app->request->post(), $modelName . '.' . $fieldName . '-url', '');
  145. $value = ArrayHelper::getValue(Yii::$app->request->post(), $modelName . '.' . $fieldName . '-value', '');
  146. $isDelete = ArrayHelper::getValue(Yii::$app->request->post(), $modelName . '.' . $fieldName . '-is_delete', 0);
  147. $model->$fieldName = [
  148. 'url' => $valueUrl,
  149. 'file' => UploadedFile::getInstance($model, $fieldName),
  150. 'value' => $value,
  151. 'isDelete' => $isDelete,
  152. ];
  153. return true;
  154. }
  155. /**
  156. * @param array $field
  157. * @param \cs\base\BaseForm $model
  158. *
  159. * @return bool
  160. */
  161. public static function onLoadDb($field, $model)
  162. {
  163. $fieldName = $field[BaseForm::POS_DB_NAME];
  164. $row = $model->getRow();
  165. $model->$fieldName = [
  166. 'url' => '',
  167. 'file' => null,
  168. 'value' => $row[$fieldName],
  169. ];
  170. return true;
  171. }
  172. /**
  173. * @param array $field
  174. * @param \cs\base\BaseForm $model
  175. *
  176. * @return array поля для обновления в БД
  177. */
  178. public static function onUpdate($field, $model)
  179. {
  180. $fieldName = $field[BaseForm::POS_DB_NAME];
  181. $v = $model->$fieldName;
  182. $isDelete = false;
  183. $hasFile = false;
  184. $hasUrl = false;
  185. if ($v['isDelete'] == 1) {
  186. $isDelete = true;
  187. }
  188. $fileModel = $v['file'];
  189. if (!is_null($fileModel)) {
  190. if ($fileModel->error == 0) $hasFile = true;
  191. }
  192. if ($v['url'] != '') {
  193. $hasUrl = true;
  194. }
  195. $choose = '';
  196. if ($isDelete == false && $hasUrl == false && $hasFile == true) {
  197. $choose = 'file';
  198. }
  199. if ($isDelete == false && $hasUrl == true && $hasFile == false) {
  200. $choose = 'url';
  201. }
  202. if ($isDelete == false && $hasUrl == true && $hasFile == true) {
  203. $choose = 'file';
  204. }
  205. if ($isDelete == true && $hasUrl == false && $hasFile == false) {
  206. $choose = 'delete';
  207. }
  208. if ($isDelete == true && $hasUrl == false && $hasFile == true) {
  209. $choose = 'file';
  210. }
  211. if ($isDelete == true && $hasUrl == true && $hasFile == false) {
  212. $choose = 'url';
  213. }
  214. if ($isDelete == true && $hasUrl == true && $hasFile == true) {
  215. $choose = 'file';
  216. }
  217. if ($isDelete == false && $hasUrl == false && $hasFile == true) {
  218. $choose = 'file';
  219. }
  220. if ($isDelete == false && $hasUrl == true && $hasFile == false) {
  221. $choose = 'url';
  222. }
  223. if ($isDelete == false && $hasUrl == true && $hasFile == true) {
  224. $choose = 'file';
  225. }
  226. if ($choose == 'delete') {
  227. $row = $model->getRow();
  228. $dbValue = ArrayHelper::getValue($row, $fieldName, '');
  229. if ($dbValue != '') {
  230. // удалить старые файлы
  231. $f = new SitePath($dbValue);
  232. $f->deleteFile();
  233. }
  234. return [
  235. $fieldName => '',
  236. ];
  237. }
  238. if ($choose == 'url') {
  239. try {
  240. $data = file_get_contents($v['url']);
  241. } catch (\Exception $e) {
  242. $data = '';
  243. }
  244. if ($data == '') return [];
  245. $file = File::content($data);
  246. $url = new \cs\services\Url($v['url']);
  247. $extension = $url->getExtension('torrent');
  248. return self::save($file, $extension, $field, $model);
  249. }
  250. if ($choose == 'file') {
  251. $file = File::path($fileModel->tempName);
  252. $extension = $fileModel->extension;
  253. return self::save($file, $extension, $field, $model);
  254. }
  255. return [];
  256. }
  257. /**
  258. * Сохраняет файл
  259. *
  260. * @param \cs\services\File $file
  261. * @param string $extension
  262. * @param array $field
  263. * @param \cs\base\BaseForm $model
  264. *
  265. * @return array
  266. */
  267. public static function save($file, $extension, $field, $model)
  268. {
  269. $fieldName = $field[BaseForm::POS_DB_NAME];
  270. $path = self::getFolderPath($field, $model);
  271. $fileName = $fieldName . '.' . $extension;
  272. $path->add($fileName)->deleteFile();
  273. $file->save($path->getPathFull());
  274. return [
  275. $fieldName => $path->getPath()
  276. ];
  277. }
  278. /**
  279. * Создает папку для загрузки
  280. *
  281. * @param array $field
  282. * @param \cs\base\BaseForm $model
  283. *
  284. * @return \cs\services\SitePath
  285. */
  286. protected static function getFolderPath($field, $model)
  287. {
  288. $folder = ArrayHelper::getValue($field, 'type.1.folder', $model->getTableName());
  289. return UploadFolderDispatcher::createFolder('FileUpload5', $folder, $model->id);
  290. }
  291. }