Skip to content

Commit

Permalink
Extract method
Browse files Browse the repository at this point in the history
  • Loading branch information
guidocella committed Mar 18, 2017
1 parent 731833d commit 07f03da
Showing 1 changed file with 30 additions and 19 deletions.
49 changes: 30 additions & 19 deletions src/ModelPopulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,6 @@ protected function mergeAttributes(Model $model)
*
* @param Model $model
* @return array
* @throws \InvalidArgumentException
*/
protected function getFactoryAttributes(Model $model)
{
Expand All @@ -654,11 +653,11 @@ protected function getFactoryAttributes(Model $model)

$modelClass = get_class($model);

$isDefined = call_user_func(\Closure::bind(function () use ($modelClass) {
$modelIsDefined = call_user_func(\Closure::bind(function () use ($modelClass) {
return isset($this->definitions[$modelClass]);
}, $factory, $factory));

if (!$isDefined) {
if (!$modelIsDefined) {
// If the model is not defined in the factory and the developer didn't apply any state,
// that means he doesn't need the factory for this model, so we'll return an empty array.
if (!$states) {
Expand All @@ -673,23 +672,35 @@ protected function getFactoryAttributes(Model $model)
});
}

$stateAttributes = [];

foreach ($states as $state) {
$stateClosure = call_user_func(
\Closure::bind(function () use ($modelClass, $state) {
if (!isset($this->states[$modelClass][$state])) {
throw new \InvalidArgumentException("Unable to locate [{$state}] state for [{$modelClass}].");
}

return $this->states[$modelClass][$state];
}, $factory, $factory)
);

$stateAttributes = array_merge($stateAttributes, $stateClosure($this->generator));
}
return $factory->raw($modelClass, $this->getStateAttributes($factory, $states, $modelClass));
}

return $factory->raw($modelClass, $stateAttributes);
/**
* Get the factory state attributes of the model being built.
*
* @param Eloquent\Factory $factory
* @param string[] $states
* @param string $modelClass
* @return array
* @throws \InvalidArgumentException
*/
protected function getStateAttributes($factory, $states, $modelClass)
{
return collect($states)
->flatMap(function ($state) use ($factory, $modelClass) {
$stateClosure = call_user_func(
\Closure::bind(function () use ($modelClass, $state) {
if (!isset($this->states[$modelClass][$state])) {
throw new \InvalidArgumentException("Unable to locate [{$state}] state for [{$modelClass}].");
}

return $this->states[$modelClass][$state];
}, $factory, $factory)
);

return $stateClosure($this->generator);
})
->all();
}

/**
Expand Down

0 comments on commit 07f03da

Please sign in to comment.