Functions.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. namespace Hyperf\Support;
  12. use Carbon\Carbon;
  13. use Closure;
  14. use DateTimeZone;
  15. use Hyperf\Collection\Arr;
  16. use Hyperf\Context\ApplicationContext;
  17. use Hyperf\Di\Container;
  18. use Hyperf\Stringable\StrCache;
  19. use Hyperf\Support\Backoff\ArrayBackoff;
  20. use Throwable;
  21. /**
  22. * Return the default value of the given value.
  23. * @template TValue
  24. * @template TReturn
  25. *
  26. * @param (Closure(TValue):TReturn)|TValue $value
  27. * @return ($value is Closure ? TReturn : TValue)
  28. */
  29. function value(mixed $value, ...$args)
  30. {
  31. return $value instanceof Closure ? $value(...$args) : $value;
  32. }
  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 null;
  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. * Retry an operation a given number of times.
  66. *
  67. * @template TReturn
  68. *
  69. * @param float|int|int[] $times
  70. * @param callable(int):TReturn $callback
  71. * @param int $sleep millisecond
  72. * @return TReturn|void
  73. * @throws Throwable
  74. */
  75. function retry($times, callable $callback, int $sleep = 0)
  76. {
  77. $attempts = 0;
  78. if (is_array($times)) {
  79. $backoff = new ArrayBackoff($times);
  80. $times = count($times);
  81. } else {
  82. $backoff = new Backoff($sleep);
  83. }
  84. beginning:
  85. try {
  86. return $callback(++$attempts);
  87. } catch (Throwable $e) {
  88. if (--$times < 0) {
  89. throw $e;
  90. }
  91. $backoff->sleep();
  92. goto beginning;
  93. }
  94. }
  95. /**
  96. * Return the given value, optionally passed through the given callback.
  97. *
  98. * @template TValue
  99. * @template TReturn
  100. *
  101. * @param TValue $value
  102. * @param null|(callable(TValue):TReturn) $callback
  103. * @return ($callback is null ? TValue : TReturn)
  104. */
  105. function with($value, ?callable $callback = null)
  106. {
  107. return is_null($callback) ? $value : $callback($value);
  108. }
  109. /**
  110. * Call a callback with the arguments.
  111. *
  112. * @param mixed $callback
  113. * @return null|mixed
  114. */
  115. function call($callback, array $args = [])
  116. {
  117. $result = null;
  118. if ($callback instanceof Closure) {
  119. $result = $callback(...$args);
  120. } elseif (is_object($callback) || (is_string($callback) && function_exists($callback))) {
  121. $result = $callback(...$args);
  122. } elseif (is_array($callback)) {
  123. [$object, $method] = $callback;
  124. $result = is_object($object) ? $object->{$method}(...$args) : $object::$method(...$args);
  125. } else {
  126. $result = call_user_func_array($callback, $args);
  127. }
  128. return $result;
  129. }
  130. /**
  131. * Get the class "basename" of the given object / class.
  132. *
  133. * @param object|string $class
  134. * @return string
  135. */
  136. function class_basename($class)
  137. {
  138. $class = is_object($class) ? get_class($class) : $class;
  139. return basename(str_replace('\\', '/', $class));
  140. }
  141. /**
  142. * Returns all traits used by a trait and its traits.
  143. *
  144. * @param object|string $trait
  145. * @return array
  146. */
  147. function trait_uses_recursive($trait)
  148. {
  149. $traits = class_uses($trait);
  150. foreach ($traits as $trait) {
  151. $traits += trait_uses_recursive($trait);
  152. }
  153. return $traits;
  154. }
  155. /**
  156. * Returns all traits used by a class, its parent classes and trait of their traits.
  157. *
  158. * @param object|string $class
  159. * @return array
  160. */
  161. function class_uses_recursive($class)
  162. {
  163. if (is_object($class)) {
  164. $class = get_class($class);
  165. }
  166. $results = [];
  167. /* @phpstan-ignore-next-line */
  168. foreach (array_reverse(class_parents($class) ?: []) + [$class => $class] as $class) {
  169. $results += trait_uses_recursive($class);
  170. }
  171. return array_unique($results);
  172. }
  173. /**
  174. * Create a setter string.
  175. */
  176. function setter(string $property): string
  177. {
  178. return 'set' . StrCache::studly($property);
  179. }
  180. /**
  181. * Create a getter string.
  182. */
  183. function getter(string $property): string
  184. {
  185. return 'get' . StrCache::studly($property);
  186. }
  187. /**
  188. * Create an object instance, if the DI container exist in ApplicationContext,
  189. * then the object will be created by DI container via `make()` method, if not,
  190. * the object will create by `new` keyword.
  191. *
  192. * @template TClass
  193. *
  194. * @param class-string<TClass>|string $name
  195. * @return ($name is class-string<TClass> ? TClass : mixed)
  196. */
  197. function make(string $name, array $parameters = [])
  198. {
  199. if (ApplicationContext::hasContainer()) {
  200. /** @var Container $container */
  201. $container = ApplicationContext::getContainer();
  202. if (method_exists($container, 'make')) {
  203. return $container->make($name, $parameters);
  204. }
  205. }
  206. $parameters = array_values($parameters);
  207. return new $name(...$parameters);
  208. }
  209. /**
  210. * Return the default swoole hook flags, you can rewrite it by defining `SWOOLE_HOOK_FLAGS`.
  211. */
  212. function swoole_hook_flags(): int
  213. {
  214. return defined('SWOOLE_HOOK_FLAGS') ? SWOOLE_HOOK_FLAGS : SWOOLE_HOOK_ALL;
  215. }
  216. /**
  217. * Provide access to optional objects.
  218. * @template TValue
  219. * @template TReturn
  220. *
  221. * @param TValue $value
  222. * @param null|(callable(TValue):TReturn) $callback
  223. * @return ($callback is null ? Optional<TValue> : ($value is null ? null : TReturn))
  224. */
  225. function optional($value = null, ?callable $callback = null)
  226. {
  227. if (is_null($callback)) {
  228. return new Optional($value);
  229. }
  230. if (! is_null($value)) {
  231. return $callback($value);
  232. }
  233. return null;
  234. }
  235. /**
  236. * Build SQL contain bind.
  237. */
  238. function build_sql(string $sql, array $bindings = []): string
  239. {
  240. if (! Arr::isAssoc($bindings)) {
  241. $position = 0;
  242. foreach ($bindings as $value) {
  243. $position = strpos($sql, '?', $position);
  244. if ($position === false) {
  245. break;
  246. }
  247. $value = (string) match (gettype($value)) {
  248. 'integer', 'double' => $value,
  249. 'boolean' => (int) $value,
  250. default => sprintf("'%s'", $value),
  251. };
  252. $sql = substr_replace($sql, $value, $position, 1);
  253. $position += strlen($value);
  254. }
  255. }
  256. return $sql;
  257. }
  258. /**
  259. * Sleep milliseconds.
  260. */
  261. function msleep(int $milliSeconds): void
  262. {
  263. usleep($milliSeconds * 1000);
  264. }
  265. /**
  266. * Create a new Carbon instance for the current time.
  267. *
  268. * @param null|DateTimeZone|string $tz
  269. * @return Carbon
  270. */
  271. function now($tz = null)
  272. {
  273. return Carbon::now($tz);
  274. }
  275. /**
  276. * Create a new Carbon instance for the current date.
  277. *
  278. * @param null|DateTimeZone|string $tz
  279. * @return Carbon
  280. */
  281. function today($tz = null)
  282. {
  283. return Carbon::today($tz);
  284. }