function ingredientsFromString($str, Recipe $recipe) { $ingredients = explode(',', $str); foreach ($ingredients as $ingredient) { $ingToSave = \App\Ingredient::where('name', '=', trim($ingredient))->first(); ## Check singular form if necessary if (!isset($ingToSave)) { $ingToSave = \App\Ingredient::where('name', '=', trim(str_singular($ingredient)))->first(); } ## Links ingredient to recipe, or adds new ingredient and links if (isset($ingToSave)) { $recipe->ingredients()->save($ingToSave); } else { $newIng = new \App\Ingredient(); $newIng->name = $ingredient; $newIng->save(); $recipe->ingredients()->save($newIng); } } }
public function populate() { set_time_limit(300); $client = new Client(); $array = $this->ingredientsArray(); foreach ($array as $key => $value) { $crawler = $client->request('GET', $value); $synonyms = $this->synonymsArray($value); $crawler->filter('b')->each(function ($node) use($key, $synonyms) { $s = $node->text(); // Replaces   with a space $s = str_replace('0xa0', ' ', $s); // Removes extraneous words $s = str_replace('Synonyms:', '', $s); $s = str_replace('Substitutes:', '', $s); $s = str_replace('Pronunciation:', '', $s); $s = str_replace('Pronuncation:', '', $s); $s = str_replace('Notes:', '', $s); $s = str_replace('Equivalents:', '', $s); $s = str_replace('Varieties:', '', $s); $s = str_replace('Latin name:', '', $s); $s = str_replace('Latin', '', $s); $s = str_replace('Warning:', '', $s); $s = str_replace('Plural:', '', $s); $s = str_replace('Cooking hints:', '', $s); $s = str_replace('Links', '', $s); $s = str_replace('Tips', '', $s); $s = str_replace('To make your own:', '', $s); $s = str_replace('Includes:', '', $s); $s = str_replace('Cuts:', '', $s); $s = str_replace(':', '', $s); $s = trim($s, " \t\n\r\v "); if ($s == '' || $s == '=' || $s == '.' || $s == ',' || $s == '+') { return false; } if (array_search($s, $synonyms)) { return false; } if (!strpbrk($s, '=') && !empty($s) && !strpbrk($s, 'See')) { $ingredient = new \App\Ingredient(); $ingredient->category = $key; $ingredient->name = $s; $ingredient->save(); } elseif (strpbrk($s, '=')) { $ingredient = new \App\Ingredient(); $ingredient->category = $key; $synonyms = explode('=', $s); if ($synonyms[0] == '') { return false; } $name = $synonyms[0]; $parallel_name = ''; foreach ($synonyms as $synonym) { if ($synonym != $name && $synonym != '') { $parallel_name .= $synonym; } } $ingredient->name = $name; $ingredient->parallel_name = $parallel_name; $ingredient->save(); } }); } echo 'Finished!'; }