Skip to content

Commit 73fd836

Browse files
committed
fix route placement
1 parent be8d481 commit 73fd836

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

src/Services/RouteService.php

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,50 @@ 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+
$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+
}
40+
41+
private function getRoutesFileEndLine($file_lines)
42+
{
43+
// in case the last line has not been modified at all
44+
$end_line_number = array_search('}); // this should be the absolute last line of this file', $file_lines);
45+
46+
if ($end_line_number) {
47+
return $end_line_number;
48+
}
49+
50+
// otherwise, in case the last line HAS been modified
51+
// return the last line that has an ending in it
52+
$possible_end_lines = array_filter($file_lines, function ($k) {
53+
return strpos($k, '});') === 0;
54+
});
55+
56+
if ($possible_end_lines) {
57+
end($possible_end_lines);
58+
$end_line_number = key($possible_end_lines);
59+
60+
return $end_line_number;
61+
}
2562
}
2663
}

0 commit comments

Comments
 (0)