Dot.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace AdminAddonUserManager;
  3. /**
  4. * Class Dot
  5. *
  6. * @package SelvinOrtiz\Dot
  7. *
  8. * https://github.com/selvinortiz/dot
  9. */
  10. class Dot
  11. {
  12. /**
  13. * Returns whether or not the $key exists within $arr
  14. *
  15. * @param array $arr
  16. * @param string $key
  17. *
  18. * @return bool
  19. */
  20. public static function has($arr, $key)
  21. {
  22. if (strpos($key, '.') !== false && count(($keys = explode('.', $key)))) {
  23. foreach ($keys as $key) {
  24. if (!array_key_exists($key, $arr)) {
  25. return false;
  26. }
  27. $arr = $arr[$key];
  28. }
  29. return true;
  30. }
  31. return array_key_exists($key, $arr);
  32. }
  33. /**
  34. * Returns he value of $key if found in $arr or $default
  35. *
  36. * @param array $arr
  37. * @param string $key
  38. * @param null|mixed $default
  39. *
  40. * @return mixed
  41. */
  42. public static function get($arr, $key, $default = null)
  43. {
  44. if (strpos($key, '.') !== false && count(($keys = explode('.', $key)))) {
  45. foreach ($keys as $key) {
  46. if (!array_key_exists($key, $arr)) {
  47. return $default;
  48. }
  49. $arr = $arr[$key];
  50. }
  51. return $arr;
  52. }
  53. return array_key_exists($key, $arr) ? $arr[$key] : $default;
  54. }
  55. /**
  56. * Sets the $value identified by $key inside $arr
  57. *
  58. * @param array &$arr
  59. * @param string $key
  60. * @param mixed $value
  61. */
  62. public static function set(array &$arr, $key, $value)
  63. {
  64. if (strpos($key, '.') !== false && ($keys = explode('.', $key)) && count($keys)) {
  65. while (count($keys) > 1) {
  66. $key = array_shift($keys);
  67. if (!isset($arr[$key]) || !is_array($arr[$key])) {
  68. $arr[$key] = [];
  69. }
  70. $arr = &$arr[$key];
  71. }
  72. $arr[array_shift($keys)] = $value;
  73. } else {
  74. $arr[$key] = $value;
  75. }
  76. }
  77. /**
  78. * Deletes a $key and its value from the $arr
  79. *
  80. * @param array &$arr
  81. * @param string $key
  82. */
  83. public static function delete(array &$arr, $key)
  84. {
  85. if (strpos($key, '.') !== false && ($keys = explode('.', $key)) && count($keys)) {
  86. while (count($keys) > 1) {
  87. $arr = &$arr[array_shift($keys)];
  88. }
  89. unset($arr[array_shift($keys)]);
  90. } else {
  91. unset($arr[$key]);
  92. }
  93. }
  94. }