1 | <?php |
||
12 | class Tail extends Command implements WebCommand |
||
13 | { |
||
14 | /** |
||
15 | * The console command name. |
||
16 | * |
||
17 | * @var string |
||
18 | */ |
||
19 | protected $name = 'tail'; |
||
20 | |||
21 | /** |
||
22 | * The console command description. |
||
23 | * |
||
24 | * @var string |
||
25 | */ |
||
26 | protected $description = 'tail command'; |
||
27 | |||
28 | /** |
||
29 | * $files. |
||
30 | * |
||
31 | * @var \Illuminate\Filesystem\Filesystem |
||
32 | */ |
||
33 | protected $files; |
||
34 | |||
35 | /** |
||
36 | * __construct. |
||
37 | * |
||
38 | * @param \Illuminate\Filesystem\Filesystem $files |
||
39 | */ |
||
40 | 2 | public function __construct(Filesystem $files) |
|
46 | |||
47 | /** |
||
48 | * Handle the command. |
||
49 | * |
||
50 | * @throws \InvalidArgumentException |
||
51 | */ |
||
52 | 2 | public function handle() |
|
53 | { |
||
54 | 2 | $path = $this->argument('path'); |
|
55 | 2 | $lines = (int) $this->option('lines'); |
|
56 | |||
57 | 2 | if (empty($path) === false) { |
|
58 | 1 | $root = function_exists('base_path') === true ? base_path() : getcwd(); |
|
59 | 1 | $file = rtrim($root, '/').'/'.$path; |
|
60 | } else { |
||
61 | 1 | $path = function_exists('storage_path') === true ? storage_path() : getcwd(); |
|
62 | 1 | $path = rtrim($path, '/').'/'; |
|
63 | |||
64 | 1 | $file = (new Collection($this->files->glob($path.'logs/*.log'))) |
|
65 | 1 | ->map(function ($file) { |
|
66 | 1 | return is_file($file) === true ? $file : false; |
|
67 | })->sortByDesc(function ($file) { |
||
68 | 1 | return filectime($file); |
|
69 | 1 | })->first(); |
|
70 | } |
||
71 | |||
72 | 2 | $this->readLine($file, $lines); |
|
73 | 2 | } |
|
74 | |||
75 | /** |
||
76 | * readLine. |
||
77 | * |
||
78 | * @param string $file |
||
79 | * @param int $lines |
||
80 | * @return string |
||
81 | */ |
||
82 | 2 | protected function readLine($file, $lines = 50) |
|
83 | { |
||
84 | 2 | if (is_file($file) === false) { |
|
85 | $this->error('tail: cannot open ‘'.$file.'’ for reading: No such file or directory'); |
||
86 | |||
87 | return; |
||
88 | } |
||
89 | |||
90 | 2 | $fp = fopen($file, 'r'); |
|
91 | 2 | $i = 1; |
|
92 | 2 | $result = []; |
|
93 | 2 | while (! feof($fp)) { |
|
94 | 2 | if ($i > $lines) { |
|
95 | 2 | break; |
|
96 | } |
||
97 | 2 | $content = fgets($fp); |
|
98 | 2 | $result[] = $content; |
|
99 | 2 | $i++; |
|
100 | } |
||
101 | 2 | fclose($fp); |
|
102 | |||
103 | 2 | $this->line(implode('', $result)); |
|
104 | 2 | } |
|
105 | |||
106 | /** |
||
107 | * Get the console command arguments. |
||
108 | * |
||
109 | * @return array |
||
110 | */ |
||
111 | 2 | protected function getArguments() |
|
117 | |||
118 | /** |
||
119 | * Get the console command options. |
||
120 | * |
||
121 | * @return array |
||
122 | */ |
||
123 | 2 | protected function getOptions() |
|
129 | } |
||
130 |