Util.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-12-27 14:53
  7. */
  8. namespace common\helpers;
  9. use Yii;
  10. use yii\base\Exception;
  11. use yii\imagine\Image;
  12. use yii\db\ActiveRecord;
  13. use yii\helpers\FileHelper;
  14. use yii\web\UploadedFile;
  15. class Util
  16. {
  17. /**
  18. * 处理单模型单文件上传
  19. *
  20. * @param ActiveRecord $model
  21. * @param $field
  22. * @param $insert
  23. * @param $uploadPath
  24. * @param array $options
  25. * $options[thumbSizes] array 需要截图的尺寸,如[['w'=>100,'h'=>100]]
  26. * $options['filename'] string 新文件名,默认自动生成
  27. * @return bool
  28. * @throws \yii\base\Exception
  29. */
  30. public static function handleModelSingleFileUpload(ActiveRecord &$model, $field, $insert, $uploadPath, $options=[])
  31. {
  32. $upload = UploadedFile::getInstance($model, $field);
  33. /* @var $cdn \feehi\cdn\TargetInterface */
  34. $cdn = Yii::$app->get('cdn');
  35. if ($upload !== null) {
  36. $uploadPath = Yii::getAlias($uploadPath);
  37. if( strpos(strrev($uploadPath), '/') !== 0 ) $uploadPath .= '/';
  38. if (! FileHelper::createDirectory($uploadPath)) {
  39. $model->addError($field, "Create directory failed " . $uploadPath);
  40. return false;
  41. }
  42. $fullName = isset($options['filename']) ? $uploadPath . $options['filename'] : $uploadPath . date('YmdHis') . '_' . uniqid() . '.' . $upload->getExtension();
  43. if (! $upload->saveAs($fullName)) {
  44. $model->addError($field, Yii::t('app', 'Upload {attribute} error: ' . $upload->error, ['attribute' => Yii::t('app', ucfirst($field))]) . ': ' . $fullName);
  45. return false;
  46. }
  47. $model->$field = str_replace(Yii::getAlias('@frontend/web'), '', $fullName);
  48. $cdn->upload($fullName, $model->$field);
  49. if(isset($options['thumbSizes'])) self::thumbnails($fullName, $options['thumbSizes']);
  50. if( !$insert ){
  51. $file = Yii::getAlias('@frontend/web') . $model->getOldAttribute($field);
  52. if( file_exists($file) && is_file($file) ) unlink($file);
  53. if( $cdn->exists( $model->getOldAttribute($field) ) ) $cdn->delete($model->getOldAttribute($field));
  54. if(isset($options['thumbSizes'])) self::deleteThumbnails($file, $options['thumbSizes']);
  55. }
  56. } else {
  57. if( $model->$field === '0' ){//删除
  58. $file = Yii::getAlias('@frontend/web') . $model->getOldAttribute($field);
  59. if( file_exists($file) && is_file($file) ) unlink($file);
  60. if( $cdn->exists( $model->getOldAttribute($field) ) ) $cdn->delete($model->getOldAttribute($field));
  61. if(isset($options['thumbSizes'])) self::deleteThumbnails($file, $options['thumbSizes']);
  62. $model->$field = '';
  63. }else {
  64. if($insert) {
  65. $model->$field = '';
  66. }else{
  67. $model->$field = $model->getOldAttribute($field);
  68. }
  69. }
  70. }
  71. }
  72. /**
  73. * 处理单模型单文件非常态上传
  74. *
  75. * @param ActiveRecord $model
  76. * @param $field
  77. * @param $uploadPath
  78. * @param $oldFullName
  79. * @param array $options
  80. * @return bool
  81. * @throws yii\base\Exception
  82. */
  83. public static function handleModelSingleFileUploadAbnormal(ActiveRecord &$model, $field, $uploadPath, $oldFullName, $options=[])
  84. {
  85. if( !isset($options['successDeleteOld']) ) $options['successDeleteOld'] = true;//成功后删除旧文件
  86. if( !isset($options['deleteOldFile']) ) $options['deleteOldFile'] = false;//删除旧文件
  87. $upload = UploadedFile::getInstance($model, $field);
  88. /* @var $cdn \feehi\cdn\TargetInterface */
  89. $cdn = Yii::$app->get('cdn');
  90. if ($upload !== null) {
  91. $uploadPath = Yii::getAlias($uploadPath);
  92. if( strpos(strrev($uploadPath), '/') !== 0 ) $uploadPath .= '/';
  93. if (! FileHelper::createDirectory($uploadPath)) {
  94. $model->addError($field, "Create directory failed " . $uploadPath);
  95. return false;
  96. }
  97. $fullName = isset($options['filename']) ? $uploadPath . $options['filename'] : $uploadPath . date('YmdHis') . '_' . uniqid() . '.' . $upload->getExtension();
  98. if (! $upload->saveAs($fullName)) {
  99. $model->addError($field, Yii::t('app', 'Upload {attribute} error: ' . $upload->error, ['attribute' => yii::t('app', ucfirst($field))]) . ': ' . $fullName);
  100. return false;
  101. }
  102. $model->$field = str_replace(Yii::getAlias('@frontend/web'), '', $fullName);
  103. $cdn->upload($fullName, $model->$field);
  104. if(isset($options['thumbSizes'])) self::thumbnails($fullName, $options['thumbSizes']);
  105. if( $options['successDeleteOld'] && $oldFullName ){
  106. $file = Yii::getAlias('@frontend/web') . $oldFullName;
  107. if( file_exists($file) && is_file($file) ) unlink($file);
  108. if( $cdn->exists( $oldFullName ) ) $cdn->delete($oldFullName);
  109. if(isset($options['thumbSizes'])) self::deleteThumbnails($file, $options['thumbSizes']);
  110. }
  111. } else {
  112. if( $model->$field === '0' ){//删除
  113. $file = Yii::getAlias('@frontend/web') . $oldFullName;
  114. if( file_exists($file) && is_file($file) ) unlink($file);
  115. if( $cdn->exists( $oldFullName ) ) $cdn->delete($oldFullName);
  116. if(isset($options['thumbSizes'])) self::deleteThumbnails($file, $options['thumbSizes']);
  117. $model->$field = '';
  118. }else {
  119. $model->$field = $oldFullName;
  120. }
  121. }
  122. if( $options['deleteOldFile'] ){
  123. $file = Yii::getAlias('@frontend/web') . $oldFullName;
  124. if( file_exists($file) && is_file($file) ) unlink($file);
  125. if( $cdn->exists( $oldFullName ) ) $cdn->delete($oldFullName);
  126. if(isset($options['thumbSizes'])) self::deleteThumbnails($file, $options['thumbSizes']);
  127. }
  128. }
  129. /**
  130. * 生成各个尺寸的缩略图
  131. *
  132. * @param $fullName string 原图路径
  133. * @param array $thumbSizes 二维数组 如 [["w"=>110,"height"=>"20"],["w"=>200,"h"=>"30"]]则生成两张缩量图,分别为宽110高20和宽200高30
  134. * @throws yii\base\InvalidConfigException
  135. */
  136. public static function thumbnails($fullName, array $thumbSizes)
  137. {
  138. foreach ($thumbSizes as $info){
  139. $thumbFullName = self::getThumbName($fullName, $info['w'], $info['h']);
  140. Image::thumbnail($fullName, $info['w'], $info['h'])->save($thumbFullName);
  141. /** @var $cdn \feehi\cdn\TargetInterface */
  142. $cdn = Yii::$app->get('cdn');
  143. $cdn->upload($thumbFullName, str_replace(Yii::getAlias('@frontend/web'), '', $thumbFullName));
  144. }
  145. }
  146. /**
  147. * 删除各个尺寸的缩略图
  148. *
  149. * @param $fullName string 原图图片路径
  150. * @param $thumbSizes array 二维数组 如 [["w"=>110,"height"=>"20"],["w"=>200,"h"=>"30"]]则生成两张缩量图,分别为宽110高20和宽200高30
  151. * @param $deleteOrigin bool 是否删除原图
  152. * @throws yii\base\InvalidConfigException
  153. */
  154. public static function deleteThumbnails($fullName, array $thumbSizes, $deleteOrigin=false)
  155. {
  156. foreach ($thumbSizes as $info){
  157. $thumbFullName = self::getThumbName($fullName, $info['w'], $info['h']);
  158. if( file_exists($thumbFullName) && is_file($thumbFullName) ) unlink($thumbFullName);
  159. $cdn = Yii::$app->get('cdn');
  160. $cdn->delete(str_replace(Yii::getAlias("@frontend/web"), '', $thumbFullName));
  161. }
  162. if( $deleteOrigin ){
  163. file_exists($fullName) && unlink($fullName);
  164. }
  165. }
  166. /**
  167. * 根据原图路径生成缩略图路径
  168. *
  169. * @param $fullName string 原图路径
  170. * @param $width int 长
  171. * @param $height int 宽
  172. * @return string 如/path/to/uploads/article/xx@100x20.png
  173. */
  174. public static function getThumbName($fullName, $width, $height)
  175. {
  176. $dotPosition = strrpos($fullName, '.', mb_strlen(Yii::getAlias('@frontend')));
  177. $thumbExt = "@" . $width . 'x' . $height;
  178. if( $dotPosition === false ){
  179. $thumbFullName = $fullName . $thumbExt;
  180. }else{
  181. $thumbFullName = substr_replace($fullName,$thumbExt, $dotPosition, 0);
  182. }
  183. return $thumbFullName;
  184. }
  185. public static function getViewTemplate($type="article")
  186. {
  187. if( $type == "article" ){
  188. $files = Yii::$app->params['article.template.directory'];
  189. }else if ($type == "page"){
  190. $files = Yii::$app->params['page.template.directory'];
  191. }else if($type == "category"){
  192. $files = Yii::$app->params['category.template.directory'];
  193. }else{
  194. throw new Exception("Unknown " . $type);
  195. }
  196. $templates = [];
  197. foreach ($files as $key => $file){
  198. if( !is_int($key) ) {
  199. $templates[str_replace(Yii::getAlias("@frontend/views"), "", $key)] = $file;
  200. }else{
  201. $templates[str_replace(Yii::getAlias("@frontend/views"), "", $file)] = $file;
  202. }
  203. }
  204. return $templates;
  205. }
  206. }