Functions.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. use Hyperf\Utils\ApplicationContext;
  12. use Hyperf\Utils\Arr;
  13. use Hyperf\Utils\Backoff;
  14. use Hyperf\Utils\Collection;
  15. use Hyperf\Utils\Coroutine;
  16. use Hyperf\Utils\HigherOrderTapProxy;
  17. use Hyperf\Utils\Optional;
  18. use Hyperf\Utils\Parallel;
  19. use Hyperf\Utils\Str;
  20. use Hyperf\Utils\Waiter;
  21. if (! function_exists('value')) {
  22. /**
  23. * Return the default value of the given value.
  24. *
  25. * @param mixed $value
  26. */
  27. function value($value, ...$args)
  28. {
  29. return $value instanceof Closure ? $value(...$args) : $value;
  30. }
  31. }
  32. if (! function_exists('env')) {
  33. /**
  34. * Gets the value of an environment variable.
  35. *
  36. * @param string $key
  37. * @param null|mixed $default
  38. */
  39. function env($key, $default = null)
  40. {
  41. $value = getenv($key);
  42. if ($value === false) {
  43. return value($default);
  44. }
  45. switch (strtolower($value)) {
  46. case 'true':
  47. case '(true)':
  48. return true;
  49. case 'false':
  50. case '(false)':
  51. return false;
  52. case 'empty':
  53. case '(empty)':
  54. return '';
  55. case 'null':
  56. case '(null)':
  57. return;
  58. }
  59. if (($valueLength = strlen($value)) > 1 && $value[0] === '"' && $value[$valueLength - 1] === '"') {
  60. return substr($value, 1, -1);
  61. }
  62. return $value;
  63. }
  64. }
  65. if (! function_exists('retry')) {
  66. /**
  67. * Retry an operation a given number of times.
  68. *
  69. * @param float|int $times
  70. * @param int $sleep millisecond
  71. * @throws \Throwable
  72. */
  73. function retry($times, callable $callback, int $sleep = 0)
  74. {
  75. $attempts = 0;
  76. $backoff = new Backoff($sleep);
  77. beginning:
  78. try {
  79. return $callback(++$attempts);
  80. } catch (\Throwable $e) {
  81. if (--$times < 0) {
  82. throw $e;
  83. }
  84. $backoff->sleep();
  85. goto beginning;
  86. }
  87. }
  88. }
  89. if (! function_exists('with')) {
  90. /**
  91. * Return the given value, optionally passed through the given callback.
  92. *
  93. * @param mixed $value
  94. */
  95. function with($value, callable $callback = null)
  96. {
  97. return is_null($callback) ? $value : $callback($value);
  98. }
  99. }
  100. if (! function_exists('collect')) {
  101. /**
  102. * Create a collection from the given value.
  103. *
  104. * @param null|mixed $value
  105. * @return Collection
  106. */
  107. function collect($value = null)
  108. {
  109. return new Collection($value);
  110. }
  111. }
  112. if (! function_exists('data_fill')) {
  113. /**
  114. * Fill in data where it's missing.
  115. *
  116. * @param mixed $target
  117. * @param array|string $key
  118. * @param mixed $value
  119. */
  120. function data_fill(&$target, $key, $value)
  121. {
  122. return data_set($target, $key, $value, false);
  123. }
  124. }
  125. if (! function_exists('data_get')) {
  126. /**
  127. * Get an item from an array or object using "dot" notation.
  128. *
  129. * @param null|array|int|string $key
  130. * @param null|mixed $default
  131. * @param mixed $target
  132. */
  133. function data_get($target, $key, $default = null)
  134. {
  135. if (is_null($key)) {
  136. return $target;
  137. }
  138. $key = is_array($key) ? $key : explode('.', is_int($key) ? (string) $key : $key);
  139. while (! is_null($segment = array_shift($key))) {
  140. if ($segment === '*') {
  141. if ($target instanceof Collection) {
  142. $target = $target->all();
  143. } elseif (! is_array($target)) {
  144. return value($default);
  145. }
  146. $result = [];
  147. foreach ($target as $item) {
  148. $result[] = data_get($item, $key);
  149. }
  150. return in_array('*', $key) ? Arr::collapse($result) : $result;
  151. }
  152. if (Arr::accessible($target) && Arr::exists($target, $segment)) {
  153. $target = $target[$segment];
  154. } elseif (is_object($target) && isset($target->{$segment})) {
  155. $target = $target->{$segment};
  156. } else {
  157. return value($default);
  158. }
  159. }
  160. return $target;
  161. }
  162. }
  163. if (! function_exists('data_set')) {
  164. /**
  165. * Set an item on an array or object using dot notation.
  166. *
  167. * @param mixed $target
  168. * @param array|string $key
  169. * @param bool $overwrite
  170. * @param mixed $value
  171. */
  172. function data_set(&$target, $key, $value, $overwrite = true)
  173. {
  174. $segments = is_array($key) ? $key : explode('.', $key);
  175. if (($segment = array_shift($segments)) === '*') {
  176. if (! Arr::accessible($target)) {
  177. $target = [];
  178. }
  179. if ($segments) {
  180. foreach ($target as &$inner) {
  181. data_set($inner, $segments, $value, $overwrite);
  182. }
  183. } elseif ($overwrite) {
  184. foreach ($target as &$inner) {
  185. $inner = $value;
  186. }
  187. }
  188. } elseif (Arr::accessible($target)) {
  189. if ($segments) {
  190. if (! Arr::exists($target, $segment)) {
  191. $target[$segment] = [];
  192. }
  193. data_set($target[$segment], $segments, $value, $overwrite);
  194. } elseif ($overwrite || ! Arr::exists($target, $segment)) {
  195. $target[$segment] = $value;
  196. }
  197. } elseif (is_object($target)) {
  198. if ($segments) {
  199. if (! isset($target->{$segment})) {
  200. $target->{$segment} = [];
  201. }
  202. data_set($target->{$segment}, $segments, $value, $overwrite);
  203. } elseif ($overwrite || ! isset($target->{$segment})) {
  204. $target->{$segment} = $value;
  205. }
  206. } else {
  207. $target = [];
  208. if ($segments) {
  209. $target[$segment] = [];
  210. data_set($target[$segment], $segments, $value, $overwrite);
  211. } elseif ($overwrite) {
  212. $target[$segment] = $value;
  213. }
  214. }
  215. return $target;
  216. }
  217. }
  218. if (! function_exists('head')) {
  219. /**
  220. * Get the first element of an array. Useful for method chaining.
  221. *
  222. * @param array $array
  223. */
  224. function head($array)
  225. {
  226. return reset($array);
  227. }
  228. }
  229. if (! function_exists('last')) {
  230. /**
  231. * Get the last element from an array.
  232. *
  233. * @param array $array
  234. */
  235. function last($array)
  236. {
  237. return end($array);
  238. }
  239. }
  240. if (! function_exists('tap')) {
  241. /**
  242. * Call the given Closure with the given value then return the value.
  243. *
  244. * @param null|callable $callback
  245. * @param mixed $value
  246. */
  247. function tap($value, $callback = null)
  248. {
  249. if (is_null($callback)) {
  250. return new HigherOrderTapProxy($value);
  251. }
  252. $callback($value);
  253. return $value;
  254. }
  255. }
  256. if (! function_exists('call')) {
  257. /**
  258. * Call a callback with the arguments.
  259. *
  260. * @param mixed $callback
  261. * @return null|mixed
  262. */
  263. function call($callback, array $args = [])
  264. {
  265. $result = null;
  266. if ($callback instanceof \Closure) {
  267. $result = $callback(...$args);
  268. } elseif (is_object($callback) || (is_string($callback) && function_exists($callback))) {
  269. $result = $callback(...$args);
  270. } elseif (is_array($callback)) {
  271. [$object, $method] = $callback;
  272. $result = is_object($object) ? $object->{$method}(...$args) : $object::$method(...$args);
  273. } else {
  274. $result = call_user_func_array($callback, $args);
  275. }
  276. return $result;
  277. }
  278. }
  279. if (! function_exists('go')) {
  280. /**
  281. * @return bool|int
  282. */
  283. function go(callable $callable)
  284. {
  285. $id = Coroutine::create($callable);
  286. return $id > 0 ? $id : false;
  287. }
  288. }
  289. if (! function_exists('co')) {
  290. /**
  291. * @return bool|int
  292. */
  293. function co(callable $callable)
  294. {
  295. $id = Coroutine::create($callable);
  296. return $id > 0 ? $id : false;
  297. }
  298. }
  299. if (! function_exists('defer')) {
  300. function defer(callable $callable): void
  301. {
  302. Coroutine::defer($callable);
  303. }
  304. }
  305. if (! function_exists('class_basename')) {
  306. /**
  307. * Get the class "basename" of the given object / class.
  308. *
  309. * @param object|string $class
  310. * @return string
  311. */
  312. function class_basename($class)
  313. {
  314. $class = is_object($class) ? get_class($class) : $class;
  315. return basename(str_replace('\\', '/', $class));
  316. }
  317. }
  318. if (! function_exists('trait_uses_recursive')) {
  319. /**
  320. * Returns all traits used by a trait and its traits.
  321. *
  322. * @param string $trait
  323. * @return array
  324. */
  325. function trait_uses_recursive($trait)
  326. {
  327. $traits = class_uses($trait);
  328. foreach ($traits as $trait) {
  329. $traits += trait_uses_recursive($trait);
  330. }
  331. return $traits;
  332. }
  333. }
  334. if (! function_exists('class_uses_recursive')) {
  335. /**
  336. * Returns all traits used by a class, its parent classes and trait of their traits.
  337. *
  338. * @param object|string $class
  339. * @return array
  340. */
  341. function class_uses_recursive($class)
  342. {
  343. if (is_object($class)) {
  344. $class = get_class($class);
  345. }
  346. $results = [];
  347. /* @phpstan-ignore-next-line */
  348. foreach (array_reverse(class_parents($class)) + [$class => $class] as $class) {
  349. $results += trait_uses_recursive($class);
  350. }
  351. return array_unique($results);
  352. }
  353. }
  354. if (! function_exists('setter')) {
  355. /**
  356. * Create a setter string.
  357. */
  358. function setter(string $property): string
  359. {
  360. return 'set' . Str::studly($property);
  361. }
  362. }
  363. if (! function_exists('getter')) {
  364. /**
  365. * Create a getter string.
  366. */
  367. function getter(string $property): string
  368. {
  369. return 'get' . Str::studly($property);
  370. }
  371. }
  372. if (! function_exists('parallel')) {
  373. /**
  374. * @param callable[] $callables
  375. * @param int $concurrent if $concurrent is equal to 0, that means unlimit
  376. */
  377. function parallel(array $callables, int $concurrent = 0)
  378. {
  379. $parallel = new Parallel($concurrent);
  380. foreach ($callables as $key => $callable) {
  381. $parallel->add($callable, $key);
  382. }
  383. return $parallel->wait();
  384. }
  385. }
  386. if (! function_exists('make')) {
  387. /**
  388. * Create an object instance, if the DI container exist in ApplicationContext,
  389. * then the object will be created by DI container via `make()` method, if not,
  390. * the object will create by `new` keyword.
  391. */
  392. function make(string $name, array $parameters = [])
  393. {
  394. if (ApplicationContext::hasContainer()) {
  395. $container = ApplicationContext::getContainer();
  396. if (method_exists($container, 'make')) {
  397. return $container->make($name, $parameters);
  398. }
  399. }
  400. $parameters = array_values($parameters);
  401. return new $name(...$parameters);
  402. }
  403. }
  404. if (! function_exists('run')) {
  405. /**
  406. * Run callable in non-coroutine environment, all hook functions by Swoole only available in the callable.
  407. *
  408. * @param array|callable $callbacks
  409. */
  410. function run($callbacks, int $flags = SWOOLE_HOOK_ALL): bool
  411. {
  412. if (Coroutine::inCoroutine()) {
  413. throw new RuntimeException('Function \'run\' only execute in non-coroutine environment.');
  414. }
  415. \Swoole\Runtime::enableCoroutine($flags);
  416. $result = \Swoole\Coroutine\Run(...(array) $callbacks);
  417. \Swoole\Runtime::enableCoroutine(false);
  418. return $result;
  419. }
  420. }
  421. if (! function_exists('swoole_hook_flags')) {
  422. /**
  423. * Return the default swoole hook flags, you can rewrite it by defining `SWOOLE_HOOK_FLAGS`.
  424. */
  425. function swoole_hook_flags(): int
  426. {
  427. return defined('SWOOLE_HOOK_FLAGS') ? SWOOLE_HOOK_FLAGS : SWOOLE_HOOK_ALL;
  428. }
  429. }
  430. if (! function_exists('optional')) {
  431. /**
  432. * Provide access to optional objects.
  433. *
  434. * @param mixed $value
  435. * @return mixed
  436. */
  437. function optional($value = null, callable $callback = null)
  438. {
  439. if (is_null($callback)) {
  440. return new Optional($value);
  441. }
  442. if (! is_null($value)) {
  443. return $callback($value);
  444. }
  445. }
  446. }
  447. if (! function_exists('wait')) {
  448. function wait(Closure $closure, ?float $timeout = null)
  449. {
  450. if (ApplicationContext::hasContainer()) {
  451. $waiter = ApplicationContext::getContainer()->get(Waiter::class);
  452. return $waiter->wait($closure, $timeout);
  453. }
  454. return (new Waiter())->wait($closure, $timeout);
  455. }
  456. }