ArrayHelper.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace fphammerle\helpers;
  3. class ArrayHelper
  4. {
  5. /**
  6. * @return array
  7. */
  8. public static function flatten(array $arr)
  9. {
  10. return iterator_to_array(
  11. new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr)),
  12. false
  13. );
  14. }
  15. /**
  16. * @param mixed $source_array
  17. * @param \Closure $callback
  18. * @return mixed
  19. */
  20. public static function map($source, \Closure $callback)
  21. {
  22. $callback_reflection = new \ReflectionFunction($callback);
  23. if($callback_reflection->getNumberOfRequiredParameters() == 1) {
  24. $mapper = function($k, $v) use ($callback) {
  25. return $callback($v);
  26. };
  27. } else {
  28. $mapper = $callback;
  29. }
  30. if(is_array($source)) {
  31. return self::multimap($source, function($k, $v) use ($mapper) {
  32. return [$k => $mapper($k, $v)];
  33. });
  34. } else {
  35. return $mapper(null, $source);
  36. }
  37. }
  38. /**
  39. * @param mixed $source_array
  40. * @param \Closure $callback
  41. * @return mixed
  42. */
  43. public static function mapIfSet($source, \Closure $callback)
  44. {
  45. if($source === null) {
  46. return null;
  47. } else {
  48. $callback_reflection = new \ReflectionFunction($callback);
  49. if($callback_reflection->getNumberOfRequiredParameters() == 1) {
  50. $mapper = function($k, $v) use ($callback) {
  51. return is_null($v) ? null : $callback($v);
  52. };
  53. } else {
  54. $mapper = function($k, $v) use ($callback) {
  55. return is_null($v) ? null : $callback($k, $v);
  56. };
  57. }
  58. return self::map($source, $mapper);
  59. }
  60. }
  61. /**
  62. * @param array $source_array
  63. * @param \Closure $callback
  64. * @return array
  65. */
  66. public static function multimap(array $source_array, \Closure $callback)
  67. {
  68. $mapped_array = [];
  69. foreach($source_array as $old_key => $old_value) {
  70. $pairs = $callback($old_key, $old_value);
  71. if($pairs === null) {
  72. // skip
  73. } elseif(is_array($pairs)) {
  74. foreach($pairs as $new_key => $new_pair) {
  75. $mapped_array[$new_key] = $new_pair;
  76. }
  77. } else {
  78. throw new \UnexpectedValueException(
  79. sprintf('expected array, %s given', gettype($pairs))
  80. );
  81. }
  82. }
  83. return $mapped_array;
  84. }
  85. }