github.com/goravel/framework@v1.13.9/event/console/event_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 EventMakeCommand struct { 18 } 19 20 // Signature The name and signature of the console command. 21 func (receiver *EventMakeCommand) Signature() string { 22 return "make:event" 23 } 24 25 // Description The console command description. 26 func (receiver *EventMakeCommand) Description() string { 27 return "Create a new event class" 28 } 29 30 // Extend The console command extend. 31 func (receiver *EventMakeCommand) Extend() command.Extend { 32 return command.Extend{ 33 Category: "make", 34 } 35 } 36 37 // Handle Execute the console command. 38 func (receiver *EventMakeCommand) Handle(ctx console.Context) error { 39 name := ctx.Argument(0) 40 if name == "" { 41 return errors.New("Not enough arguments (missing: name) ") 42 } 43 44 if err := file.Create(receiver.getPath(name), receiver.populateStub(receiver.getStub(), name)); err != nil { 45 return err 46 } 47 48 color.Greenln("Event created successfully") 49 50 return nil 51 } 52 53 func (receiver *EventMakeCommand) getStub() string { 54 return EventStubs{}.Event() 55 } 56 57 // populateStub Populate the place-holders in the command stub. 58 func (receiver *EventMakeCommand) populateStub(stub string, name string) string { 59 eventName, packageName, _ := receiver.parseName(name) 60 stub = strings.ReplaceAll(stub, "DummyEvent", str.Case2Camel(eventName)) 61 stub = strings.ReplaceAll(stub, "DummyPackage", packageName) 62 63 return stub 64 } 65 66 // getPath Get the full path to the command. 67 func (receiver *EventMakeCommand) getPath(name string) string { 68 pwd, _ := os.Getwd() 69 70 eventName, _, folderPath := receiver.parseName(name) 71 72 return filepath.Join(pwd, "app", "events", folderPath, str.Camel2Case(eventName)+".go") 73 } 74 75 // parseName Parse the name to get the event name, package name and folder path. 76 func (receiver *EventMakeCommand) parseName(name string) (string, string, string) { 77 name = strings.TrimSuffix(name, ".go") 78 79 segments := strings.Split(name, "/") 80 81 eventName := segments[len(segments)-1] 82 83 packageName := "events" 84 folderPath := "" 85 86 if len(segments) > 1 { 87 folderPath = filepath.Join(segments[:len(segments)-1]...) 88 packageName = segments[len(segments)-2] 89 } 90 91 return eventName, packageName, folderPath 92 }