JavaScript.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace Dcat\Admin\Support;
  3. use Illuminate\Contracts\Support\Arrayable;
  4. use Illuminate\Support\Str;
  5. class JavaScript
  6. {
  7. protected static $scripts = [];
  8. /**
  9. * @var string
  10. */
  11. protected $id;
  12. public function __construct($script)
  13. {
  14. $this->id = 'js('.Str::random().')';
  15. $this->value($script);
  16. }
  17. /**
  18. * 设置或获取代码内容.
  19. *
  20. * @param mixed $script
  21. *
  22. * @return mixed
  23. */
  24. public function value($script = null)
  25. {
  26. if ($script === null) {
  27. return static::$scripts[$this->id];
  28. }
  29. static::$scripts[$this->id] = (string) value($script);
  30. }
  31. /**
  32. * @param string|\Closure $script
  33. *
  34. * @return string
  35. */
  36. public static function make($script)
  37. {
  38. return (string) new static($script);
  39. }
  40. /**
  41. * 获取所有代码
  42. *
  43. * @return array
  44. */
  45. public static function all()
  46. {
  47. return static::$scripts;
  48. }
  49. /**
  50. * 删除代码.
  51. *
  52. * @param string $id
  53. */
  54. public static function delete(string $id)
  55. {
  56. unset(static::$scripts[$id]);
  57. }
  58. /**
  59. * 格式化为js代码.
  60. *
  61. * @param array|Arrayable $value
  62. *
  63. * @return string
  64. */
  65. public static function format($value)
  66. {
  67. if (is_array($value) || is_object($value)) {
  68. $value = json_encode(Helper::array($value));
  69. }
  70. foreach (static::all() as $id => $script) {
  71. $id = "\"$id\"";
  72. if (mb_strpos($value, $id) !== false) {
  73. $value = str_replace($id, $script, $value);
  74. static::delete($id);
  75. }
  76. }
  77. return $value;
  78. }
  79. /**
  80. * @return string
  81. */
  82. public function __toString()
  83. {
  84. return $this->id;
  85. }
  86. }