forked from goravel/framework
/
seeder_make_command.go
103 lines (77 loc) · 2.6 KB
/
seeder_make_command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package console
import (
"os"
"path/filepath"
"strings"
"github.com/gookit/color"
"github.com/mewway/go-laravel/contracts/config"
"github.com/mewway/go-laravel/support"
"github.com/mewway/go-laravel/contracts/console"
"github.com/mewway/go-laravel/contracts/console/command"
"github.com/mewway/go-laravel/support/file"
"github.com/mewway/go-laravel/support/str"
)
type SeederMakeCommand struct {
config config.Config
}
func NewSeederMakeCommand(config config.Config) *SeederMakeCommand {
return &SeederMakeCommand{
config: config,
}
}
// Signature The name and signature of the console command.
func (receiver *SeederMakeCommand) Signature() string {
return "make:seeder"
}
// Description The console command description.
func (receiver *SeederMakeCommand) Description() string {
return "Create a new seeder class"
}
// Extend The console command extend.
func (receiver *SeederMakeCommand) Extend() command.Extend {
return command.Extend{
Category: "make",
}
}
// Handle Execute the console command.
func (receiver *SeederMakeCommand) Handle(ctx console.Context) error {
name := ctx.Argument(0)
if name == "" {
color.Redln("Not enough arguments (missing: name)")
return nil
}
if err := file.Create(receiver.getPath(name), receiver.populateStub(receiver.getStub(), name)); err != nil {
return err
}
color.Greenln("Seeder created successfully")
return nil
}
func (receiver *SeederMakeCommand) getStub() string {
return Stubs{}.Seeder()
}
// populateStub Populate the place-holders in the command stub.
func (receiver *SeederMakeCommand) populateStub(stub string, name string) string {
modelName, packageName, _ := receiver.parseName(name)
stub = strings.ReplaceAll(stub, "DummySeeder", str.Case2Camel(modelName))
stub = strings.ReplaceAll(stub, "DummyPackage", packageName)
return stub
}
// getPath Get the full path to the command.
func (receiver *SeederMakeCommand) getPath(name string) string {
pwd, _ := os.Getwd()
modelName, _, folderPath := receiver.parseName(name)
return filepath.Join(pwd, support.DirDatabase, support.DirSeeder, folderPath, str.Camel2Case(modelName)+".go")
}
// parseName Parse the name to get the model name, package name and folder path.
func (receiver *SeederMakeCommand) parseName(name string) (string, string, string) {
name = strings.TrimSuffix(name, ".go")
segments := strings.Split(name, "/")
modelName := segments[len(segments)-1]
packageName := support.DirSeeder
folderPath := ""
if len(segments) > 1 {
folderPath = filepath.Join(segments[:len(segments)-1]...)
packageName = segments[len(segments)-2]
}
return modelName, packageName, folderPath
}