Helper.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. <?php
  2. namespace Dcat\Admin\Support;
  3. use Dcat\Admin\Grid;
  4. use Illuminate\Contracts\Support\Arrayable;
  5. use Illuminate\Contracts\Support\Htmlable;
  6. use Illuminate\Contracts\Support\Renderable;
  7. use Illuminate\Support\Arr;
  8. use Illuminate\Support\Facades\Artisan;
  9. use Illuminate\Support\Str;
  10. class Helper
  11. {
  12. /**
  13. * Update extension config.
  14. *
  15. * @param array $config
  16. *
  17. * @return bool
  18. */
  19. public static function updateExtensionConfig(array $config)
  20. {
  21. $files = app('files');
  22. $result = (bool) $files->put(config_path('admin-extensions.php'), self::exportArrayPhp($config));
  23. if ($result && is_file(base_path('bootstrap/cache/config.php'))) {
  24. Artisan::call('config:cache');
  25. }
  26. config(['admin-extensions' => $config]);
  27. return $result;
  28. }
  29. /**
  30. * Converts the given value to an array.
  31. *
  32. * @param $value
  33. * @param bool $filter
  34. *
  35. * @return array
  36. */
  37. public static function array($value, bool $filter = true): array
  38. {
  39. if (! $value) {
  40. return [];
  41. }
  42. if ($value instanceof \Closure) {
  43. $value = $value();
  44. }
  45. if (is_array($value)) {
  46. } elseif ($value instanceof Arrayable) {
  47. $value = $value->toArray();
  48. } elseif (is_string($value)) {
  49. $value = explode(',', $value);
  50. } else {
  51. $value = (array) $value;
  52. }
  53. return $filter ? array_filter($value, function ($v) {
  54. return $v !== '' && $v !== null;
  55. }) : $value;
  56. }
  57. /**
  58. * Converts the given value to string.
  59. *
  60. * @param mixed $value
  61. * @param array $params
  62. * @param object $newThis
  63. *
  64. * @return string
  65. */
  66. public static function render($value, $params = [], $newThis = null): string
  67. {
  68. if (is_string($value)) {
  69. return $value;
  70. }
  71. if ($value instanceof Grid) {
  72. return (string) $value->render();
  73. }
  74. if ($value instanceof \Closure) {
  75. $newThis && $value = $value->bindTo($newThis);
  76. $value = $value(...(array) $params);
  77. }
  78. if ($value instanceof Renderable) {
  79. return (string) $value->render();
  80. }
  81. if ($value instanceof Htmlable) {
  82. return (string) $value->toHtml();
  83. }
  84. return (string) $value;
  85. }
  86. /**
  87. * Build an HTML attribute string from an array.
  88. *
  89. * @param array $attributes
  90. *
  91. * @return string
  92. */
  93. public static function buildHtmlAttributes($attributes)
  94. {
  95. $html = '';
  96. foreach ((array) $attributes as $key => &$value) {
  97. if (is_numeric($key)) {
  98. $key = $value;
  99. }
  100. $element = '';
  101. if ($value !== null) {
  102. $element = $key.'="'.htmlentities($value, ENT_QUOTES, 'UTF-8').'"';
  103. }
  104. $html .= $element;
  105. }
  106. return $html;
  107. }
  108. /**
  109. * Get url with the added query string parameters.
  110. *
  111. * @param string $url
  112. * @param array $query
  113. *
  114. * @return string
  115. */
  116. public static function urlWithQuery(?string $url, array $query = [])
  117. {
  118. if (! $url || ! $query) {
  119. return $url;
  120. }
  121. $array = explode('?', $url);
  122. $url = $array[0];
  123. $originalQuery = $array[1] ?? '';
  124. parse_str($originalQuery, $originalQuery);
  125. return $url.'?'.http_build_query(array_merge($originalQuery, $query));
  126. }
  127. /**
  128. * @param string $url
  129. * @param string|array|Arrayable $keys
  130. *
  131. * @return string
  132. */
  133. public static function urlWithoutQuery($url, $keys)
  134. {
  135. if (! Str::contains($url, '?') || ! $keys) {
  136. return $url;
  137. }
  138. if ($keys instanceof Arrayable) {
  139. $keys = $keys->toArray();
  140. }
  141. $keys = (array) $keys;
  142. $urlInfo = parse_url($url);
  143. parse_str($urlInfo['query'], $query);
  144. Arr::forget($query, $keys);
  145. $baseUrl = explode('?', $url)[0];
  146. return $query
  147. ? $baseUrl.'?'.http_build_query($query)
  148. : $baseUrl;
  149. }
  150. /**
  151. * Get full url without query strings.
  152. *
  153. * @param Arrayable|array|string $keys
  154. *
  155. * @return string
  156. */
  157. public static function fullUrlWithoutQuery($keys)
  158. {
  159. return static::urlWithoutQuery(request()->fullUrl(), $keys);
  160. }
  161. /**
  162. * If a request match the specific path.
  163. *
  164. * @example
  165. * Helper::matchRequestPath('auth/user')
  166. * Helper::matchRequestPath('auth/user*')
  167. * Helper::matchRequestPath('auth/user/* /edit')
  168. * Helper::matchRequestPath('GET,POST:auth/user')
  169. *
  170. * @param string $path
  171. * @param null|string $current
  172. *
  173. * @return bool
  174. */
  175. public static function matchRequestPath($path, ?string $current = null)
  176. {
  177. $request = request();
  178. $current = $current ?: $request->decodedPath();
  179. if (Str::contains($path, ':')) {
  180. [$methods, $path] = explode(':', $path);
  181. $methods = array_map('strtoupper', explode(',', $methods));
  182. if (! empty($methods) && ! in_array($request->method(), $methods)) {
  183. return false;
  184. }
  185. }
  186. if (! Str::contains($path, '*')) {
  187. return $path === $current;
  188. }
  189. $path = str_replace(['*', '/'], ['([0-9a-z-_,])*', "\/"], $path);
  190. return preg_match("/$path/i", $current);
  191. }
  192. /**
  193. * Build nested array.
  194. *
  195. * @param array $nodes
  196. * @param int $parentId
  197. * @param string|null $primaryKeyName
  198. * @param string|null $parentKeyName
  199. * @param string|null $childrenKeyName
  200. *
  201. * @return array
  202. */
  203. public static function buildNestedArray(
  204. $nodes = [],
  205. $parentId = 0,
  206. ?string $primaryKeyName = null,
  207. ?string $parentKeyName = null,
  208. ?string $childrenKeyName = null
  209. ) {
  210. $branch = [];
  211. $primaryKeyName = $primaryKeyName ?: 'id';
  212. $parentKeyName = $parentKeyName ?: 'parent_id';
  213. $childrenKeyName = $childrenKeyName ?: 'children';
  214. $parentId = is_numeric($parentId) ? (int) $parentId : $parentId;
  215. foreach ($nodes as $node) {
  216. $pk = Arr::get($node, $parentKeyName);
  217. $pk = is_numeric($pk) ? (int) $pk : $pk;
  218. if ($pk === $parentId) {
  219. $children = static::buildNestedArray(
  220. $nodes,
  221. Arr::get($node, $primaryKeyName),
  222. $primaryKeyName,
  223. $parentKeyName,
  224. $childrenKeyName
  225. );
  226. if ($children) {
  227. $node[$childrenKeyName] = $children;
  228. }
  229. $branch[] = $node;
  230. }
  231. }
  232. return $branch;
  233. }
  234. /**
  235. * Generate a URL friendly "slug" from a given string.
  236. *
  237. * @param string $name
  238. * @param string $symbol
  239. *
  240. * @return mixed
  241. */
  242. public static function slug(string $name, string $symbol = '-')
  243. {
  244. $text = preg_replace_callback('/([A-Z])/', function (&$text) use ($symbol) {
  245. return $symbol.strtolower($text[1]);
  246. }, $name);
  247. return str_replace('_', $symbol, ltrim($text, $symbol));
  248. }
  249. /**
  250. * @param array $array
  251. * @param int $level
  252. *
  253. * @return string
  254. */
  255. public static function exportArray(array &$array, $level = 1)
  256. {
  257. $start = '[';
  258. $end = ']';
  259. $txt = "$start\n";
  260. foreach ($array as $k => &$v) {
  261. if (is_array($v)) {
  262. $pre = is_string($k) ? "'$k' => " : "$k => ";
  263. $txt .= str_repeat(' ', $level * 4).$pre.static::exportArray($v, $level + 1).",\n";
  264. continue;
  265. }
  266. $t = $v;
  267. if ($v === true) {
  268. $t = 'true';
  269. } elseif ($v === false) {
  270. $t = 'false';
  271. } elseif ($v === null) {
  272. $t = 'null';
  273. } elseif (is_string($v)) {
  274. $v = str_replace("'", "\\'", $v);
  275. $t = "'$v'";
  276. }
  277. $pre = is_string($k) ? "'$k' => " : "$k => ";
  278. $txt .= str_repeat(' ', $level * 4)."{$pre}{$t},\n";
  279. }
  280. return $txt.str_repeat(' ', ($level - 1) * 4).$end;
  281. }
  282. /**
  283. * @param array $array
  284. *
  285. * @return string
  286. */
  287. public static function exportArrayPhp(array $array)
  288. {
  289. return "<?php \nreturn ".static::exportArray($array).";\n";
  290. }
  291. /**
  292. * Delete from array by value.
  293. *
  294. * @param array $array
  295. * @param mixed $value
  296. */
  297. public static function deleteByValue(&$array, $value)
  298. {
  299. $value = (array) $value;
  300. foreach ($array as $index => $item) {
  301. if (in_array($item, $value)) {
  302. unset($array[$index]);
  303. }
  304. }
  305. }
  306. }