/** * Add relationships to the model * * @param $fileContents * @param $newModel * @return string */ private function addRelationships($fileContents, $newModel = true) { if (!$newModel) { $fileContents = substr($fileContents, 0, strrpos($fileContents, "}")); } foreach ($this->model->getRelationships() as $relation) { $relatedModel = $relation->model; if (strpos($fileContents, $relation->getName()) !== false && !$newModel) { continue; } $functionContent = "\t\treturn \$this->" . $relation->getType() . "('" . $relatedModel->nameWithNamespace() . "');\n"; $fileContents .= $this->fileCreator->createFunction($relation->getName(), $functionContent); $relatedModelFile = $this->configSettings['pathTo']['models'] . $relatedModel->upper() . '.php'; if (!\File::exists($relatedModelFile)) { if ($this->fromFile) { continue; } else { $editRelatedModel = $this->confirm("Model " . $relatedModel->upper() . " doesn't exist yet. Would you like to create it now [y/n]? ", true); if ($editRelatedModel) { $this->fileCreator->createClass($relatedModelFile, "", array('name' => "\\Eloquent")); } else { continue; } } } $content = \File::get($relatedModelFile); if (preg_match("/function " . $this->model->lower() . "/", $content) !== 1 && preg_match("/function " . $this->model->plural() . "/", $content) !== 1) { $index = 0; $reverseRelations = $relation->reverseRelations(); if (count($reverseRelations) > 1) { $index = $this->command->ask($relatedModel->upper() . " (0=" . $reverseRelations[0] . " OR 1=" . $reverseRelations[1] . ") " . $this->model->upper() . "? "); } $reverseRelationType = $reverseRelations[$index]; $reverseRelationName = $relation->getReverseName($this->model, $reverseRelationType); $content = substr($content, 0, strrpos($content, "}")); $functionContent = "\t\treturn \$this->" . $reverseRelationType . "('" . $this->model->nameWithNamespace() . "');\n"; $content .= $this->fileCreator->createFunction($reverseRelationName, $functionContent) . "}\n"; \File::put($relatedModelFile, $content); } } return $fileContents; }