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