Skip to content

Commit

Permalink
add mapInto method
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Jun 3, 2017
1 parent 8e6e0de commit 2642ac7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,19 @@ public function flatMap(callable $callback)
return $this->map($callback)->collapse();
}

/**
* Map the values into a new class.
*
* @param string $class
* @return static
*/
public function mapInto($class)
{
return $this->map(function ($value, $key) use ($class) {
return new $class($value, $key);
});
}

/**
* Get the max value of a given key.
*
Expand Down
22 changes: 22 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1209,6 +1209,18 @@ public function testMapWithKeysCallbackKey()
);
}

public function testMapInto()
{
$data = new Collection([
'first', 'second',
]);

$data = $data->mapInto(TestCollectionMapIntoObject::class);

$this->assertEquals('first', $data[0]->value);
$this->assertEquals('second', $data[1]->value);
}

public function testNth()
{
$data = new Collection([
Expand Down Expand Up @@ -2200,3 +2212,13 @@ public function jsonSerialize()
return ['foo' => 'bar'];
}
}

class TestCollectionMapIntoObject
{
public $value;

public function __construct($value)
{
$this->value = $value;
}
}

0 comments on commit 2642ac7

Please sign in to comment.