1: <?php
2:
3: namespace Baril\Bonsai\Console;
4:
5: use Illuminate\Console\Command;
6: use Illuminate\Database\Eloquent\Model;
7:
8: class ShowTreeCommand extends Command
9: {
10: protected $signature = 'bonsai:show {model : The model class.}
11: {--label= : The property to use as label.}
12: {--depth= : The depth limit.}';
13: protected $description = 'Outputs the content of the table in tree form';
14:
15: protected $model;
16: protected $label;
17: protected $currentDepth = 0;
18: protected $flags = [];
19:
20: public function handle()
21: {
22: $model = $this->input->getArgument('model');
23: if (
24: !class_exists($model)
25: || !is_subclass_of($model, Model::class)
26: || !method_exists($model, 'getClosureTable')
27: ) {
28: $this->error('{model} must be a valid model class and use the BelongsToTree trait!');
29: return;
30: }
31:
32: $this->model = $model;
33: $this->label = $this->input->getOption('label');
34:
35: $this->showTree($this->input->getOption('depth'));
36: }
37:
38: protected function showTree($depth)
39: {
40: $tree = $this->model::getTree($depth);
41: $count = count($tree);
42: foreach ($tree as $k => $node) {
43: $this->showNode($node, $k == $count - 1);
44: }
45: }
46:
47: protected function showNode($node, $isLast)
48: {
49: $this->flags[$this->currentDepth] = $isLast;
50: $line = '';
51: for ($i = 0; $i < $this->currentDepth; $i++) {
52: $line .= $this->flags[$i] ? " " : "\u{2502} ";
53: }
54: $line .= ($isLast ? "\u{2514}" : "\u{251C}") . "\u{2500}<info> #" . $node->getKey() . '</info>';
55: if ($this->label) {
56: $line .= ': ' . $node->{$this->label};
57: }
58: $this->line($line);
59: if ($node->relationLoaded('children')) {
60: $this->currentDepth++;
61: $subCount = count($node->children);
62: foreach ($node->children as $k => $child) {
63: $this->showNode($child, $k == $subCount - 1);
64: }
65: $this->currentDepth--;
66: }
67: }
68: }
69: