Helpers.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. /*
  8. * This file is part of the overtrue/wechat.
  9. *
  10. * (c) overtrue <i@overtrue.me>
  11. *
  12. * This source file is subject to the MIT license that is bundled
  13. * with this source code in the file LICENSE.
  14. */
  15. namespace ByteDance\Kernel;
  16. use ByteDance\Kernel\Contracts\Arrayable;
  17. use ByteDance\Kernel\Exceptions\RuntimeException;
  18. use ByteDance\Kernel\Support\Arr;
  19. use ByteDance\Kernel\Support\Collection;
  20. function data_get($data, $key, $default = null)
  21. {
  22. switch (true) {
  23. case is_array($data):
  24. return Arr::get($data, $key, $default);
  25. case $data instanceof Collection:
  26. return $data->get($key, $default);
  27. case $data instanceof Arrayable:
  28. return Arr::get($data->toArray(), $key, $default);
  29. case $data instanceof \ArrayIterator:
  30. return $data->getArrayCopy()[$key] ?? $default;
  31. case $data instanceof \ArrayAccess:
  32. return $data[$key] ?? $default;
  33. case $data instanceof \IteratorAggregate && $data->getIterator() instanceof \ArrayIterator:
  34. return $data->getIterator()->getArrayCopy()[$key] ?? $default;
  35. default:
  36. throw new RuntimeException(sprintf('Can\'t access data with key "%s"', $key));
  37. }
  38. }
  39. function data_to_array($data)
  40. {
  41. switch (true) {
  42. case is_array($data):
  43. return $data;
  44. case $data instanceof Collection:
  45. return $data->all();
  46. case $data instanceof Arrayable:
  47. return $data->toArray();
  48. case $data instanceof \IteratorAggregate && $data->getIterator() instanceof \ArrayIterator:
  49. return $data->getIterator()->getArrayCopy();
  50. case $data instanceof \ArrayIterator:
  51. return $data->getArrayCopy();
  52. default:
  53. throw new RuntimeException(sprintf('Can\'t transform data to array'));
  54. }
  55. }