Helper.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. <?php
  2. namespace Dcat\Admin\Support;
  3. use Dcat\Admin\Grid;
  4. use Dcat\Laravel\Database\WhereHasInServiceProvider;
  5. use Illuminate\Contracts\Support\Arrayable;
  6. use Illuminate\Contracts\Support\Htmlable;
  7. use Illuminate\Contracts\Support\Jsonable;
  8. use Illuminate\Contracts\Support\Renderable;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Arr;
  11. use Illuminate\Support\Collection;
  12. use Illuminate\Support\Facades\File;
  13. use Illuminate\Support\Str;
  14. use Symfony\Component\Process\Process;
  15. class Helper
  16. {
  17. /**
  18. * @var array
  19. */
  20. public static $fileTypes = [
  21. 'image' => 'png|jpg|jpeg|tmp|gif',
  22. 'word' => 'doc|docx',
  23. 'excel' => 'xls|xlsx|csv',
  24. 'powerpoint' => 'ppt|pptx',
  25. 'pdf' => 'pdf',
  26. 'code' => 'php|js|java|python|ruby|go|c|cpp|sql|m|h|json|html|aspx',
  27. 'archive' => 'zip|tar\.gz|rar|rpm',
  28. 'txt' => 'txt|pac|log|md',
  29. 'audio' => 'mp3|wav|flac|3pg|aa|aac|ape|au|m4a|mpc|ogg',
  30. 'video' => 'mkv|rmvb|flv|mp4|avi|wmv|rm|asf|mpeg',
  31. ];
  32. protected static $controllerNames = [];
  33. /**
  34. * 把给定的值转化为数组.
  35. *
  36. * @param $value
  37. * @param bool $filter
  38. *
  39. * @return array
  40. */
  41. public static function array($value, bool $filter = true): array
  42. {
  43. if ($value === null || $value === '' || $value === []) {
  44. return [];
  45. }
  46. if ($value instanceof \Closure) {
  47. $value = $value();
  48. }
  49. if (is_array($value)) {
  50. } elseif ($value instanceof Jsonable) {
  51. $value = json_decode($value->toJson(), true);
  52. } elseif ($value instanceof Arrayable) {
  53. $value = $value->toArray();
  54. } elseif (is_string($value)) {
  55. $array = null;
  56. try {
  57. $array = json_decode($value, true);
  58. } catch (\Throwable $e) {
  59. }
  60. $value = is_array($array) ? $array : explode(',', $value);
  61. } else {
  62. $value = (array) $value;
  63. }
  64. return $filter ? array_filter($value, function ($v) {
  65. return $v !== '' && $v !== null;
  66. }) : $value;
  67. }
  68. /**
  69. * 把给定的值转化为字符串.
  70. *
  71. * @param string|Grid|\Closure|Renderable|Htmlable $value
  72. * @param array $params
  73. * @param object $newThis
  74. *
  75. * @return string
  76. */
  77. public static function render($value, $params = [], $newThis = null): string
  78. {
  79. if (is_string($value)) {
  80. return $value;
  81. }
  82. if ($value instanceof \Closure) {
  83. $newThis && ($value = $value->bindTo($newThis));
  84. $value = $value(...(array) $params);
  85. }
  86. if ($value instanceof Renderable) {
  87. return (string) $value->render();
  88. }
  89. if ($value instanceof Htmlable) {
  90. return (string) $value->toHtml();
  91. }
  92. return (string) $value;
  93. }
  94. /**
  95. * 获取当前控制器名称.
  96. *
  97. * @return mixed|string
  98. */
  99. public static function getControllerName()
  100. {
  101. $router = app('router');
  102. if (! $router->current()) {
  103. return 'undefined';
  104. }
  105. $actionName = $router->current()->getActionName();
  106. if (! isset(static::$controllerNames[$actionName])) {
  107. $controller = class_basename(explode('@', $actionName)[0]);
  108. static::$controllerNames[$actionName] = str_replace('Controller', '', $controller);
  109. }
  110. return static::$controllerNames[$actionName];
  111. }
  112. /**
  113. * @param array $attributes
  114. *
  115. * @return string
  116. */
  117. public static function buildHtmlAttributes($attributes)
  118. {
  119. $html = '';
  120. foreach ((array) $attributes as $key => &$value) {
  121. if (is_array($value)) {
  122. $value = implode(' ', $value);
  123. }
  124. if (is_numeric($key)) {
  125. $key = $value;
  126. }
  127. $element = '';
  128. if ($value !== null) {
  129. $element = $key.'="'.htmlentities($value, ENT_QUOTES, 'UTF-8').'"';
  130. }
  131. $html .= $element;
  132. }
  133. return $html;
  134. }
  135. /**
  136. * @param string $url
  137. * @param array $query
  138. *
  139. * @return string
  140. */
  141. public static function urlWithQuery(?string $url, array $query = [])
  142. {
  143. if (! $url || ! $query) {
  144. return $url;
  145. }
  146. $array = explode('?', $url);
  147. $url = $array[0];
  148. parse_str($array[1] ?? '', $originalQuery);
  149. return $url.'?'.http_build_query(array_merge($originalQuery, $query));
  150. }
  151. /**
  152. * @param string $url
  153. * @param string|array|Arrayable $keys
  154. *
  155. * @return string
  156. */
  157. public static function urlWithoutQuery($url, $keys)
  158. {
  159. if (! Str::contains($url, '?') || ! $keys) {
  160. return $url;
  161. }
  162. if ($keys instanceof Arrayable) {
  163. $keys = $keys->toArray();
  164. }
  165. $keys = (array) $keys;
  166. $urlInfo = parse_url($url);
  167. parse_str($urlInfo['query'], $query);
  168. Arr::forget($query, $keys);
  169. $baseUrl = explode('?', $url)[0];
  170. return $query
  171. ? $baseUrl.'?'.http_build_query($query)
  172. : $baseUrl;
  173. }
  174. /**
  175. * @param Arrayable|array|string $keys
  176. *
  177. * @return string
  178. */
  179. public static function fullUrlWithoutQuery($keys)
  180. {
  181. return static::urlWithoutQuery(request()->fullUrl(), $keys);
  182. }
  183. /**
  184. * @param string $url
  185. * @param string|array $keys
  186. *
  187. * @return bool
  188. */
  189. public static function urlHasQuery(string $url, $keys)
  190. {
  191. $value = explode('?', $url);
  192. if (empty($value[1])) {
  193. return false;
  194. }
  195. parse_str($value[1], $query);
  196. foreach ((array) $keys as $key) {
  197. if (Arr::has($query, $key)) {
  198. return true;
  199. }
  200. }
  201. return false;
  202. }
  203. /**
  204. * 匹配请求路径.
  205. *
  206. * @example
  207. * Helper::matchRequestPath(admin_base_path('auth/user'))
  208. * Helper::matchRequestPath(admin_base_path('auth/user*'))
  209. * Helper::matchRequestPath(admin_base_path('auth/user/* /edit'))
  210. * Helper::matchRequestPath('GET,POST:auth/user')
  211. *
  212. * @param string $path
  213. * @param null|string $current
  214. *
  215. * @return bool
  216. */
  217. public static function matchRequestPath($path, ?string $current = null)
  218. {
  219. $request = request();
  220. $current = $current ?: $request->decodedPath();
  221. if (Str::contains($path, ':')) {
  222. [$methods, $path] = explode(':', $path);
  223. $methods = array_map('strtoupper', explode(',', $methods));
  224. if (! empty($methods) && ! in_array($request->method(), $methods)) {
  225. return false;
  226. }
  227. }
  228. // 判断路由名称
  229. if ($request->routeIs($path) || $request->routeIs(admin_route_name($path))) {
  230. return true;
  231. }
  232. if (! Str::contains($path, '*')) {
  233. return $path === $current;
  234. }
  235. $path = str_replace(['*', '/'], ['([0-9a-z-_,])*', "\/"], $path);
  236. return preg_match("/$path/i", $current);
  237. }
  238. /**
  239. * 生成层级数据.
  240. *
  241. * @param array $nodes
  242. * @param int $parentId
  243. * @param string|null $primaryKeyName
  244. * @param string|null $parentKeyName
  245. * @param string|null $childrenKeyName
  246. *
  247. * @return array
  248. */
  249. public static function buildNestedArray(
  250. $nodes = [],
  251. $parentId = 0,
  252. ?string $primaryKeyName = null,
  253. ?string $parentKeyName = null,
  254. ?string $childrenKeyName = null
  255. ) {
  256. $branch = [];
  257. $primaryKeyName = $primaryKeyName ?: 'id';
  258. $parentKeyName = $parentKeyName ?: 'parent_id';
  259. $childrenKeyName = $childrenKeyName ?: 'children';
  260. $parentId = is_numeric($parentId) ? (int) $parentId : $parentId;
  261. foreach ($nodes as $node) {
  262. $pk = $node[$parentKeyName];
  263. $pk = is_numeric($pk) ? (int) $pk : $pk;
  264. if ($pk === $parentId) {
  265. $children = static::buildNestedArray(
  266. $nodes,
  267. $node[$primaryKeyName],
  268. $primaryKeyName,
  269. $parentKeyName,
  270. $childrenKeyName
  271. );
  272. if ($children) {
  273. $node[$childrenKeyName] = $children;
  274. }
  275. $branch[] = $node;
  276. }
  277. }
  278. return $branch;
  279. }
  280. /**
  281. * @param string $name
  282. * @param string $symbol
  283. *
  284. * @return mixed
  285. */
  286. public static function slug(string $name, string $symbol = '-')
  287. {
  288. $text = preg_replace_callback('/([A-Z])/', function ($text) use ($symbol) {
  289. return $symbol.strtolower($text[1]);
  290. }, $name);
  291. return str_replace('_', $symbol, ltrim($text, $symbol));
  292. }
  293. /**
  294. * @param array $array
  295. * @param int $level
  296. *
  297. * @return string
  298. */
  299. public static function exportArray(array &$array, $level = 1)
  300. {
  301. $start = '[';
  302. $end = ']';
  303. $txt = "$start\n";
  304. foreach ($array as $k => &$v) {
  305. if (is_array($v)) {
  306. $pre = is_string($k) ? "'$k' => " : "$k => ";
  307. $txt .= str_repeat(' ', $level * 4).$pre.static::exportArray($v, $level + 1).",\n";
  308. continue;
  309. }
  310. $t = $v;
  311. if ($v === true) {
  312. $t = 'true';
  313. } elseif ($v === false) {
  314. $t = 'false';
  315. } elseif ($v === null) {
  316. $t = 'null';
  317. } elseif (is_string($v)) {
  318. $v = str_replace("'", "\\'", $v);
  319. $t = "'$v'";
  320. }
  321. $pre = is_string($k) ? "'$k' => " : "$k => ";
  322. $txt .= str_repeat(' ', $level * 4)."{$pre}{$t},\n";
  323. }
  324. return $txt.str_repeat(' ', ($level - 1) * 4).$end;
  325. }
  326. /**
  327. * @param array $array
  328. *
  329. * @return string
  330. */
  331. public static function exportArrayPhp(array $array)
  332. {
  333. return "<?php \nreturn ".static::exportArray($array).";\n";
  334. }
  335. /**
  336. * 删除数组中的元素.
  337. *
  338. * @param array $array
  339. * @param mixed $value
  340. * @param bool $strict
  341. */
  342. public static function deleteByValue(&$array, $value, bool $strict = false)
  343. {
  344. $value = (array) $value;
  345. foreach ($array as $index => $item) {
  346. if (in_array($item, $value, $strict)) {
  347. unset($array[$index]);
  348. }
  349. }
  350. }
  351. /**
  352. * 颜色转亮.
  353. *
  354. * @param string $color
  355. * @param int $amt
  356. *
  357. * @return string
  358. */
  359. public static function colorLighten(string $color, int $amt)
  360. {
  361. if (! $amt) {
  362. return $color;
  363. }
  364. $hasPrefix = false;
  365. if (mb_strpos($color, '#') === 0) {
  366. $color = mb_substr($color, 1);
  367. $hasPrefix = true;
  368. }
  369. [$red, $blue, $green] = static::colorToRBG($color, $amt);
  370. return ($hasPrefix ? '#' : '').dechex($green + ($blue << 8) + ($red << 16));
  371. }
  372. /**
  373. * 颜色转暗.
  374. *
  375. * @param string $color
  376. * @param int $amt
  377. *
  378. * @return string
  379. */
  380. public static function colorDarken(string $color, int $amt)
  381. {
  382. return static::colorLighten($color, -$amt);
  383. }
  384. /**
  385. * 颜色透明度.
  386. *
  387. * @param string $color
  388. * @param float|string $alpha
  389. *
  390. * @return string
  391. */
  392. public static function colorAlpha(string $color, $alpha)
  393. {
  394. if ($alpha >= 1) {
  395. return $color;
  396. }
  397. if (mb_strpos($color, '#') === 0) {
  398. $color = mb_substr($color, 1);
  399. }
  400. [$red, $blue, $green] = static::colorToRBG($color);
  401. return "rgba($red, $blue, $green, $alpha)";
  402. }
  403. /**
  404. * @param string $color
  405. * @param int $amt
  406. *
  407. * @return array
  408. */
  409. public static function colorToRBG(string $color, int $amt = 0)
  410. {
  411. $format = function ($value) {
  412. if ($value > 255) {
  413. return 255;
  414. }
  415. if ($value < 0) {
  416. return 0;
  417. }
  418. return $value;
  419. };
  420. $num = hexdec($color);
  421. $red = $format(($num >> 16) + $amt);
  422. $blue = $format((($num >> 8) & 0x00FF) + $amt);
  423. $green = $format(($num & 0x0000FF) + $amt);
  424. return [$red, $blue, $green];
  425. }
  426. /**
  427. * 验证扩展包名称.
  428. *
  429. * @param string $name
  430. *
  431. * @return int
  432. */
  433. public static function validateExtensionName($name)
  434. {
  435. return preg_match('/^[\w\-_]+\/[\w\-_]+$/', $name);
  436. }
  437. /**
  438. * Get file icon.
  439. *
  440. * @param string $file
  441. *
  442. * @return string
  443. */
  444. public static function getFileIcon($file = '')
  445. {
  446. $extension = File::extension($file);
  447. foreach (static::$fileTypes as $type => $regex) {
  448. if (preg_match("/^($regex)$/i", $extension) !== 0) {
  449. return "fa fa-file-{$type}-o";
  450. }
  451. }
  452. return 'fa fa-file-o';
  453. }
  454. /**
  455. * 判断是否是ajax请求.
  456. *
  457. * @param Request $request
  458. *
  459. * @return bool
  460. */
  461. public static function isAjaxRequest(?Request $request = null)
  462. {
  463. /* @var Request $request */
  464. $request = $request ?: request();
  465. return $request->ajax() && ! $request->pjax();
  466. }
  467. /**
  468. * 判断是否是IE浏览器.
  469. *
  470. * @return false|int
  471. */
  472. public static function isIEBrowser()
  473. {
  474. return (bool) preg_match('/Mozilla\/5\.0 \(Windows NT 10\.0; WOW64; Trident\/7\.0; rv:[0-9\.]*\) like Gecko/i', $_SERVER['HTTP_USER_AGENT'] ?? '');
  475. }
  476. /**
  477. * 判断是否QQ浏览器.
  478. *
  479. * @return bool
  480. */
  481. public static function isQQBrowser()
  482. {
  483. return mb_strpos(mb_strtolower($_SERVER['HTTP_USER_AGENT'] ?? ''), 'qqbrowser') !== false;
  484. }
  485. /**
  486. * @param string $url
  487. *
  488. * @return void
  489. */
  490. public static function setPreviousUrl($url)
  491. {
  492. session()->flash('admin.prev.url', static::urlWithoutQuery((string) $url, '_pjax'));
  493. }
  494. /**
  495. * @return string
  496. */
  497. public static function getPreviousUrl()
  498. {
  499. return (string) (session()->get('admin.prev.url') ? url(session()->get('admin.prev.url')) : url()->previous());
  500. }
  501. /**
  502. * @param mixed $command
  503. * @param int $timeout
  504. * @param null $input
  505. * @param null $cwd
  506. *
  507. * @return Process
  508. */
  509. public static function process($command, $timeout = 100, $input = null, $cwd = null)
  510. {
  511. $parameters = [
  512. $command,
  513. $cwd,
  514. [],
  515. $input,
  516. $timeout,
  517. ];
  518. return is_string($command)
  519. ? Process::fromShellCommandline(...$parameters)
  520. : new Process(...$parameters);
  521. }
  522. /**
  523. * 判断两个值是否相等.
  524. *
  525. * @param $value1
  526. * @param $value2
  527. *
  528. * @return bool
  529. */
  530. public static function equal($value1, $value2)
  531. {
  532. if ($value1 === null || $value2 === null) {
  533. return false;
  534. }
  535. if (! is_scalar($value1) || ! is_scalar($value2)) {
  536. return $value1 === $value2;
  537. }
  538. return (string) $value1 === (string) $value2;
  539. }
  540. /**
  541. * 判断给定的数组是是否包含给定元素.
  542. *
  543. * @param mixed $value
  544. * @param array $array
  545. *
  546. * @return bool
  547. */
  548. public static function inArray($value, array $array)
  549. {
  550. $array = array_map(function ($v) {
  551. if (is_scalar($v) || $v === null) {
  552. $v = (string) $v;
  553. }
  554. return $v;
  555. }, $array);
  556. return in_array((string) $value, $array, true);
  557. }
  558. /**
  559. * Limit the number of characters in a string.
  560. *
  561. * @param string $value
  562. * @param int $limit
  563. * @param string $end
  564. * @return string
  565. */
  566. public static function strLimit($value, $limit = 100, $end = '...')
  567. {
  568. if (mb_strlen($value, 'UTF-8') <= $limit) {
  569. return $value;
  570. }
  571. return rtrim(mb_substr($value, 0, $limit, 'UTF-8')).$end;
  572. }
  573. /**
  574. * 获取类名或对象的文件路径.
  575. *
  576. * @param string|object $class
  577. *
  578. * @return string
  579. *
  580. * @throws \ReflectionException
  581. */
  582. public static function guessClassFileName($class)
  583. {
  584. if (is_object($class)) {
  585. $class = get_class($class);
  586. }
  587. try {
  588. if (class_exists($class)) {
  589. return (new \ReflectionClass($class))->getFileName();
  590. }
  591. } catch (\Throwable $e) {
  592. }
  593. $class = trim($class, '\\');
  594. $composer = Composer::parse(base_path('composer.json'));
  595. $map = collect($composer->autoload['psr-4'] ?? [])->mapWithKeys(function ($path, $namespace) {
  596. $namespace = trim($namespace, '\\').'\\';
  597. return [$namespace => [$namespace, $path]];
  598. })->sortBy(function ($_, $namespace) {
  599. return strlen($namespace);
  600. }, SORT_REGULAR, true);
  601. $prefix = explode($class, '\\')[0];
  602. if ($map->isEmpty()) {
  603. if (Str::startsWith($class, 'App\\')) {
  604. $values = ['App\\', 'app/'];
  605. }
  606. } else {
  607. $values = $map->filter(function ($_, $k) use ($class) {
  608. return Str::startsWith($class, $k);
  609. })->first();
  610. }
  611. if (empty($values)) {
  612. $values = [$prefix.'\\', self::slug($prefix).'/'];
  613. }
  614. [$namespace, $path] = $values;
  615. return base_path(str_replace([$namespace, '\\'], [$path, '/'], $class)).'.php';
  616. }
  617. /**
  618. * Is input data is has-one relation.
  619. *
  620. * @param Collection $fields
  621. * @param array $input
  622. */
  623. public static function prepareHasOneRelation(Collection $fields, array &$input)
  624. {
  625. $relations = [];
  626. $fields->each(function ($field) use (&$relations) {
  627. $column = $field->column();
  628. if (is_array($column)) {
  629. foreach ($column as $v) {
  630. if (Str::contains($v, '.')) {
  631. $first = explode('.', $v)[0];
  632. $relations[$first] = null;
  633. }
  634. }
  635. return;
  636. }
  637. if (Str::contains($column, '.')) {
  638. $first = explode('.', $column)[0];
  639. $relations[$first] = null;
  640. }
  641. });
  642. foreach ($relations as $first => $v) {
  643. if (isset($input[$first])) {
  644. foreach ($input[$first] as $key => $value) {
  645. if (is_array($value)) {
  646. $input["$first.$key"] = $value;
  647. }
  648. }
  649. $input = array_merge($input, Arr::dot([$first => $input[$first]]));
  650. }
  651. }
  652. }
  653. /**
  654. * 设置查询条件.
  655. *
  656. * @param mixed $model
  657. * @param string $column
  658. * @param string $query
  659. * @param mixed array $params
  660. *
  661. * @return void
  662. */
  663. public static function withQueryCondition($model, ?string $column, string $query, array $params)
  664. {
  665. if (! Str::contains($column, '.')) {
  666. $model->$query($column, ...$params);
  667. return;
  668. }
  669. $method = $query === 'orWhere' ? 'orWhere' : 'where';
  670. $subQuery = $query === 'orWhere' ? 'where' : $query;
  671. $model->$method(function ($q) use ($column, $subQuery, $params) {
  672. static::withRelationQuery($q, $column, $subQuery, $params);
  673. });
  674. }
  675. /**
  676. * 设置关联关系查询条件.
  677. *
  678. * @param mixed $model
  679. * @param string $column
  680. * @param string $query
  681. * @param mixed ...$params
  682. *
  683. * @return void
  684. */
  685. public static function withRelationQuery($model, ?string $column, string $query, array $params)
  686. {
  687. $column = explode('.', $column);
  688. array_unshift($params, array_pop($column));
  689. // 增加对whereHasIn的支持
  690. $method = class_exists(WhereHasInServiceProvider::class) ? 'whereHasIn' : 'whereHas';
  691. $model->$method(implode('.', $column), function ($relation) use ($params, $query) {
  692. $relation->$query(...$params);
  693. });
  694. }
  695. /**
  696. * Html转义.
  697. *
  698. * @param array|string $item
  699. *
  700. * @return mixed
  701. */
  702. public static function htmlEntityEncode($item)
  703. {
  704. if (is_object($item)) {
  705. return $item;
  706. }
  707. if (is_array($item)) {
  708. array_walk_recursive($item, function (&$value) {
  709. $value = htmlentities($value);
  710. });
  711. } else {
  712. $item = htmlentities($item);
  713. }
  714. return $item;
  715. }
  716. /**
  717. * 格式化表单元素 name 属性.
  718. *
  719. * @param string|array $name
  720. *
  721. * @return mixed|string
  722. */
  723. public static function formatElementName($name)
  724. {
  725. if (! $name) {
  726. return $name;
  727. }
  728. if (is_array($name)) {
  729. foreach ($name as &$v) {
  730. $v = static::formatElementName($v);
  731. }
  732. return $name;
  733. }
  734. $name = explode('.', $name);
  735. if (count($name) == 1) {
  736. return $name[0];
  737. }
  738. $html = array_shift($name);
  739. foreach ($name as $piece) {
  740. $html .= "[$piece]";
  741. }
  742. return $html;
  743. }
  744. /**
  745. * Set an array item to a given value using "dot" notation.
  746. *
  747. * If no key is given to the method, the entire array will be replaced.
  748. *
  749. * @param array|\ArrayAccess $array
  750. * @param string $key
  751. * @param mixed $value
  752. * @return array
  753. */
  754. public static function arraySet(&$array, $key, $value)
  755. {
  756. if (is_null($key)) {
  757. return $array = $value;
  758. }
  759. $keys = explode('.', $key);
  760. $default = null;
  761. while (count($keys) > 1) {
  762. $key = array_shift($keys);
  763. if (! isset($array[$key]) || (! is_array($array[$key]) && ! $array[$key] instanceof \ArrayAccess)) {
  764. $array[$key] = [];
  765. }
  766. if (is_array($array)) {
  767. $array = &$array[$key];
  768. } else {
  769. if (is_object($array[$key])) {
  770. $array[$key] = static::arraySet($array[$key], implode('.', $keys), $value);
  771. } else {
  772. $mid = $array[$key];
  773. $array[$key] = static::arraySet($mid, implode('.', $keys), $value);
  774. }
  775. }
  776. }
  777. $array[array_shift($keys)] = $value;
  778. return $array;
  779. }
  780. /**
  781. * 把下划线风格字段名转化为驼峰风格.
  782. *
  783. * @param array $array
  784. *
  785. * @return array
  786. */
  787. public static function camelArray(array &$array)
  788. {
  789. foreach ($array as $k => $v) {
  790. if (is_array($v)) {
  791. Helper::camelArray($v);
  792. }
  793. $array[Str::camel($k)] = $v;
  794. }
  795. return $array;
  796. }
  797. /**
  798. * 获取文件名称.
  799. *
  800. * @param string $name
  801. *
  802. * @return array|mixed
  803. */
  804. public static function basename($name)
  805. {
  806. if (! $name) {
  807. return $name;
  808. }
  809. return last(explode('/', $name));
  810. }
  811. /**
  812. * @param string|int $key
  813. * @param array|object $arrayOrObject
  814. *
  815. * @return bool
  816. */
  817. public static function keyExists($key, $arrayOrObject)
  818. {
  819. if (is_object($arrayOrObject)) {
  820. $arrayOrObject = static::array($arrayOrObject, false);
  821. }
  822. return array_key_exists($key, $arrayOrObject);
  823. }
  824. }