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 getConsoleOutput() |
13
|
|
|
{ |
14
|
|
|
return 'Added route to '.$this->command->naming[$this->key]->getRelativeFilePath(); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function call() |
18
|
|
|
{ |
19
|
|
|
$routeFile = $this->naming->getFile(); |
20
|
|
|
|
21
|
|
|
if ($this->filesystem->exists($routeFile)) { |
22
|
|
|
$this->addRoute($routeFile); |
23
|
|
|
$this->addGeneratedFileToIdeStack(); |
24
|
|
|
} |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
private function getRouteString() |
28
|
|
|
{ |
29
|
|
|
return 'CRUD::resource(\'' . $this->naming->getName() . '\', \'' . $this->command->naming['crudController']->getClassName() . '\');'; |
|
|
|
|
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
private function addRoute($routeFile) |
33
|
|
|
{ |
34
|
|
|
$old_file_content = $this->filesystem->get($routeFile); |
35
|
|
|
|
36
|
|
|
// insert the given code before the file's last line |
37
|
|
|
$file_lines = preg_split('/\r\n|\r|\n/', $old_file_content); |
38
|
|
|
if ($end_line_number = $this->getRoutesFileEndLine($file_lines)) { |
39
|
|
|
$file_lines[$end_line_number + 1] = $file_lines[$end_line_number]; |
40
|
|
|
$file_lines[$end_line_number] = ' ' . $this->getRouteString(); |
41
|
|
|
$new_file_content = implode(PHP_EOL, $file_lines); |
42
|
|
|
|
43
|
|
|
$this->filesystem->put($routeFile, $new_file_content); |
44
|
|
|
} else { |
45
|
|
|
$this->filesystem->append($routeFile, PHP_EOL . $this->getRouteString()); |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function getRoutesFileEndLine($file_lines) |
|
|
|
|
50
|
|
|
{ |
51
|
|
|
// in case the last line has not been modified at all |
52
|
|
|
$end_line_number = array_search('}); // this should be the absolute last line of this file', $file_lines); |
53
|
|
|
|
54
|
|
|
if ($end_line_number) { |
55
|
|
|
return $end_line_number; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// otherwise, in case the last line HAS been modified |
59
|
|
|
// return the last line that has an ending in it |
60
|
|
|
$possible_end_lines = array_filter($file_lines, function ($k) { |
61
|
|
|
return strpos($k, '});') === 0; |
62
|
|
|
}); |
63
|
|
|
|
64
|
|
|
if ($possible_end_lines) { |
|
|
|
|
65
|
|
|
end($possible_end_lines); |
66
|
|
|
$end_line_number = key($possible_end_lines); |
67
|
|
|
|
68
|
|
|
return $end_line_number; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
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.