Field.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. <?php
  2. namespace Dcat\Admin\Show;
  3. use Dcat\Admin\Show;
  4. use Dcat\Admin\Traits\HasBuilderEvents;
  5. use Dcat\Admin\Traits\HasDefinitions;
  6. use Dcat\Admin\Widgets\Dump;
  7. use Illuminate\Contracts\Support\Arrayable;
  8. use Illuminate\Contracts\Support\Renderable;
  9. use Illuminate\Support\Arr;
  10. use Illuminate\Support\Collection;
  11. use Illuminate\Support\Facades\File;
  12. use Illuminate\Support\Facades\Storage;
  13. use Illuminate\Support\Fluent;
  14. use Illuminate\Support\Str;
  15. use Illuminate\Support\Traits\Macroable;
  16. class Field implements Renderable
  17. {
  18. use HasBuilderEvents,
  19. HasDefinitions,
  20. Macroable {
  21. __call as macroCall;
  22. }
  23. /**
  24. * @var array
  25. */
  26. protected static $extendedFields = [];
  27. /**
  28. * @var string
  29. */
  30. protected $view = 'admin::show.field';
  31. /**
  32. * Name of column.
  33. *
  34. * @var string
  35. */
  36. protected $name;
  37. /**
  38. * Label of column.
  39. *
  40. * @var string
  41. */
  42. protected $label;
  43. /**
  44. * Escape field value or not.
  45. *
  46. * @var bool
  47. */
  48. protected $escape = true;
  49. /**
  50. * Field value.
  51. *
  52. * @var mixed
  53. */
  54. protected $value;
  55. /**
  56. * @var Collection
  57. */
  58. protected $showAs = [];
  59. /**
  60. * Parent show instance.
  61. *
  62. * @var Show
  63. */
  64. protected $parent;
  65. /**
  66. * Relation name.
  67. *
  68. * @var string
  69. */
  70. protected $relation;
  71. /**
  72. * If show contents in box.
  73. *
  74. * @var bool
  75. */
  76. protected $border = false;
  77. /**
  78. * @var int
  79. */
  80. protected $width = 3;
  81. /**
  82. * @var array
  83. */
  84. protected $fileTypes = [
  85. 'image' => 'png|jpg|jpeg|tmp|gif',
  86. 'word' => 'doc|docx',
  87. 'excel' => 'xls|xlsx|csv',
  88. 'powerpoint' => 'ppt|pptx',
  89. 'pdf' => 'pdf',
  90. 'code' => 'php|js|java|python|ruby|go|c|cpp|sql|m|h|json|html|aspx',
  91. 'archive' => 'zip|tar\.gz|rar|rpm',
  92. 'txt' => 'txt|pac|log|md',
  93. 'audio' => 'mp3|wav|flac|3pg|aa|aac|ape|au|m4a|mpc|ogg',
  94. 'video' => 'mkv|rmvb|flv|mp4|avi|wmv|rm|asf|mpeg',
  95. ];
  96. /**
  97. * Field constructor.
  98. *
  99. * @param string $name
  100. * @param string $label
  101. */
  102. public function __construct($name = '', $label = '')
  103. {
  104. $this->name = $name;
  105. $this->label = $this->formatLabel($label);
  106. $this->showAs = new Collection();
  107. $this->callResolving();
  108. }
  109. /**
  110. * Set parent show instance.
  111. *
  112. * @param Show $show
  113. *
  114. * @return $this
  115. */
  116. public function setParent(Show $show)
  117. {
  118. $this->parent = $show;
  119. return $this;
  120. }
  121. /**
  122. * Get name of this column.
  123. *
  124. * @return mixed
  125. */
  126. public function getName()
  127. {
  128. return $this->name;
  129. }
  130. /**
  131. * @param int $width
  132. * @return $this
  133. */
  134. public function width(int $width)
  135. {
  136. $this->width = $width;
  137. return $this;
  138. }
  139. /**
  140. * Format label.
  141. *
  142. * @param $label
  143. *
  144. * @return mixed
  145. */
  146. protected function formatLabel($label)
  147. {
  148. $label = $label ?: ucfirst(admin_trans_field($this->name));
  149. return str_replace(['.', '_'], ' ', $label);
  150. }
  151. /**
  152. * Get label of the column.
  153. *
  154. * @return mixed
  155. */
  156. public function getLabel()
  157. {
  158. return $this->label;
  159. }
  160. /**
  161. * Field display callback.
  162. *
  163. * @param mixed $callable
  164. *
  165. * @return $this
  166. */
  167. public function as($callable, ...$params)
  168. {
  169. $this->showAs->push([$callable, $params]);
  170. return $this;
  171. }
  172. /**
  173. * Display field using array value map.
  174. *
  175. * @param array $values
  176. * @param null $default
  177. *
  178. * @return $this
  179. */
  180. public function using(array $values, $default = null)
  181. {
  182. return $this->as(function ($value) use ($values, $default) {
  183. if (is_null($value)) {
  184. return $default;
  185. }
  186. return Arr::get($values, $value, $default);
  187. });
  188. }
  189. /**
  190. * Show field as a image.
  191. *
  192. * @param string $server
  193. * @param int $width
  194. * @param int $height
  195. *
  196. * @return $this
  197. */
  198. public function image($server = '', $width = 200, $height = 200)
  199. {
  200. return $this->unescape()->as(function ($path) use ($server, $width, $height) {
  201. if (empty($path)) {
  202. return '';
  203. }
  204. if (url()->isValidUrl($path)) {
  205. $src = $path;
  206. } elseif ($server) {
  207. $src = $server.$path;
  208. } else {
  209. $disk = config('admin.upload.disk');
  210. if (config("filesystems.disks.{$disk}")) {
  211. $src = Storage::disk($disk)->url($path);
  212. } else {
  213. return '';
  214. }
  215. }
  216. return "<img data-init='preview' src='$src' style='max-width:{$width}px;max-height:{$height}px' class='img' />";
  217. });
  218. }
  219. /**
  220. * Show field as a file.
  221. *
  222. * @param string $server
  223. * @param bool $download
  224. *
  225. * @return Field
  226. */
  227. public function file($server = '', $download = true)
  228. {
  229. $field = $this;
  230. return $this->unescape()->as(function ($path) use ($server, $download, $field) {
  231. $name = basename($path);
  232. $field->wrap(false);
  233. $size = $url = '';
  234. if (url()->isValidUrl($path)) {
  235. $url = $path;
  236. } elseif ($server) {
  237. $url = $server.$path;
  238. } else {
  239. $storage = Storage::disk(config('admin.upload.disk'));
  240. if ($storage->exists($path)) {
  241. $url = $storage->url($path);
  242. $size = ($storage->size($path) / 1000).'KB';
  243. }
  244. }
  245. if (!$url) {
  246. return '';
  247. }
  248. return <<<HTML
  249. <ul class="mailbox-attachments clearfix">
  250. <li style="margin-bottom: 0;">
  251. <span class="mailbox-attachment-icon"><i class="fa {$field->getFileIcon($name)}"></i></span>
  252. <div class="mailbox-attachment-info">
  253. <div class="mailbox-attachment-name">
  254. <i class="fa fa-paperclip"></i> {$name}
  255. </div>
  256. <span class="mailbox-attachment-size">
  257. {$size}&nbsp;
  258. <a href="{$url}" class="btn btn-default btn-xs pull-right" target="_blank"><i class="fa fa-cloud-download"></i></a>
  259. </span>
  260. </div>
  261. </li>
  262. </ul>
  263. HTML;
  264. });
  265. }
  266. /**
  267. * Show field as a link.
  268. *
  269. * @param string $href
  270. * @param string $target
  271. *
  272. * @return Field
  273. */
  274. public function link($href = '', $target = '_blank')
  275. {
  276. return $this->unescape()->as(function ($link) use ($href, $target) {
  277. $href = $href ?: $link;
  278. return "<a href='$href' target='{$target}'>{$link}</a>";
  279. });
  280. }
  281. /**
  282. * Show field as labels.
  283. *
  284. * @param string $style
  285. *
  286. * @return Field
  287. */
  288. public function label($style = 'success')
  289. {
  290. return $this->unescape()->as(function ($value) use ($style) {
  291. if ($value instanceof Arrayable) {
  292. $value = $value->toArray();
  293. }
  294. return collect((array) $value)->map(function ($name) use ($style) {
  295. return "<span class='label label-{$style}'>$name</span>";
  296. })->implode('&nbsp;');
  297. });
  298. }
  299. /**
  300. * Show field as badges.
  301. *
  302. * @param string $style
  303. *
  304. * @return Field
  305. */
  306. public function badge($style = 'blue')
  307. {
  308. return $this->unescape()->as(function ($value) use ($style) {
  309. if ($value instanceof Arrayable) {
  310. $value = $value->toArray();
  311. }
  312. return collect((array) $value)->map(function ($name) use ($style) {
  313. return "<span class='badge bg-{$style}'>$name</span>";
  314. })->implode('&nbsp;');
  315. });
  316. }
  317. /**
  318. * Show field as json code.
  319. *
  320. * @return Field
  321. */
  322. public function json()
  323. {
  324. $field = $this;
  325. return $this->unescape()->as(function ($value) use ($field) {
  326. $content = is_string($value) ? json_decode($value, true) : $value;
  327. $field->wrap(false);
  328. return Dump::make($content);
  329. });
  330. }
  331. /**
  332. * @param string $val
  333. * @return $this
  334. */
  335. public function prepend($val)
  336. {
  337. return $this->as(function ($v) use (&$val) {
  338. if (is_array($v)) {
  339. array_unshift($v, $val);
  340. return $v;
  341. } elseif ($v instanceof Collection) {
  342. return $v->prepend($val);
  343. }
  344. return $val . $v;
  345. });
  346. }
  347. /**
  348. * @param string $val
  349. * @return $this
  350. */
  351. public function append($val)
  352. {
  353. return $this->as(function ($v) use (&$val) {
  354. if (is_array($v)) {
  355. array_push($v, $val);
  356. return $v;
  357. } elseif ($v instanceof Collection) {
  358. return $v->push($val);
  359. }
  360. return $v . $val;
  361. });
  362. }
  363. /**
  364. * Split a string by string
  365. *
  366. * @param string $d
  367. * @return $this
  368. */
  369. public function explode(string $d = ',')
  370. {
  371. return $this->as(function ($v) use ($d) {
  372. if (is_array($v) || $v instanceof Arrayable) return $v;
  373. return $v ? explode($d, $v) : [];
  374. });
  375. }
  376. /**
  377. * Render this column with the given view.
  378. *
  379. * @param string $view
  380. *
  381. * @return $this
  382. */
  383. public function view($view)
  384. {
  385. $name = $this->name;
  386. return $this->as(function ($value) use ($view, $name) {
  387. $model = $this;
  388. return view($view, compact('model', 'value', 'name'))->render();
  389. });
  390. }
  391. /**
  392. * Get file icon.
  393. *
  394. * @param string $file
  395. *
  396. * @return string
  397. */
  398. public function getFileIcon($file = '')
  399. {
  400. $extension = File::extension($file);
  401. foreach ($this->fileTypes as $type => $regex) {
  402. if (preg_match("/^($regex)$/i", $extension) !== 0) {
  403. return "fa-file-{$type}-o";
  404. }
  405. }
  406. return 'fa-file-o';
  407. }
  408. /**
  409. * Set escape or not for this field.
  410. *
  411. * @param bool $escape
  412. *
  413. * @return $this
  414. */
  415. public function escape($escape = true)
  416. {
  417. $this->escape = $escape;
  418. return $this;
  419. }
  420. /**
  421. * Unescape for this field.
  422. *
  423. * @return Field
  424. */
  425. public function unescape()
  426. {
  427. return $this->escape(false);
  428. }
  429. /**
  430. * Set value for this field.
  431. *
  432. * @param Fluent $model
  433. *
  434. * @return $this
  435. */
  436. public function setValue(Fluent $model)
  437. {
  438. $this->value = $model->get($this->name);
  439. return $this;
  440. }
  441. /**
  442. * @return $this
  443. */
  444. public function wrap(bool $wrap = true)
  445. {
  446. $this->border = $wrap;
  447. return $this;
  448. }
  449. /**
  450. * @param string $method
  451. * @param array $arguments
  452. *
  453. * @return $this
  454. */
  455. public function __call($method, $arguments = [])
  456. {
  457. if ($class = Arr::get(static::$extendedFields, $method)) {
  458. return $this->callExtendedField($class, $arguments);
  459. }
  460. if (static::hasMacro($method)) {
  461. return $this->macroCall($method, $arguments);
  462. }
  463. return $this->callSupportDisplayer($method, $arguments);
  464. }
  465. /**
  466. * Call extended field.
  467. *
  468. * @param string|AbstractField|\Closure $abstract
  469. * @param array $arguments
  470. *
  471. * @return Field
  472. */
  473. protected function callExtendedField($abstract, $arguments = [])
  474. {
  475. if ($abstract instanceof \Closure) {
  476. return $this->as($abstract, ...$arguments);
  477. }
  478. if (is_string($abstract) && class_exists($abstract)) {
  479. /** @var AbstractField $extend */
  480. $extend = new $abstract();
  481. }
  482. if ($abstract instanceof AbstractField) {
  483. /** @var AbstractField $extend */
  484. $extend = $abstract;
  485. }
  486. if (!isset($extend)) {
  487. admin_warning("[$abstract] is not a valid Show field.");
  488. return $this;
  489. }
  490. if (!$extend->escape) {
  491. $this->unescape();
  492. }
  493. $field = $this;
  494. return $this->as(function ($value) use ($extend, $field, $arguments) {
  495. if (!$extend->border) {
  496. $field->wrap(false);
  497. }
  498. $extend->setValue($value)->setModel($this);
  499. return $extend->render(...$arguments);
  500. });
  501. }
  502. /**
  503. * Call Illuminate/Support.
  504. *
  505. * @param string $abstract
  506. * @param array $arguments
  507. *
  508. * @return $this
  509. */
  510. protected function callSupportDisplayer($abstract, $arguments)
  511. {
  512. return $this->as(function ($value) use ($abstract, $arguments) {
  513. if (is_array($value) || $value instanceof Arrayable) {
  514. return call_user_func_array([collect($value), $abstract], $arguments);
  515. }
  516. if (is_string($value)) {
  517. return call_user_func_array([Str::class, $abstract], array_merge([$value], $arguments));
  518. }
  519. return $value;
  520. });
  521. }
  522. /**
  523. * Get all variables passed to field view.
  524. *
  525. * @return array
  526. */
  527. protected function variables()
  528. {
  529. return [
  530. 'content' => $this->value,
  531. 'escape' => $this->escape,
  532. 'label' => $this->getLabel(),
  533. 'wrapped' => $this->border,
  534. 'width' => $this->width,
  535. ];
  536. }
  537. /**
  538. * Render this field.
  539. *
  540. * @return string
  541. */
  542. public function render()
  543. {
  544. if (static::hasDefinition($this->name)) {
  545. $this->useDefinedColumn();
  546. }
  547. if ($this->showAs->isNotEmpty()) {
  548. $this->showAs->each(function ($callable) {
  549. list($callable, $params) = $callable;
  550. if (!$callable instanceof \Closure) {
  551. $this->value = $callable;
  552. return;
  553. }
  554. $this->value = $callable->call(
  555. $this->parent->getModel(),
  556. $this->value,
  557. ...$params
  558. );
  559. });
  560. }
  561. return view($this->view, $this->variables());
  562. }
  563. /**
  564. * Use a defined column.
  565. *
  566. * @throws \Exception
  567. */
  568. protected function useDefinedColumn()
  569. {
  570. $class = static::$definitions[$this->name];
  571. if (!$class instanceof \Closure) {
  572. throw new \Exception("Invalid column definition [$class]");
  573. }
  574. $this->as($class);
  575. }
  576. /**
  577. * Register custom field.
  578. *
  579. * @param string $abstract
  580. * @param string $class
  581. *
  582. * @return void
  583. */
  584. public static function extend($abstract, $class)
  585. {
  586. static::$extendedFields[$abstract] = $class;
  587. }
  588. /**
  589. * @return array
  590. */
  591. public static function getExtensions()
  592. {
  593. return static::$extendedFields;
  594. }
  595. }