1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Webfactor\Laravel\Generators\Services; |
4
|
|
|
|
5
|
|
|
use Webfactor\Laravel\Generators\Contracts\ServiceAbstract; |
6
|
|
|
use Webfactor\Laravel\Generators\Contracts\ServiceInterface; |
7
|
|
|
|
8
|
|
|
class RouteService extends ServiceAbstract implements ServiceInterface |
9
|
|
|
{ |
10
|
|
|
protected $key = 'routeFile'; |
11
|
|
|
|
12
|
|
|
public function call() |
13
|
|
|
{ |
14
|
|
|
$routeFile = $this->naming->getFile(); |
15
|
|
|
|
16
|
|
|
if ($this->filesystem->exists($routeFile)) { |
17
|
|
|
$this->addRoute($routeFile); |
18
|
|
|
$this->addGeneratedFileToIdeStack(); |
19
|
|
|
} |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
private function getRouteString() |
23
|
|
|
{ |
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
|
|
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.