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