Util.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is a part of dflydev/dot-access-data.
  5. *
  6. * (c) Dragonfly Development Inc.
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Dflydev\DotAccessData;
  12. class Util
  13. {
  14. /**
  15. * Test if array is an associative array
  16. *
  17. * Note that this function will return true if an array is empty. Meaning
  18. * empty arrays will be treated as if they are associative arrays.
  19. *
  20. * @param array<mixed> $arr
  21. *
  22. * @return bool
  23. *
  24. * @psalm-pure
  25. */
  26. public static function isAssoc(array $arr): bool
  27. {
  28. return !count($arr) || count(array_filter(array_keys($arr), 'is_string')) == count($arr);
  29. }
  30. /**
  31. * Merge contents from one associtative array to another
  32. *
  33. * @param mixed $to
  34. * @param mixed $from
  35. * @param DataInterface::PRESERVE|DataInterface::REPLACE|DataInterface::MERGE $mode
  36. *
  37. * @return mixed
  38. *
  39. * @psalm-pure
  40. */
  41. public static function mergeAssocArray($to, $from, int $mode = DataInterface::REPLACE)
  42. {
  43. if ($mode === DataInterface::MERGE && self::isList($to) && self::isList($from)) {
  44. return array_merge($to, $from);
  45. }
  46. if (is_array($from) && is_array($to)) {
  47. foreach ($from as $k => $v) {
  48. if (!isset($to[$k])) {
  49. $to[$k] = $v;
  50. } else {
  51. $to[$k] = self::mergeAssocArray($to[$k], $v, $mode);
  52. }
  53. }
  54. return $to;
  55. }
  56. return $mode === DataInterface::PRESERVE ? $to : $from;
  57. }
  58. /**
  59. * @param mixed $value
  60. *
  61. * @return bool
  62. *
  63. * @psalm-pure
  64. */
  65. private static function isList($value): bool
  66. {
  67. return is_array($value) && array_values($value) === $value;
  68. }
  69. }