Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add 'with' to allow chaining of methods #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 51 additions & 6 deletions src/FactoryStory.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace FactoryStories;

use Illuminate\Support\Collection;
use FactoryStories\Contracts\FactoryStoryContract;

/**
Expand All @@ -11,6 +12,7 @@ abstract class FactoryStory
{

protected $times = 1;
protected $with = null;

/**
* Here you can create your complex model factory
Expand All @@ -32,7 +34,7 @@ abstract public function build($params = []);
*/
public function times($amount)
{
$this->times = $amount;
$this->times = (int)$amount;

return $this;
}
Expand All @@ -46,12 +48,55 @@ public function times($amount)
*/
public function create($params = [])
{
if (is_int($this->times) && $this->times > 1) {
return collect(range(1, $this->times))
->transform(function ($index) use ($params) {
return $this->build($params);
});
if ($this->times <= 1) {
return $this->forge($params);
}

return Collection::times($this->times, function () use ($params) {
return $this->forge($params);
});
}

/**
* Add methods to be ran after initial build
*
* @param array $methods Array of method names
*
* @return FactoryStory $this Updated $with
*/

public function with($methods = [])
{
if(!is_null($this->with)) {
$this->with->merge(collect($methods));
}
else {
$this->with = collect($methods);
}

return $this;
}

/**
* Handles any creation steps that need to be done after building
* a story but before returning
*
* @param array $params Array of custom params
*
* @return Mixed
*/

public function forge($params = [])
{
if(is_null($this->with) || $this->with->count() === 0) {
return $this->build($params);
}

$story = $this->build($params);

$this->with->reduce(function($story, $methodName) {
return $this->$methodName($story);
}, $story);

return $this->build($params);
}
Expand Down