Permalink
Browse files

Added Collection:add.

  • Loading branch information...
1 parent 569e8cd commit 933bcdd0ad4753d72791374f53b9ce8c13f7a296 @hype- hype- committed Dec 13, 2012
@@ -181,4 +181,14 @@ public function sortWith($comparator);
* @return Collection
*/
public function sortBy($metric);
-}
+
+ /**
+ * Get a new Collection with given value and optionally key appended.
+ * Maintains index associations.
+ *
+ * @param mixed $value
+ * @param mixed $key
+ * @return Collection
+ */
+ public function add($value, $key = null);
+}
@@ -146,4 +146,20 @@ public function sortBy($metric)
{
return $this->apply(Functions::sortBy($metric));
}
-}
+
+ /**
+ * {@inheritdoc}
+ */
+ public function add($value, $key = null)
+ {
+ $results = $this->toArray();
+
+ if ($key === null) {
+ $results[] = $value;
+ } else {
+ $results[$key] = $value;
+ }
+
+ return static::create($results);
+ }
+}
@@ -176,4 +176,20 @@ public function merge(Collection $other)
{
return static::create(array_merge($this->_elements, $other->toArray()));
}
-}
+
+ /**
+ * {@inheritdoc}
+ */
+ public function add($value, $key = null)
+ {
+ $results = $this->toArray();
+
+ if ($key === null) {
+ $results[] = $value;
+ } else {
+ $results[$key] = $value;
+ }
+
+ return static::create($results);
+ }
+}
@@ -141,4 +141,12 @@ public function sortBy($metric)
{
return static::create($this->collection->sortBy($metric));
}
-}
+
+ /**
+ * {@inheritdoc}
+ */
+ public function add($value, $key = null)
+ {
+ return static::create($this->collection->add($value, $key));
+ }
+}
@@ -517,4 +517,59 @@ public function shouldBeAbleToSortByMetric($elements, $expected)
});
$this->assertEquals($expected, $result->toArray());
}
-}
+
+ /**
+ * @test
+ * @dataProvider addValue
+ *
+ * @param array $elements
+ * @param mixed $value
+ * @param array $expected
+ */
+ public function shouldBeAbleToAddValue(array $elements, $value, array $expected)
+ {
+ $collection = $this->getCollection($elements);
+ $result = $collection->add($value);
+
+ $this->assertEquals($expected, $result->toArray());
+ }
+
+ /**
+ * @return array
+ */
+ public function addValue()
+ {
+ return array(
+ array(array('a', 'b'), 'c', array('a', 'b', 'c')),
+ array(array(1, 3), 2, array(1, 3, 2)),
+ );
+ }
+
+ /**
+ * @test
+ * @dataProvider addKeyAndValue
+ *
+ * @param array $elements
+ * @param mixed $key
+ * @param mixed $value
+ * @param array $expected
+ */
+ public function shouldBeAbleToAddKeyAndValue(array $elements, $key, $value, array $expected)
+ {
+ $collection = $this->getCollection($elements);
+ $result = $collection->add($value, $key);
+
+ $this->assertEquals($expected, $result->toArray());
+ }
+
+ /**
+ * @return array
+ */
+ public function addKeyAndValue()
+ {
+ return array(
+ array(array('a' => 'b'), 'c', 'd', array('a' => 'b', 'c' => 'd')),
+ array(array(1 => 'a', 3 => 'b'), 2, 'c', array(1 => 'a', 3 => 'b', 2 => 'c')),
+ );
+ }
+}

0 comments on commit 933bcdd

Please sign in to comment.