Cropper.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace common\widgets\cropper;
  3. use Yii;
  4. use yii\helpers\Url;
  5. use yii\widgets\InputWidget;
  6. use common\helpers\ArrayHelper;
  7. use common\helpers\Html;
  8. use common\helpers\StringHelper;
  9. /**
  10. * Class Cropper
  11. * @package common\widgets\cropper
  12. * @author jianyan74 <751393839@qq.com>
  13. */
  14. class Cropper extends InputWidget
  15. {
  16. /**
  17. * @var array
  18. */
  19. public $config = [];
  20. /**
  21. * @var array
  22. */
  23. public $formData = [];
  24. /**
  25. * 默认主题
  26. *
  27. * @var string
  28. */
  29. public $theme = 'default';
  30. /**
  31. * 默认主题配置
  32. *
  33. * @var array
  34. */
  35. public $themeConfig = [];
  36. /**
  37. * 盒子ID
  38. *
  39. * @var
  40. */
  41. protected $boxId;
  42. /**
  43. * @throws \yii\base\InvalidConfigException
  44. * @throws \Exception
  45. */
  46. public function init()
  47. {
  48. parent::init();
  49. $name = $this->hasModel() ? Html::getInputName($this->model, $this->attribute) : $this->name;
  50. $this->boxId = md5($name) . StringHelper::uuid('uniqid');
  51. $this->config = ArrayHelper::merge([
  52. 'aspectRatio' => '1',
  53. 'multiple' => false,
  54. 'server' => Url::to(['/files/base64']),
  55. ], $this->config);
  56. $this->formData = ArrayHelper::merge([
  57. 'drive' => Yii::$app->services->config->backendConfig('storage_default'),
  58. 'image' => '',
  59. ], $this->formData);
  60. $this->themeConfig = ArrayHelper::merge([
  61. 'select' => true
  62. ], $this->themeConfig);
  63. }
  64. /**
  65. * @return string
  66. */
  67. public function run()
  68. {
  69. $value = $this->hasModel() ? Html::getAttributeValue($this->model, $this->attribute) : $this->value;
  70. $name = $this->hasModel() ? Html::getInputName($this->model, $this->attribute) : $this->name;
  71. empty($value) && $value = [];
  72. if ($this->config['multiple'] == true) {
  73. // 赋予默认值
  74. $name = $name . '[]';
  75. if ($value && !is_array($value)) {
  76. $value = json_decode($value, true);
  77. empty($value) && $value = unserialize($value);
  78. empty($value) && $value = [];
  79. }
  80. }
  81. if (!is_array($value)) {
  82. $tmp = $value;
  83. $value = [];
  84. $value[] = $tmp;
  85. }
  86. return $this->render($this->theme, [
  87. 'name' => $name,
  88. 'value' => $value,
  89. 'boxId' => $this->boxId,
  90. 'config' => $this->config,
  91. 'type' => 'images',
  92. 'formData' => $this->formData,
  93. 'themeConfig' => $this->themeConfig,
  94. ]);
  95. }
  96. }
粤ICP备19079148号