Browse Source

added ArrayHelper::map()

Fabian Peter Hammerle 7 years ago
parent
commit
6454349403
2 changed files with 58 additions and 0 deletions
  1. 14 0
      ArrayHelper.php
  2. 44 0
      tests/ArrayHelperTest.php

+ 14 - 0
ArrayHelper.php

@@ -15,6 +15,20 @@ class ArrayHelper
             );
     }
 
+    /**
+     * @param mixed $source_array
+     * @param \Closure $callback
+     * @return mixed
+     */
+   public static function map($source, \Closure $callback)
+   {
+       if(is_array($source)) {
+           return array_map($callback, $source);
+       } else {
+           return $callback($source);
+       }
+   }
+
     /**
      * @param array $source_array
      * @param \Closure $callback

+ 44 - 0
tests/ArrayHelperTest.php

@@ -92,6 +92,50 @@ class ArrayHelperTest extends \PHPUnit_Framework_TestCase
             );
     }
 
+    public function mapProvider()
+    {
+        return [
+            [
+                null,
+                function($v) { return 1; },
+                1,
+                ],
+            [
+                'string',
+                function($v) { return strrev($v); },
+                'gnirts',
+                ],
+            [
+                ['a' => 1, 'b' => 2, 'c' => 3],
+                function($v) { return $v; },
+                ['a' => 1, 'b' => 2, 'c' => 3],
+                ],
+            [
+                ['a' => 1, 'b' => 2, 'c' => 3],
+                function($v) { return $v < 2 ? null : $v; },
+                ['a' => null, 'b' => 2, 'c' => 3],
+                ],
+            [
+                ['a' => 1, 'b' => null, 'c' => 3],
+                function($v) { return $v; },
+                ['a' => 1, 'b' => null, 'c' => 3],
+                ],
+            [
+                ['a' => 1, 'b' => 2, 'b' => 3],
+                function($v) { return $v * $v; },
+                ['a' => 1, 'b' => 4, 'b' => 9],
+                ],
+            ];
+    }
+
+    /**
+     * @dataProvider mapProvider
+     */
+    public function testMap($source, $callback, $expected)
+    {
+        $this->assertSame($expected, ArrayHelper::map($source, $callback));
+    }
+
     public function multimapProvider()
     {
         return [