Skip to content

Commit 69eaf86

Browse files
authored
Merge pull request #31 from webfactor/issue-24
fix route placement
2 parents 5d84d68 + 9175ea4 commit 69eaf86

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

src/Services/RouteService.php

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,53 @@ public function call()
1414
$routeFile = $this->naming->getFile();
1515

1616
if ($this->filesystem->exists($routeFile)) {
17-
$this->filesystem->append($routeFile, $this->getRouteString());
17+
$this->addRoute($routeFile);
1818
$this->addGeneratedFileToIdeStack();
1919
}
2020
}
2121

2222
private function getRouteString()
2323
{
24-
return PHP_EOL . 'CRUD::resource(\'' . $this->naming->getName() . '\', \'' . $this->command->naming['crudController']->getClassName() . '\');';
24+
return 'CRUD::resource(\'' . $this->naming->getName() . '\', \'' . $this->command->naming['crudController']->getClassName() . '\');';
25+
}
26+
27+
private function addRoute($routeFile)
28+
{
29+
$old_file_content = $this->filesystem->get($routeFile);
30+
31+
// insert the given code before the file's last line
32+
$file_lines = preg_split('/\r\n|\r|\n/', $old_file_content);
33+
if ($end_line_number = $this->getRoutesFileEndLine($file_lines)) {
34+
$file_lines[$end_line_number + 1] = $file_lines[$end_line_number];
35+
$file_lines[$end_line_number] = ' ' . $this->getRouteString();
36+
$new_file_content = implode(PHP_EOL, $file_lines);
37+
38+
$this->filesystem->put($routeFile, $new_file_content);
39+
} else {
40+
$this->filesystem->append($routeFile, PHP_EOL . $this->getRouteString());
41+
}
42+
}
43+
44+
private function getRoutesFileEndLine($file_lines)
45+
{
46+
// in case the last line has not been modified at all
47+
$end_line_number = array_search('}); // this should be the absolute last line of this file', $file_lines);
48+
49+
if ($end_line_number) {
50+
return $end_line_number;
51+
}
52+
53+
// otherwise, in case the last line HAS been modified
54+
// return the last line that has an ending in it
55+
$possible_end_lines = array_filter($file_lines, function ($k) {
56+
return strpos($k, '});') === 0;
57+
});
58+
59+
if ($possible_end_lines) {
60+
end($possible_end_lines);
61+
$end_line_number = key($possible_end_lines);
62+
63+
return $end_line_number;
64+
}
2565
}
2666
}

0 commit comments

Comments
 (0)