I want to follows a rule one function do one thing only. So i need to refactor this method. That do many thing to do a task (setTags). Mostly inside foreach the code will re-use to other method (setGenres, setLanguage, setCharacter, setCountries) with same style code.
This raw original method. in bottom my refactor method.
public function setTags($tags)
{
foreach ($tags as $name)
{
$tag = Tag::firstOrCreate([
'name' => ucwords($name)
]);
if (empty($this->media->tags()->where('tag_id', $tag->id)->exists())) {
$this->media->tags()->attach($tag->id);
}
}
}
Refactor method
// is it right to name it createModelValue?
public function createModelValue($model, $value) {
$collection = $model::firstOrCreate([
'name' => ucwords($value)
]);
if (!empty($collection)) {
return $collection;
}else{ return NULL; }
}
// new problem how to pass $model (tag) as function relationship to replace tags function
public function setModel($model) {
if (empty($this->media->tags()->where("{$model}_id", $model->id)->exists())) {
$this->media->tags()->attach($model->id);
}
}
