Completed
Push — master ( 523ab4...07ae72 )
by Song
10:44 queued 07:58
created

ExportSeedCommand::handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 49
rs 9.1127
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Console;
4
5
use Encore\Admin\Admin;
6
use Illuminate\Console\Command;
7
8
class ExportSeedCommand extends Command
9
{
10
    /**
11
     * The console command name.
12
     *
13
     * @var string
14
     */
15
    protected $signature = 'admin:export-seed {classname=AdminTablesSeeder}
16
                                              {--users : add to seed users tables}';
17
    
18
    /**
19
     * The console command description.
20
     *
21
     * @var string
22
     */
23
    protected $description = 'Export seed a Laravel-admin database tables menu, roles and permissions';
24
    
25
    /**
26
     * Execute the console command.
27
     *
28
     * @return void
29
     */
30
    public function handle()
31
    {
32
        $name = $this->argument('classname');
33
        $exceptFields = [];
34
        $exportUsers = $this->option('users');
35
        
36
        $seedFile = $this->laravel->databasePath() . '/seeds/' . $name . '.php';
0 ignored issues
show
Bug introduced by
The method databasePath() does not exist on Illuminate\Contracts\Foundation\Application. Did you maybe mean basePath()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
37
        $contents = $this->getStub('AdminTablesSeeder');
38
        
39
        $replaces = [
40
            'DummyClass' => $name,
41
            
42
            'ClassMenu'       => config('admin.database.menu_model'),
43
            'ClassPermission' => config('admin.database.permissions_model'),
44
            'ClassRole'       => config('admin.database.roles_model'),
45
            
46
            'TableRoleMenu'        => config('admin.database.role_menu_table'),
47
            'TableRolePermissions' => config('admin.database.role_permissions_table'),
48
            
49
            'ArrayMenu'       => $this->getTableDataArrayAsString(config('admin.database.menu_table'), $exceptFields),
50
            'ArrayPermission' => $this->getTableDataArrayAsString(config('admin.database.permissions_table'), $exceptFields),
51
            'ArrayRole'       => $this->getTableDataArrayAsString(config('admin.database.roles_table'), $exceptFields),
52
            
53
            'ArrayPivotRoleMenu'        => $this->getTableDataArrayAsString(config('admin.database.role_menu_table'), $exceptFields),
54
            'ArrayPivotRolePermissions' => $this->getTableDataArrayAsString(config('admin.database.role_permissions_table'), $exceptFields),
55
        ];
56
        
57
        if ($exportUsers) {
58
            $replaces  = array_merge($replaces, [
59
                'ClassUsers'            => config('admin.database.users_model'),
60
                'TableRoleUsers'        => config('admin.database.role_users_table'),
61
                'TablePermissionsUsers' => config('admin.database.user_permissions_table'),
62
                
63
                'ArrayUsers'                 => $this->getTableDataArrayAsString(config('admin.database.users_table'), $exceptFields),
64
                'ArrayPivotRoleUsers'        => $this->getTableDataArrayAsString(config('admin.database.role_users_table'), $exceptFields),
65
                'ArrayPivotPermissionsUsers' => $this->getTableDataArrayAsString(config('admin.database.user_permissions_table'), $exceptFields),
66
            ]);
67
            
68
        } else {
69
            $contents = preg_replace('/\/\/ users tables[\s\S]*?(?=\/\/ finish)/mu', '', $contents);
70
        }
71
        
72
        $contents = str_replace(array_keys($replaces), array_values($replaces), $contents);
73
        
74
        $this->laravel['files']->put($seedFile, $contents);
75
        
76
        $this->line('<info>Admin tables seed file was created:</info> ' . str_replace(base_path(), '', $seedFile));
77
        $this->line("Use: <info>php artisan db:seed --class={$name}</info>");
78
    }
79
    
80
    /**
81
     * Get data array from table as string result var_export
82
     *
83
     * @param string $table
84
     * @param array $exceptFields
85
     * @return string
86
     */
87
    protected function getTableDataArrayAsString($table, $exceptFields = [])
88
    {
89
        $fields = \DB::getSchemaBuilder()->getColumnListing($table);
90
        $fields = array_diff($fields, $exceptFields);
91
        
92
        $array = \DB::table($table)->get($fields)->map(function ($item) {
93
            return (array)$item;
94
        })->all();
95
        
96
        return $this->varExport($array, str_repeat(' ', 12));
97
    }
98
    
99
    /**
100
     * Get stub contents.
101
     *
102
     * @param $name
103
     *
104
     * @return string
105
     */
106
    protected function getStub($name)
107
    {
108
        return $this->laravel['files']->get(__DIR__ . "/stubs/$name.stub");
109
    }
110
    
111
    /**
112
     * Custom var_export for correct work with \r\n
113
     *
114
     * @param $var
115
     * @param string $indent
116
     *
117
     * @return string
118
     */
119
    protected function varExport($var, $indent = '')
120
    {
121
        switch (gettype($var)) {
122
            
123
            case 'string':
124
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
125
            
126
            case 'array':
127
                $indexed = array_keys($var) === range(0, count($var) - 1);
128
                
129
                $r = [];
130
                
131
                foreach ($var as $key => $value) {
132
                    $r[] = "$indent    "
133
                        . ($indexed ? "" : $this->varExport($key) . " => ")
134
                        . $this->varExport($value, "{$indent}    ");
135
                }
136
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
137
            
138
            case 'boolean':
139
                return $var ? 'true' : 'false';
140
            
141
            case 'integer':
142
            case 'double':
143
                return $var;
144
            
145
            default:
146
                return var_export($var, true);
147
        }
148
    }
149
}
150