From 07f03daaf3d85a0f2a6417946405f4cd91af35bf Mon Sep 17 00:00:00 2001 From: guidocella Date: Sat, 18 Mar 2017 20:49:06 +0100 Subject: [PATCH] Extract method --- src/ModelPopulator.php | 49 ++++++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/src/ModelPopulator.php b/src/ModelPopulator.php index cf8ccb9..aa96c49 100644 --- a/src/ModelPopulator.php +++ b/src/ModelPopulator.php @@ -634,7 +634,6 @@ protected function mergeAttributes(Model $model) * * @param Model $model * @return array - * @throws \InvalidArgumentException */ protected function getFactoryAttributes(Model $model) { @@ -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) { @@ -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(); } /**