Browse Source

Cleaning code and adding another test case

Jose Lorenzo Rodriguez 10 years ago
parent
commit
74bf9f0656
2 changed files with 33 additions and 6 deletions
  1. 32 5
      src/Collection/ExtractTrait.php
  2. 1 1
      tests/TestCase/Collection/CollectionTest.php

+ 32 - 5
src/Collection/ExtractTrait.php

@@ -37,16 +37,22 @@ trait ExtractTrait
         }
 
         $path = explode('.', $callback);
-        $callback = function ($element) use ($path) {
-            return $this->_extract($element, $path);
-        };
 
-        return $callback;
+        if (strpos($callback, '{n}') !== false) {
+            return function ($element) use ($path) {
+                return $this->_extract($element, $path);
+            };
+        }
+
+        return function ($element) use ($path) {
+            return $this->_simpleExtract($element, $path);
+        };
     }
 
     /**
      * Returns a column from $data that can be extracted
-     * by iterating over the column names contained in $path
+     * by iterating over the column names contained in $path.
+     * It will return arrays for elements in represented with `{n}`
      *
      * @param array|\ArrayAccess $data Data.
      * @param array $path Path to extract from.
@@ -84,6 +90,27 @@ trait ExtractTrait
     }
 
     /**
+     * Returns a column from $data that can be extracted
+     * by iterating over the column names contained in $path
+     *
+     * @param array|\ArrayAccess $data Data.
+     * @param array $path Path to extract from.
+     * @return mixed
+     */
+    protected function _simpleExtract($data, $path)
+    {
+        $value = null;
+        foreach ($path as $column) {
+            if (!isset($data[$column])) {
+                return null;
+            }
+            $value = $data[$column];
+            $data = $value;
+        }
+        return $value;
+    }
+
+    /**
      * Returns a callable that receives a value and will return whether or not
      * it matches certain condition.
      *

+ 1 - 1
tests/TestCase/Collection/CollectionTest.php

@@ -1425,7 +1425,7 @@ class CollectionTest extends TestCase
             ['not_comments' => []]
         ];
         $extracted = (new Collection($items))->extract('comments.{n}.voters.{n}.id');
-        $expected = [1, 2, 3, 4, 5, null];
+        $expected = [1, 2, 3, 4, 5, null, 6];
         $this->assertEquals($expected, $extracted->toList());
     }
 }