From c78885a5b26d10b89ec1b13ee1039e9442066dc0 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 10:38:50 +0530 Subject: [PATCH 01/32] solve potential nil error for console --- console/application.go | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/console/application.go b/console/application.go index 34193084a..6bdd474d1 100644 --- a/console/application.go +++ b/console/application.go @@ -47,20 +47,28 @@ func (c *Application) Register(commands []console.Command) { // Call Run an Artisan console command by name. func (c *Application) Call(command string) { - commands := []string{os.Args[0]} - if c.isArtisan { - commands = append(commands, "artisan") + if os.Args != nil && len(os.Args) > 0 { + commands := []string{os.Args[0]} + + if c.isArtisan { + commands = append(commands, "artisan") + } + + c.Run(append(commands, strings.Split(command, " ")...), false) } - c.Run(append(commands, strings.Split(command, " ")...), false) } // CallAndExit Run an Artisan console command by name and exit. func (c *Application) CallAndExit(command string) { - commands := []string{os.Args[0]} - if c.isArtisan { - commands = append(commands, "artisan") + if os.Args != nil && len(os.Args) > 0 { + commands := []string{os.Args[0]} + + if c.isArtisan { + commands = append(commands, "artisan") + } + + c.Run(append(commands, strings.Split(command, " ")...), true) } - c.Run(append(commands, strings.Split(command, " ")...), true) } // Run a command. Args come from os.Args. From 610ac59765f8a84914ce76715fda2b79333907a2 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 12:21:40 +0530 Subject: [PATCH 02/32] solve potential nil error for progress bar --- console/progress_bar.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/console/progress_bar.go b/console/progress_bar.go index bd6a6b5d6..75066dd8d 100644 --- a/console/progress_bar.go +++ b/console/progress_bar.go @@ -19,10 +19,16 @@ func NewProgressBar(total int) *ProgressBar { } func (r *ProgressBar) Advance(step ...int) { + var instance *pterm.ProgressbarPrinter + if len(step) > 0 { - r.instance = r.instance.Add(step[0]) + instance = r.instance.Add(step[0]) } else { - r.instance = r.instance.Increment() + instance = r.instance.Increment() + } + + if instance != nil { + r.instance = instance } } From 51de4fe688aba1afd60a055882271621107a8550 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 13:10:13 +0530 Subject: [PATCH 03/32] solve potential nil error for str.When --- support/str/str.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/support/str/str.go b/support/str/str.go index 5714f729d..117bc067f 100644 --- a/support/str/str.go +++ b/support/str/str.go @@ -804,12 +804,14 @@ func (s *String) Upper() *String { } // When returns the String instance with the given callback applied if the given condition is true. -// If the condition is false, the fallback callback is applied.(if provided) +// If the condition is false, the fallback callback is applied (if provided). func (s *String) When(condition bool, callback ...func(*String) *String) *String { if condition { - return callback[0](s) + if len(callback) > 0 && callback[0] != nil { + return callback[0](s) + } } else { - if len(callback) > 1 { + if len(callback) > 1 && callback[1] != nil { return callback[1](s) } } From b4ff7114e5c25f232c0ff2a1161caeade6eca455 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 14:19:21 +0530 Subject: [PATCH 04/32] resolve nil error for filesystem --- console/application.go | 4 ++-- filesystem/file.go | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/console/application.go b/console/application.go index 6bdd474d1..2da4ee378 100644 --- a/console/application.go +++ b/console/application.go @@ -47,7 +47,7 @@ func (c *Application) Register(commands []console.Command) { // Call Run an Artisan console command by name. func (c *Application) Call(command string) { - if os.Args != nil && len(os.Args) > 0 { + if len(os.Args) > 0 { commands := []string{os.Args[0]} if c.isArtisan { @@ -60,7 +60,7 @@ func (c *Application) Call(command string) { // CallAndExit Run an Artisan console command by name and exit. func (c *Application) CallAndExit(command string) { - if os.Args != nil && len(os.Args) > 0 { + if len(os.Args) > 0 { commands := []string{os.Args[0]} if c.isArtisan { diff --git a/filesystem/file.go b/filesystem/file.go index 32375d107..06e36527d 100644 --- a/filesystem/file.go +++ b/filesystem/file.go @@ -25,6 +25,10 @@ type File struct { } func NewFile(file string) (*File, error) { + if err := checkFacades(); err != nil { + return nil, err + } + if !supportfile.Exists(file) { return nil, errors.New("file doesn't exist") } @@ -39,6 +43,10 @@ func NewFile(file string) (*File, error) { } func NewFileFromRequest(fileHeader *multipart.FileHeader) (*File, error) { + if err := checkFacades(); err != nil { + return nil, err + } + src, err := fileHeader.Open() if err != nil { return nil, err @@ -129,3 +137,16 @@ func (f *File) Store(path string) (string, error) { func (f *File) StoreAs(path string, name string) (string, error) { return f.storage.Disk(f.disk).PutFileAs(path, f, name) } + +// CheckFacades ensures that ConfigFacade and StorageFacade are properly initialized. +func checkFacades() error { + if ConfigFacade == nil { + return errors.New("config facade is not initialized") + } + + if StorageFacade == nil { + return errors.New("storage facade is not initialized") + } + + return nil +} From 45b921e3be89037f0b33700dbcf47a352cd38f9c Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 15:07:21 +0530 Subject: [PATCH 05/32] resolve nil errors --- database/service_provider.go | 31 +++++++++++++++++-------------- testing/docker/database.go | 5 +++++ validation/errors_test.go | 3 +++ validation/validation_test.go | 12 ++++++++++-- 4 files changed, 35 insertions(+), 16 deletions(-) diff --git a/database/service_provider.go b/database/service_provider.go index fe57182d9..617563c23 100644 --- a/database/service_provider.go +++ b/database/service_provider.go @@ -47,18 +47,21 @@ func (database *ServiceProvider) registerCommands(app foundation.Application) { config := app.MakeConfig() seeder := app.MakeSeeder() artisan := app.MakeArtisan() - app.MakeArtisan().Register([]consolecontract.Command{ - console.NewMigrateMakeCommand(config), - console.NewMigrateCommand(config), - console.NewMigrateRollbackCommand(config), - console.NewMigrateResetCommand(config), - console.NewMigrateRefreshCommand(config, artisan), - console.NewMigrateFreshCommand(config, artisan), - console.NewMigrateStatusCommand(config), - console.NewModelMakeCommand(), - console.NewObserverMakeCommand(), - console.NewSeedCommand(config, seeder), - console.NewSeederMakeCommand(), - console.NewFactoryMakeCommand(), - }) + + if artisan != nil { + artisan.Register([]consolecontract.Command{ + console.NewMigrateMakeCommand(config), + console.NewMigrateCommand(config), + console.NewMigrateRollbackCommand(config), + console.NewMigrateResetCommand(config), + console.NewMigrateRefreshCommand(config, artisan), + console.NewMigrateFreshCommand(config, artisan), + console.NewMigrateStatusCommand(config), + console.NewModelMakeCommand(), + console.NewObserverMakeCommand(), + console.NewSeedCommand(config, seeder), + console.NewSeederMakeCommand(), + console.NewFactoryMakeCommand(), + }) + } } diff --git a/testing/docker/database.go b/testing/docker/database.go index b0327c92f..d5f7dbce1 100644 --- a/testing/docker/database.go +++ b/testing/docker/database.go @@ -2,6 +2,7 @@ package docker import ( "context" + "errors" "fmt" "time" @@ -27,6 +28,10 @@ type Database struct { func NewDatabase(app foundation.Application, connection string, gormInitialize gorm.Initialize) (*Database, error) { config := app.MakeConfig() + if config == nil { + return nil, errors.New("config facade is not set") + } + if connection == "" { connection = config.GetString("database.default") } diff --git a/validation/errors_test.go b/validation/errors_test.go index 4cacb911e..fb96a42a0 100644 --- a/validation/errors_test.go +++ b/validation/errors_test.go @@ -74,7 +74,10 @@ func TestOne(t *testing.T) { test.rules, test.options..., ) + assert.Nil(t, err, test.describe) + assert.NotNil(t, validator, test.describe) + if test.expectRes != "" { assert.Equal(t, test.expectRes, validator.Errors().One(), test.describe) } diff --git a/validation/validation_test.go b/validation/validation_test.go index e32ff4850..b5656c398 100644 --- a/validation/validation_test.go +++ b/validation/validation_test.go @@ -2894,7 +2894,11 @@ func (receiver *Uppercase) Signature() string { func (receiver *Uppercase) Passes(data httpvalidate.Data, val any, options ...any) bool { name, exist := data.Get("name") - return strings.ToUpper(val.(string)) == val.(string) && len(val.(string)) == cast.ToInt(options[0]) && name == val && exist + if len(options) > 0 { + return strings.ToUpper(val.(string)) == val.(string) && len(val.(string)) == cast.ToInt(options[0]) && name == val && exist + } + + return false } // Message Get the validation error message. @@ -2914,7 +2918,11 @@ func (receiver *Lowercase) Signature() string { func (receiver *Lowercase) Passes(data httpvalidate.Data, val any, options ...any) bool { address, exist := data.Get("address") - return strings.ToLower(val.(string)) == val.(string) && len(val.(string)) == cast.ToInt(options[0]) && address == val && exist + if len(options) > 0 { + return strings.ToLower(val.(string)) == val.(string) && len(val.(string)) == cast.ToInt(options[0]) && address == val && exist + } + + return false } // Message Get the validation error message. From 07dd54acec943ce6903f089c21c830938470d92a Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 15:17:33 +0530 Subject: [PATCH 06/32] resolve nil errors --- testing/docker/database.go | 7 ++++++- validation/errors_test.go | 20 +++++++++++++++----- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/testing/docker/database.go b/testing/docker/database.go index d5f7dbce1..8947a6955 100644 --- a/testing/docker/database.go +++ b/testing/docker/database.go @@ -89,7 +89,12 @@ func (receiver *Database) Build() error { return fmt.Errorf("connect to %s failed", receiver.driver.Name().String()) } - receiver.app.MakeArtisan().Call("migrate") + artisan := receiver.app.MakeArtisan() + if artisan == nil { + return errors.New("artisan instance is not available") + } + + artisan.Call("migrate") receiver.app.Singleton(frameworkdatabase.BindingOrm, func(app foundation.Application) (any, error) { config := app.MakeConfig() defaultConnection := config.GetString("database.default") diff --git a/validation/errors_test.go b/validation/errors_test.go index fb96a42a0..3833c7138 100644 --- a/validation/errors_test.go +++ b/validation/errors_test.go @@ -79,7 +79,9 @@ func TestOne(t *testing.T) { assert.NotNil(t, validator, test.describe) if test.expectRes != "" { - assert.Equal(t, test.expectRes, validator.Errors().One(), test.describe) + errors := validator.Errors() + assert.NotNil(t, errors) + assert.Equal(t, test.expectRes, errors.One(), test.describe) } } } @@ -119,10 +121,14 @@ func TestGet(t *testing.T) { ) assert.Nil(t, err, test.describe) if len(test.expectA) > 0 { - assert.Equal(t, test.expectA, validator.Errors().Get("a"), test.describe) + errors := validator.Errors() + assert.NotNil(t, errors) + assert.Equal(t, test.expectA, errors.Get("a"), test.describe) } if len(test.expectB) > 0 { - assert.Equal(t, test.expectB, validator.Errors().Get("b"), test.describe) + errors := validator.Errors() + assert.NotNil(t, errors) + assert.Equal(t, test.expectB, errors.Get("b"), test.describe) } } } @@ -164,7 +170,9 @@ func TestAll(t *testing.T) { ) assert.Nil(t, err, test.describe) if len(test.expectRes) > 0 { - assert.Equal(t, test.expectRes, validator.Errors().All(), test.describe) + errors := validator.Errors() + assert.NotNil(t, errors) + assert.Equal(t, test.expectRes, errors.All(), test.describe) } } } @@ -202,7 +210,9 @@ func TestHas(t *testing.T) { ) assert.Nil(t, err, test.describe) if test.expectRes { - assert.Equal(t, test.expectRes, validator.Errors().Has("a"), test.describe) + errors := validator.Errors() + assert.NotNil(t, errors) + assert.Equal(t, test.expectRes, errors.Has("a"), test.describe) } } } From 58d507adbb047a42a701eec5b83660a21db61ea5 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 15:44:00 +0530 Subject: [PATCH 07/32] resolve nil errors --- auth/service_provider.go | 11 +++++++---- foundation/application.go | 9 ++++++++- http/limit/store.go | 20 ++++++++++++++------ http/service_provider.go | 13 ++++++++----- mail/service_provider.go | 19 +++++++++++++------ testing/docker/database.go | 9 ++++++++- testing/service_provider.go | 4 ++-- testing/test_case.go | 13 +++++++++++-- 8 files changed, 71 insertions(+), 27 deletions(-) diff --git a/auth/service_provider.go b/auth/service_provider.go index 19763ce8a..b1c682906 100644 --- a/auth/service_provider.go +++ b/auth/service_provider.go @@ -32,8 +32,11 @@ func (database *ServiceProvider) Boot(app foundation.Application) { } func (database *ServiceProvider) registerCommands(app foundation.Application) { - app.MakeArtisan().Register([]contractconsole.Command{ - console.NewJwtSecretCommand(app.MakeConfig()), - console.NewPolicyMakeCommand(), - }) + artisan := app.MakeArtisan() + if artisan != nil { + artisan.Register([]contractconsole.Command{ + console.NewJwtSecretCommand(app.MakeConfig()), + console.NewPolicyMakeCommand(), + }) + } } diff --git a/foundation/application.go b/foundation/application.go index f526b32aa..39d51b397 100644 --- a/foundation/application.go +++ b/foundation/application.go @@ -14,6 +14,7 @@ import ( "github.com/goravel/framework/foundation/json" "github.com/goravel/framework/support" "github.com/goravel/framework/support/carbon" + "github.com/goravel/framework/support/color" ) var ( @@ -121,7 +122,13 @@ func (app *Application) Version() string { } func (app *Application) CurrentLocale(ctx context.Context) string { - return app.MakeLang(ctx).CurrentLocale() + lang := app.MakeLang(ctx) + if lang == nil { + color.Red().Println("Error: Lang facade not initialized.") + return "" + } + + return lang.CurrentLocale() } func (app *Application) SetLocale(ctx context.Context, locale string) context.Context { diff --git a/http/limit/store.go b/http/limit/store.go index 81fb47b95..c3ed9a431 100644 --- a/http/limit/store.go +++ b/http/limit/store.go @@ -2,9 +2,11 @@ package limit import ( "context" + "errors" "sync" "time" + "github.com/goravel/framework/contracts/cache" "github.com/goravel/framework/http" "github.com/goravel/framework/support/carbon" ) @@ -56,6 +58,7 @@ type Store interface { type store struct { tokens uint64 interval time.Duration + cache cache.Cache } func NewStore(tokens uint64, interval time.Duration) (Store, error) { @@ -67,9 +70,14 @@ func NewStore(tokens uint64, interval time.Duration) (Store, error) { interval = 1 * time.Second } + if http.CacheFacade == nil { + return nil, errors.New("cache facade is not initialized") + } + s := &store{ tokens: tokens, interval: interval, + cache: http.CacheFacade, } return s, nil @@ -79,13 +87,13 @@ func NewStore(tokens uint64, interval time.Duration) (Store, error) { // successful, it returns true, otherwise false. It also returns the configured // limit, remaining tokens, and reset time. func (s *store) Take(_ context.Context, key string) (uint64, uint64, uint64, bool, error) { - b, ok := http.CacheFacade.Get(key).(*Bucket) + b, ok := s.cache.Get(key).(*Bucket) if ok { return b.take() } nb := NewBucket(s.tokens, s.interval) - if err := http.CacheFacade.Put(key, nb, s.interval); err != nil { + if err := s.cache.Put(key, nb, s.interval); err != nil { return 0, 0, 0, false, err } @@ -94,7 +102,7 @@ func (s *store) Take(_ context.Context, key string) (uint64, uint64, uint64, boo // Get retrieves the information about the key, if any exists. func (s *store) Get(_ context.Context, key string) (uint64, uint64, error) { - b, ok := http.CacheFacade.Get(key).(*Bucket) + b, ok := s.cache.Get(key).(*Bucket) if ok { return b.get() } @@ -105,12 +113,12 @@ func (s *store) Get(_ context.Context, key string) (uint64, uint64, error) { // Set configures the Bucket-specific tokens and interval. func (s *store) Set(_ context.Context, key string, tokens uint64, interval time.Duration) error { b := NewBucket(tokens, interval) - return http.CacheFacade.Put(key, b, interval) + return s.cache.Put(key, b, interval) } // Burst adds the provided value to the Bucket's currently available tokens. func (s *store) Burst(_ context.Context, key string, tokens uint64) error { - b, ok := http.CacheFacade.Get(key).(*Bucket) + b, ok := s.cache.Get(key).(*Bucket) if ok { b.lock.Lock() b.availableTokens = b.availableTokens + tokens @@ -119,7 +127,7 @@ func (s *store) Burst(_ context.Context, key string, tokens uint64) error { } nb := NewBucket(s.tokens+tokens, s.interval) - return http.CacheFacade.Put(key, nb, s.interval) + return s.cache.Put(key, nb, s.interval) } // Bucket is an internal wrapper around a taker. diff --git a/http/service_provider.go b/http/service_provider.go index 5b99c147f..f22d53d4e 100644 --- a/http/service_provider.go +++ b/http/service_provider.go @@ -35,9 +35,12 @@ func (http *ServiceProvider) Boot(app foundation.Application) { } func (http *ServiceProvider) registerCommands(app foundation.Application) { - app.MakeArtisan().Register([]consolecontract.Command{ - &console.RequestMakeCommand{}, - &console.ControllerMakeCommand{}, - &console.MiddlewareMakeCommand{}, - }) + artisanFacade := app.MakeArtisan() + if artisanFacade != nil { + app.MakeArtisan().Register([]consolecontract.Command{ + &console.RequestMakeCommand{}, + &console.ControllerMakeCommand{}, + &console.MiddlewareMakeCommand{}, + }) + } } diff --git a/mail/service_provider.go b/mail/service_provider.go index 6626da25c..38c6b5149 100644 --- a/mail/service_provider.go +++ b/mail/service_provider.go @@ -19,11 +19,18 @@ func (route *ServiceProvider) Register(app foundation.Application) { } func (route *ServiceProvider) Boot(app foundation.Application) { - app.MakeQueue().Register([]queue.Job{ - NewSendMailJob(app.MakeConfig()), - }) + queueFacade := app.MakeQueue() + artisanFacade := app.MakeArtisan() - app.MakeArtisan().Register([]consolecontract.Command{ - console.NewMailMakeCommand(), - }) + if queueFacade != nil { + app.MakeQueue().Register([]queue.Job{ + NewSendMailJob(app.MakeConfig()), + }) + } + + if artisanFacade != nil { + app.MakeArtisan().Register([]consolecontract.Command{ + console.NewMailMakeCommand(), + }) + } } diff --git a/testing/docker/database.go b/testing/docker/database.go index 8947a6955..4b89c0d5f 100644 --- a/testing/docker/database.go +++ b/testing/docker/database.go @@ -13,6 +13,7 @@ import ( "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/contracts/testing" frameworkdatabase "github.com/goravel/framework/database" + "github.com/goravel/framework/support/color" supportdocker "github.com/goravel/framework/support/docker" ) @@ -132,7 +133,13 @@ func (receiver *Database) Seed(seeds ...seeder.Seeder) { } } - receiver.app.MakeArtisan().Call(command) + artisan := receiver.app.MakeArtisan() + if artisan == nil { + color.Red().Println("artisan instance is not available") + return + } + + artisan.Call(command) } func (receiver *Database) Stop() error { diff --git a/testing/service_provider.go b/testing/service_provider.go index 04281dbf2..edbbc3d50 100644 --- a/testing/service_provider.go +++ b/testing/service_provider.go @@ -7,7 +7,7 @@ import ( const Binding = "goravel.testing" -var artisanFacades contractsconsole.Artisan +var artisanFacade contractsconsole.Artisan type ServiceProvider struct { } @@ -19,5 +19,5 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { } func (receiver *ServiceProvider) Boot(app foundation.Application) { - artisanFacades = app.MakeArtisan() + artisanFacade = app.MakeArtisan() } diff --git a/testing/test_case.go b/testing/test_case.go index b0414751b..f058d41c6 100644 --- a/testing/test_case.go +++ b/testing/test_case.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/goravel/framework/contracts/database/seeder" + "github.com/goravel/framework/support/color" ) type TestCase struct { @@ -17,10 +18,18 @@ func (receiver *TestCase) Seed(seeds ...seeder.Seeder) { command += fmt.Sprintf(" %s", seed.Signature()) } } + if artisanFacade == nil { + color.Red().Println("Error: Artisan facade is not initialized. Cannot seed the database.") + return + } - artisanFacades.Call(command) + artisanFacade.Call(command) } func (receiver *TestCase) RefreshDatabase(seeds ...seeder.Seeder) { - artisanFacades.Call("migrate:refresh") + if artisanFacade == nil { + color.Red().Println("Error: Artisan facade is not initialized. Cannot refresh the database.") + return + } + artisanFacade.Call("migrate:refresh") } From 188012d84ac04d04e5797aa9cb71dc1ae562583a Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 15:47:19 +0530 Subject: [PATCH 08/32] fix:lint error --- testing/test_case_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/test_case_test.go b/testing/test_case_test.go index dc8a04c66..8701cbc07 100644 --- a/testing/test_case_test.go +++ b/testing/test_case_test.go @@ -22,7 +22,7 @@ func TestTestCaseSuite(t *testing.T) { func (s *TestCaseSuite) SetupTest() { s.mockArtisan = &consolemocks.Artisan{} s.testCase = &TestCase{} - artisanFacades = s.mockArtisan + artisanFacade = s.mockArtisan } func (s *TestCaseSuite) TestSeed() { From 7f0dbc9ce9ef985638a5cfcea12f84578baa7f8a Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 15:57:58 +0530 Subject: [PATCH 09/32] fix:test error --- filesystem/file.go | 25 ++++--------------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/filesystem/file.go b/filesystem/file.go index 06e36527d..e8657a58e 100644 --- a/filesystem/file.go +++ b/filesystem/file.go @@ -25,10 +25,6 @@ type File struct { } func NewFile(file string) (*File, error) { - if err := checkFacades(); err != nil { - return nil, err - } - if !supportfile.Exists(file) { return nil, errors.New("file doesn't exist") } @@ -43,10 +39,6 @@ func NewFile(file string) (*File, error) { } func NewFileFromRequest(fileHeader *multipart.FileHeader) (*File, error) { - if err := checkFacades(); err != nil { - return nil, err - } - src, err := fileHeader.Open() if err != nil { return nil, err @@ -119,6 +111,10 @@ func (f *File) HashName(path ...string) string { } func (f *File) LastModified() (time.Time, error) { + if f.config == nil { + return time.Time{}, errors.New("config facade is not initialized") + } + return supportfile.LastModified(f.path, f.config.GetString("app.timezone")) } @@ -137,16 +133,3 @@ func (f *File) Store(path string) (string, error) { func (f *File) StoreAs(path string, name string) (string, error) { return f.storage.Disk(f.disk).PutFileAs(path, f, name) } - -// CheckFacades ensures that ConfigFacade and StorageFacade are properly initialized. -func checkFacades() error { - if ConfigFacade == nil { - return errors.New("config facade is not initialized") - } - - if StorageFacade == nil { - return errors.New("storage facade is not initialized") - } - - return nil -} From e0d739cdd1b0f2ced4ef5b3deb494e3ed0273e60 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 16:05:34 +0530 Subject: [PATCH 10/32] fix nil error --- cache/service_provider.go | 9 ++++++--- foundation/application.go | 28 ++++++++++++++++++++++------ mail/service_provider.go | 11 ++++------- 3 files changed, 32 insertions(+), 16 deletions(-) diff --git a/cache/service_provider.go b/cache/service_provider.go index f60ca980f..5fe2ec6fb 100644 --- a/cache/service_provider.go +++ b/cache/service_provider.go @@ -26,7 +26,10 @@ func (database *ServiceProvider) Boot(app foundation.Application) { } func (database *ServiceProvider) registerCommands(app foundation.Application) { - app.MakeArtisan().Register([]contractsconsole.Command{ - console.NewClearCommand(app.MakeCache()), - }) + artisanFacade := app.MakeArtisan() + if artisanFacade != nil { + artisanFacade.Register([]contractsconsole.Command{ + console.NewClearCommand(app.MakeCache()), + }) + } } diff --git a/foundation/application.go b/foundation/application.go index 39d51b397..254af6673 100644 --- a/foundation/application.go +++ b/foundation/application.go @@ -3,6 +3,7 @@ package foundation import ( "context" "flag" + "github.com/goravel/framework/support/carbon" "os" "path/filepath" "strings" @@ -13,7 +14,6 @@ import ( "github.com/goravel/framework/foundation/console" "github.com/goravel/framework/foundation/json" "github.com/goravel/framework/support" - "github.com/goravel/framework/support/carbon" "github.com/goravel/framework/support/color" ) @@ -132,7 +132,13 @@ func (app *Application) CurrentLocale(ctx context.Context) string { } func (app *Application) SetLocale(ctx context.Context, locale string) context.Context { - return app.MakeLang(ctx).SetLocale(locale) + lang := app.MakeLang(ctx) + if lang == nil { + color.Red().Println("Error: Lang facade not initialized.") + return ctx + } + + return lang.SetLocale(locale) } func (app *Application) SetJson(j foundation.Json) { @@ -167,7 +173,9 @@ func (app *Application) addPublishGroup(group string, paths map[string]string) { // bootArtisan Boot artisan command. func (app *Application) bootArtisan() { - app.MakeArtisan().Run(os.Args, true) + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Run(os.Args, true) + } } // getBaseServiceProviders Get base service providers. @@ -179,7 +187,11 @@ func (app *Application) getBaseServiceProviders() []foundation.ServiceProvider { // getConfiguredServiceProviders Get configured service providers. func (app *Application) getConfiguredServiceProviders() []foundation.ServiceProvider { - return app.MakeConfig().Get("app.providers").([]foundation.ServiceProvider) + if configFacade := app.MakeConfig(); configFacade != nil { + return configFacade.Get("app.providers").([]foundation.ServiceProvider) + } + + return []foundation.ServiceProvider{} } // registerBaseServiceProviders Register base service providers. @@ -217,11 +229,15 @@ func (app *Application) bootServiceProviders(serviceProviders []foundation.Servi } func (app *Application) registerCommands(commands []consolecontract.Command) { - app.MakeArtisan().Register(commands) + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Register(commands) + } } func (app *Application) setTimezone() { - carbon.SetTimezone(app.MakeConfig().GetString("app.timezone", carbon.UTC)) + if configFacade := app.MakeConfig(); configFacade != nil { + carbon.SetTimezone(configFacade.GetString("app.timezone", carbon.UTC)) + } } func setEnv() { diff --git a/mail/service_provider.go b/mail/service_provider.go index 38c6b5149..a77c3401b 100644 --- a/mail/service_provider.go +++ b/mail/service_provider.go @@ -19,17 +19,14 @@ func (route *ServiceProvider) Register(app foundation.Application) { } func (route *ServiceProvider) Boot(app foundation.Application) { - queueFacade := app.MakeQueue() - artisanFacade := app.MakeArtisan() - - if queueFacade != nil { - app.MakeQueue().Register([]queue.Job{ + if queueFacade := app.MakeQueue(); queueFacade != nil { + queueFacade.Register([]queue.Job{ NewSendMailJob(app.MakeConfig()), }) } - if artisanFacade != nil { - app.MakeArtisan().Register([]consolecontract.Command{ + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Register([]consolecontract.Command{ console.NewMailMakeCommand(), }) } From 64954607b8b40738a0dad157dc3419bba036616f Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Thu, 12 Sep 2024 21:48:02 +0530 Subject: [PATCH 11/32] fix nil error --- auth/service_provider.go | 5 ++--- cache/service_provider.go | 3 +-- database/service_provider.go | 9 ++++----- foundation/application.go | 2 +- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/auth/service_provider.go b/auth/service_provider.go index b1c682906..384007274 100644 --- a/auth/service_provider.go +++ b/auth/service_provider.go @@ -32,9 +32,8 @@ func (database *ServiceProvider) Boot(app foundation.Application) { } func (database *ServiceProvider) registerCommands(app foundation.Application) { - artisan := app.MakeArtisan() - if artisan != nil { - artisan.Register([]contractconsole.Command{ + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Register([]contractconsole.Command{ console.NewJwtSecretCommand(app.MakeConfig()), console.NewPolicyMakeCommand(), }) diff --git a/cache/service_provider.go b/cache/service_provider.go index 5fe2ec6fb..3405ee47d 100644 --- a/cache/service_provider.go +++ b/cache/service_provider.go @@ -26,8 +26,7 @@ func (database *ServiceProvider) Boot(app foundation.Application) { } func (database *ServiceProvider) registerCommands(app foundation.Application) { - artisanFacade := app.MakeArtisan() - if artisanFacade != nil { + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { artisanFacade.Register([]contractsconsole.Command{ console.NewClearCommand(app.MakeCache()), }) diff --git a/database/service_provider.go b/database/service_provider.go index 617563c23..92e9a76ec 100644 --- a/database/service_provider.go +++ b/database/service_provider.go @@ -46,16 +46,15 @@ func (database *ServiceProvider) Boot(app foundation.Application) { func (database *ServiceProvider) registerCommands(app foundation.Application) { config := app.MakeConfig() seeder := app.MakeSeeder() - artisan := app.MakeArtisan() - if artisan != nil { - artisan.Register([]consolecontract.Command{ + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Register([]consolecontract.Command{ console.NewMigrateMakeCommand(config), console.NewMigrateCommand(config), console.NewMigrateRollbackCommand(config), console.NewMigrateResetCommand(config), - console.NewMigrateRefreshCommand(config, artisan), - console.NewMigrateFreshCommand(config, artisan), + console.NewMigrateRefreshCommand(config, artisanFacade), + console.NewMigrateFreshCommand(config, artisanFacade), console.NewMigrateStatusCommand(config), console.NewModelMakeCommand(), console.NewObserverMakeCommand(), diff --git a/foundation/application.go b/foundation/application.go index 254af6673..9b89fcefd 100644 --- a/foundation/application.go +++ b/foundation/application.go @@ -3,7 +3,6 @@ package foundation import ( "context" "flag" - "github.com/goravel/framework/support/carbon" "os" "path/filepath" "strings" @@ -14,6 +13,7 @@ import ( "github.com/goravel/framework/foundation/console" "github.com/goravel/framework/foundation/json" "github.com/goravel/framework/support" + "github.com/goravel/framework/support/carbon" "github.com/goravel/framework/support/color" ) From e359bb7ec61ef1a4f19042578bfe91f8f6f53f2c Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Mon, 16 Sep 2024 00:38:33 +0530 Subject: [PATCH 12/32] fix nilaway erro --- console/console/key_generate_command.go | 5 +++ console/service_provider.go | 17 ++++----- database/gorm/gorm.go | 6 ++-- filesystem/file.go | 16 +++++++++ mail/job.go | 48 ++++++++++++++++++++++++- 5 files changed, 81 insertions(+), 11 deletions(-) diff --git a/console/console/key_generate_command.go b/console/console/key_generate_command.go index 9eb6935de..facf2d283 100644 --- a/console/console/key_generate_command.go +++ b/console/console/key_generate_command.go @@ -1,6 +1,7 @@ package console import ( + "errors" "os" "strings" @@ -41,6 +42,10 @@ func (receiver *KeyGenerateCommand) Extend() command.Extend { // Handle Execute the console command. func (receiver *KeyGenerateCommand) Handle(ctx console.Context) error { + if receiver.config == nil { + return errors.New("config facade not set") + } + if receiver.config.GetString("app.env") == "production" { color.Yellow().Println("**************************************") color.Yellow().Println("* Application In Production! *") diff --git a/console/service_provider.go b/console/service_provider.go index 4c8eb0eb0..facede36c 100644 --- a/console/service_provider.go +++ b/console/service_provider.go @@ -25,12 +25,13 @@ func (receiver *ServiceProvider) Boot(app foundation.Application) { } func (receiver *ServiceProvider) registerCommands(app foundation.Application) { - artisan := app.MakeArtisan() - config := app.MakeConfig() - artisan.Register([]consolecontract.Command{ - console.NewListCommand(artisan), - console.NewKeyGenerateCommand(config), - console.NewMakeCommand(), - console.NewBuildCommand(config), - }) + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + config := app.MakeConfig() + artisanFacade.Register([]consolecontract.Command{ + console.NewListCommand(artisanFacade), + console.NewKeyGenerateCommand(config), + console.NewMakeCommand(), + console.NewBuildCommand(config), + }) + } } diff --git a/database/gorm/gorm.go b/database/gorm/gorm.go index 076b086df..ff9efeac7 100644 --- a/database/gorm/gorm.go +++ b/database/gorm/gorm.go @@ -52,8 +52,10 @@ func (r *GormImpl) Make() (*gormio.DB, error) { return nil, fmt.Errorf("init gorm dialector error: %v", err) } - if err := r.init(writeDialectors[0]); err != nil { - return nil, err + if len(writeDialectors) > 0 { + if err := r.init(writeDialectors[0]); err != nil { + return nil, err + } } if err := r.configurePool(); err != nil { diff --git a/filesystem/file.go b/filesystem/file.go index e8657a58e..174096c36 100644 --- a/filesystem/file.go +++ b/filesystem/file.go @@ -25,6 +25,14 @@ type File struct { } func NewFile(file string) (*File, error) { + if ConfigFacade == nil { + return nil, errors.New("config facade not set") + } + + if StorageFacade == nil { + return nil, errors.New("storage facade not set") + } + if !supportfile.Exists(file) { return nil, errors.New("file doesn't exist") } @@ -39,6 +47,14 @@ func NewFile(file string) (*File, error) { } func NewFileFromRequest(fileHeader *multipart.FileHeader) (*File, error) { + if ConfigFacade == nil { + return nil, errors.New("config facade not set") + } + + if StorageFacade == nil { + return nil, errors.New("storage facade not set") + } + src, err := fileHeader.Open() if err != nil { return nil, err diff --git a/mail/job.go b/mail/job.go index 90a576bad..2eec2ab61 100644 --- a/mail/job.go +++ b/mail/job.go @@ -1,6 +1,8 @@ package mail import ( + "fmt" + "github.com/goravel/framework/contracts/config" ) @@ -21,5 +23,49 @@ func (r *SendMailJob) Signature() string { // Handle Execute the job. func (r *SendMailJob) Handle(args ...any) error { - return SendMail(r.config, args[0].(string), args[1].(string), args[2].(string), args[3].(string), args[4].([]string), args[5].([]string), args[6].([]string), args[7].([]string)) + if len(args) != 8 { + return fmt.Errorf("expected 8 arguments, got %d", len(args)) + } + + from, ok := args[0].(string) + if !ok { + return fmt.Errorf("argument 0 should be of type string") + } + + subject, ok := args[1].(string) + if !ok { + return fmt.Errorf("argument 1 should be of type string") + } + + body, ok := args[2].(string) + if !ok { + return fmt.Errorf("argument 2 should be of type string") + } + + recipient, ok := args[3].(string) + if !ok { + return fmt.Errorf("argument 3 should be of type string") + } + + cc, ok := args[4].([]string) + if !ok { + return fmt.Errorf("argument 4 should be of type []string") + } + + bcc, ok := args[5].([]string) + if !ok { + return fmt.Errorf("argument 5 should be of type []string") + } + + replyTo, ok := args[6].([]string) + if !ok { + return fmt.Errorf("argument 6 should be of type []string") + } + + attachments, ok := args[7].([]string) + if !ok { + return fmt.Errorf("argument 7 should be of type []string") + } + + return SendMail(r.config, from, subject, body, recipient, cc, bcc, replyTo, attachments) } From 1599d093252ce89fc1163d58d816f379942c78ce Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Mon, 16 Sep 2024 00:47:30 +0530 Subject: [PATCH 13/32] fix nil errors --- database/service_provider.go | 5 ++--- event/service_provider.go | 10 ++++++---- http/service_provider.go | 9 ++------- queue/service_provider.go | 12 +++++------- validation/service_provider.go | 14 ++++++-------- 5 files changed, 21 insertions(+), 29 deletions(-) diff --git a/database/service_provider.go b/database/service_provider.go index 92e9a76ec..42af0eb9a 100644 --- a/database/service_provider.go +++ b/database/service_provider.go @@ -44,10 +44,9 @@ func (database *ServiceProvider) Boot(app foundation.Application) { } func (database *ServiceProvider) registerCommands(app foundation.Application) { - config := app.MakeConfig() - seeder := app.MakeSeeder() - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + config := app.MakeConfig() + seeder := app.MakeSeeder() artisanFacade.Register([]consolecontract.Command{ console.NewMigrateMakeCommand(config), console.NewMigrateCommand(config), diff --git a/event/service_provider.go b/event/service_provider.go index ffaa25c24..4bedea6ab 100644 --- a/event/service_provider.go +++ b/event/service_provider.go @@ -22,8 +22,10 @@ func (receiver *ServiceProvider) Boot(app foundation.Application) { } func (receiver *ServiceProvider) registerCommands(app foundation.Application) { - app.MakeArtisan().Register([]console.Command{ - &eventConsole.EventMakeCommand{}, - &eventConsole.ListenerMakeCommand{}, - }) + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Register([]console.Command{ + &eventConsole.EventMakeCommand{}, + &eventConsole.ListenerMakeCommand{}, + }) + } } diff --git a/http/service_provider.go b/http/service_provider.go index f22d53d4e..224fda9ee 100644 --- a/http/service_provider.go +++ b/http/service_provider.go @@ -31,13 +31,8 @@ func (http *ServiceProvider) Boot(app foundation.Application) { CacheFacade = app.MakeCache() RateLimiterFacade = app.MakeRateLimiter() - http.registerCommands(app) -} - -func (http *ServiceProvider) registerCommands(app foundation.Application) { - artisanFacade := app.MakeArtisan() - if artisanFacade != nil { - app.MakeArtisan().Register([]consolecontract.Command{ + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Register([]consolecontract.Command{ &console.RequestMakeCommand{}, &console.ControllerMakeCommand{}, &console.MiddlewareMakeCommand{}, diff --git a/queue/service_provider.go b/queue/service_provider.go index dfebea0a1..0a91b4383 100644 --- a/queue/service_provider.go +++ b/queue/service_provider.go @@ -18,11 +18,9 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { } func (receiver *ServiceProvider) Boot(app foundation.Application) { - receiver.registerCommands(app) -} - -func (receiver *ServiceProvider) registerCommands(app foundation.Application) { - app.MakeArtisan().Register([]console.Command{ - &queueConsole.JobMakeCommand{}, - }) + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Register([]console.Command{ + &queueConsole.JobMakeCommand{}, + }) + } } diff --git a/validation/service_provider.go b/validation/service_provider.go index 6b1eacdfb..b68254ba9 100644 --- a/validation/service_provider.go +++ b/validation/service_provider.go @@ -18,12 +18,10 @@ func (database *ServiceProvider) Register(app foundation.Application) { } func (database *ServiceProvider) Boot(app foundation.Application) { - database.registerCommands(app) -} - -func (database *ServiceProvider) registerCommands(app foundation.Application) { - app.MakeArtisan().Register([]consolecontract.Command{ - &console.RuleMakeCommand{}, - &console.FilterMakeCommand{}, - }) + if artisanFacade := app.MakeArtisan(); artisanFacade != nil { + artisanFacade.Register([]consolecontract.Command{ + &console.RuleMakeCommand{}, + &console.FilterMakeCommand{}, + }) + } } From 70f858b97a63326c10ce845d71f1f896f9501d63 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Tue, 17 Sep 2024 21:10:53 +0530 Subject: [PATCH 14/32] fix nil errors --- session/manager_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/session/manager_test.go b/session/manager_test.go index 821fffb88..ebf215b94 100644 --- a/session/manager_test.go +++ b/session/manager_test.go @@ -99,10 +99,11 @@ func (s *ManagerTestSuite) TestBuildSession() { s.mockConfig.On("GetString", "session.cookie").Return("test_cookie").Once() session, err := s.manager.BuildSession(driver) - session.Put("name", "goravel") - s.Nil(err) s.NotNil(session) + + session.Put("name", "goravel") + s.Equal("test_cookie", session.GetName()) s.Equal("goravel", session.Get("name")) From 9393c304db5dc354318034a0dc1df2150df4d049 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Tue, 17 Sep 2024 21:18:37 +0530 Subject: [PATCH 15/32] optimize file facade setting --- filesystem/errors.go | 8 ++++++++ filesystem/file.go | 32 ++++++++++++++++++++++++-------- 2 files changed, 32 insertions(+), 8 deletions(-) create mode 100644 filesystem/errors.go diff --git a/filesystem/errors.go b/filesystem/errors.go new file mode 100644 index 000000000..6879f1881 --- /dev/null +++ b/filesystem/errors.go @@ -0,0 +1,8 @@ +package filesystem + +import "errors" + +var ( + ErrConfigFacadeNotSet = errors.New("config facade not set") + ErrStorageFacadeNotSet = errors.New("storage facade not set") +) diff --git a/filesystem/file.go b/filesystem/file.go index 174096c36..389b3dd07 100644 --- a/filesystem/file.go +++ b/filesystem/file.go @@ -29,10 +29,6 @@ func NewFile(file string) (*File, error) { return nil, errors.New("config facade not set") } - if StorageFacade == nil { - return nil, errors.New("storage facade not set") - } - if !supportfile.Exists(file) { return nil, errors.New("file doesn't exist") } @@ -51,10 +47,6 @@ func NewFileFromRequest(fileHeader *multipart.FileHeader) (*File, error) { return nil, errors.New("config facade not set") } - if StorageFacade == nil { - return nil, errors.New("storage facade not set") - } - src, err := fileHeader.Open() if err != nil { return nil, err @@ -143,9 +135,33 @@ func (f *File) Size() (int64, error) { } func (f *File) Store(path string) (string, error) { + if err := f.validateStorageFacade(); err != nil { + return "", err + } + return f.storage.Disk(f.disk).PutFile(path, f) } func (f *File) StoreAs(path string, name string) (string, error) { + if err := f.validateStorageFacade(); err != nil { + return "", err + } + return f.storage.Disk(f.disk).PutFileAs(path, f, name) } + +func (f *File) validateConfigFacade() error { + if f.config == nil { + return ErrConfigFacadeNotSet + } + + return nil +} + +func (f *File) validateStorageFacade() error { + if f.storage == nil { + return ErrStorageFacadeNotSet + } + + return nil +} From f131c2496b74c97e6ffba847f2a6bf24788268e7 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Tue, 17 Sep 2024 21:31:06 +0530 Subject: [PATCH 16/32] . --- log/logrus_writer_test.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/log/logrus_writer_test.go b/log/logrus_writer_test.go index 1fdc8d97b..5308891cd 100644 --- a/log/logrus_writer_test.go +++ b/log/logrus_writer_test.go @@ -404,6 +404,9 @@ func TestLogrusWithCustomLogger(t *testing.T) { filename := "custom.log" logger := NewApplication(mockConfig, json.NewJson()) + + assert.NotNil(t, logger) + logger.Channel("customLogger"). WithTrace(). With(map[string]any{"filename": filename}). @@ -422,6 +425,8 @@ func TestLogrus_Fatal(t *testing.T) { mockDriverConfig(mockConfig) log := NewApplication(mockConfig, json.NewJson()) + assert.NotNil(t, log) + if os.Getenv("FATAL") == "1" { log.Fatal("Goravel") return @@ -442,6 +447,8 @@ func TestLogrus_Fatalf(t *testing.T) { mockDriverConfig(mockConfig) log := NewApplication(mockConfig, json.NewJson()) + assert.NotNil(t, log) + if os.Getenv("FATAL") == "1" { log.Fatalf("Goravel") return From 066ae54557e5f412c5230a16aaa7ff6ce55ecf4d Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Tue, 17 Sep 2024 22:58:41 +0530 Subject: [PATCH 17/32] . --- foundation/application.go | 7 ++++++- log/logrus_writer_test.go | 7 +++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/foundation/application.go b/foundation/application.go index 9b89fcefd..9fe3eb404 100644 --- a/foundation/application.go +++ b/foundation/application.go @@ -91,7 +91,12 @@ func (app *Application) StoragePath(path ...string) string { } func (app *Application) LangPath(path ...string) string { - path = append([]string{app.MakeConfig().GetString("app.lang_path", "lang")}, path...) + defaultPath := "lang" + if configFacade := app.MakeConfig(); configFacade != nil { + defaultPath = configFacade.GetString("app.lang_path", defaultPath) + } + + path = append([]string{defaultPath}, path...) return filepath.Join(path...) } diff --git a/log/logrus_writer_test.go b/log/logrus_writer_test.go index 5308891cd..685d35f26 100644 --- a/log/logrus_writer_test.go +++ b/log/logrus_writer_test.go @@ -407,8 +407,11 @@ func TestLogrusWithCustomLogger(t *testing.T) { assert.NotNil(t, logger) - logger.Channel("customLogger"). - WithTrace(). + channel := logger.Channel("customLogger") + + assert.NotNil(t, channel) + + channel.WithTrace(). With(map[string]any{"filename": filename}). User(map[string]any{"name": "kkumar-gcc"}). Owner("team@goravel.dev"). From 209f95ddb36c8655ccb44eff419dfc14d7395d6a Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Tue, 17 Sep 2024 23:18:34 +0530 Subject: [PATCH 18/32] . --- console/application_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/console/application_test.go b/console/application_test.go index f1d01305b..f528b6868 100644 --- a/console/application_test.go +++ b/console/application_test.go @@ -40,6 +40,8 @@ func TestFlagsToCliFlags(t *testing.T) { // Convert command flags to CLI flags cliFlags := flagsToCliFlags(flags) + assert.NotEmpty(t, cliFlags, "cliFlags should not be empty") + // Assert that the number of CLI flags matches the number of command flags assert.Equal(t, len(cliFlags), len(flags)) From 00616ce29cfc5a74f70fc72b7517d73f45586af5 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Tue, 17 Sep 2024 23:33:47 +0530 Subject: [PATCH 19/32] remove nil error from facades --- facades/app.go | 7 ++++++- facades/errors.go | 7 +++++++ queue/task_test.go | 12 +++++++++++- 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 facades/errors.go diff --git a/facades/app.go b/facades/app.go index a02fbf533..1b01d05cf 100644 --- a/facades/app.go +++ b/facades/app.go @@ -6,5 +6,10 @@ import ( ) func App() foundationcontract.Application { - return foundation.App + app := foundation.App + if app == nil { + panic(ErrApplicationNotSet) + } + + return app } diff --git a/facades/errors.go b/facades/errors.go new file mode 100644 index 000000000..7971b834f --- /dev/null +++ b/facades/errors.go @@ -0,0 +1,7 @@ +package facades + +import "errors" + +var ( + ErrApplicationNotSet = errors.New("application instance not initialized") +) diff --git a/queue/task_test.go b/queue/task_test.go index b95ea731b..e82967195 100644 --- a/queue/task_test.go +++ b/queue/task_test.go @@ -1,6 +1,7 @@ package queue import ( + "fmt" "testing" "github.com/stretchr/testify/assert" @@ -20,7 +21,16 @@ func (receiver *Test) Signature() string { // Handle Execute the job. func (receiver *Test) Handle(args ...any) error { - return file.Create("test.txt", args[0].(string)) + if len(args) == 0 { + return fmt.Errorf("no arguments provided") + } + + arg, ok := args[0].(string) + if !ok { + return fmt.Errorf("expected a string argument") + } + + return file.Create("test.txt", arg) } func TestDispatchSync(t *testing.T) { From e9cbd2e94b20a8c00d9604a5ac58d119cfba14d1 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Tue, 17 Sep 2024 23:50:49 +0530 Subject: [PATCH 20/32] update crypt facade --- crypt/aes.go | 24 ++++++++++++++++++------ crypt/aes_test.go | 19 ++++++++++++++++--- crypt/errors.go | 12 ++++++++++++ crypt/service_provider.go | 2 +- 4 files changed, 47 insertions(+), 10 deletions(-) create mode 100644 crypt/errors.go diff --git a/crypt/aes.go b/crypt/aes.go index bf7d15dc7..a8b3bdb51 100644 --- a/crypt/aes.go +++ b/crypt/aes.go @@ -6,6 +6,7 @@ import ( "crypto/rand" "encoding/base64" "errors" + "fmt" "io" "github.com/goravel/framework/contracts/config" @@ -20,24 +21,35 @@ type AES struct { } // NewAES returns a new AES hasher. -func NewAES(config config.Config, json foundation.Json) *AES { +func NewAES(config config.Config, json foundation.Json) (*AES, error) { + if config == nil { + return nil, ErrConfigNotSet + } + + if json == nil { + return nil, ErrJsonParserNotSet + } + key := config.GetString("app.key") // Don't use AES in artisan when the key is empty. if support.Env == support.EnvArtisan && len(key) == 0 { - return nil + return nil, ErrAppKeyNotSetInArtisan } + keyLength := len(key) // check key length before using it - if len(key) != 16 && len(key) != 24 && len(key) != 32 { - color.Red().Println("[Crypt] Empty or invalid APP_KEY, please reset it.\nExample command:\ngo run . artisan key:generate") - return nil + if keyLength != 16 && keyLength != 24 && keyLength != 32 { + color.Red().Printf("[Crypt] Invalid APP_KEY length. Expected 16, 24, or 32 bytes, but got %d bytes.\n", len(key)) + color.Red().Println("Please reset it using the following command:\ngo run . artisan key:generate") + return nil, fmt.Errorf("%w: %d bytes", ErrInvalidAppKeyLength, keyLength) } + keyBytes := []byte(key) return &AES{ key: keyBytes, json: json, - } + }, nil } // EncryptString encrypts the given string, and returns the iv and ciphertext as base64 encoded strings. diff --git a/crypt/aes_test.go b/crypt/aes_test.go index 697c6e2d1..beb61e944 100644 --- a/crypt/aes_test.go +++ b/crypt/aes_test.go @@ -3,6 +3,7 @@ package crypt import ( "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "github.com/goravel/framework/foundation/json" @@ -17,8 +18,12 @@ type AesTestSuite struct { func TestAesTestSuite(t *testing.T) { mockConfig := &configmock.Config{} mockConfig.On("GetString", "app.key").Return("11111111111111111111111111111111").Once() + aes, err := NewAES(mockConfig, json.NewJson()) + + assert.NoError(t, err) + suite.Run(t, &AesTestSuite{ - aes: NewAES(mockConfig, json.NewJson()), + aes: aes, }) mockConfig.AssertExpectations(t) } @@ -61,7 +66,11 @@ func (s *AesTestSuite) TestDecryptString() { func Benchmark_EncryptString(b *testing.B) { mockConfig := &configmock.Config{} mockConfig.On("GetString", "app.key").Return("11111111111111111111111111111111").Once() - aes := NewAES(mockConfig, json.NewJson()) + aes, err := NewAES(mockConfig, json.NewJson()) + if err != nil { + b.Fatal(err) + } + b.ResetTimer() for i := 0; i < b.N; i++ { @@ -75,7 +84,11 @@ func Benchmark_EncryptString(b *testing.B) { func Benchmark_DecryptString(b *testing.B) { mockConfig := &configmock.Config{} mockConfig.On("GetString", "app.key").Return("11111111111111111111111111111111").Once() - aes := NewAES(mockConfig, json.NewJson()) + aes, err := NewAES(mockConfig, json.NewJson()) + if err != nil { + b.Fatal(err) + } + payload, err := aes.EncryptString("Goravel") if err != nil { b.Error(err) diff --git a/crypt/errors.go b/crypt/errors.go new file mode 100644 index 000000000..c2b4c032e --- /dev/null +++ b/crypt/errors.go @@ -0,0 +1,12 @@ +package crypt + +import ( + "errors" +) + +var ( + ErrConfigNotSet = errors.New("config must not be nil") + ErrJsonParserNotSet = errors.New("JSON parser must not be nil") + ErrAppKeyNotSetInArtisan = errors.New("APP_KEY is required in artisan environment") + ErrInvalidAppKeyLength = errors.New("invalid APP_KEY length") +) diff --git a/crypt/service_provider.go b/crypt/service_provider.go index c79ef4b50..ac9d1170d 100644 --- a/crypt/service_provider.go +++ b/crypt/service_provider.go @@ -11,7 +11,7 @@ type ServiceProvider struct { func (crypt *ServiceProvider) Register(app foundation.Application) { app.Singleton(Binding, func(app foundation.Application) (any, error) { - return NewAES(app.MakeConfig(), app.GetJson()), nil + return NewAES(app.MakeConfig(), app.GetJson()) }) } From c670ff7d8d59c6e5235f51590c27077e56bb2e4d Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Wed, 18 Sep 2024 00:01:17 +0530 Subject: [PATCH 21/32] nilaway:fix for session --- session/session.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/session/session.go b/session/session.go index 4e9fc0e4e..108fc3943 100644 --- a/session/session.go +++ b/session/session.go @@ -156,7 +156,7 @@ func (s *Session) Save() error { return err } - if err = s.validateDriver(); err != nil { + if err := s.validateDriver(); err != nil { return err } From 0ed69499a0e4f23ea8abb38851e29dd5ad2dcf79 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Wed, 18 Sep 2024 00:07:10 +0530 Subject: [PATCH 22/32] nilaway:fix for file --- filesystem/file_test.go | 11 ++++++----- session/session.go | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/filesystem/file_test.go b/filesystem/file_test.go index cfdd255e1..12d5bdc83 100644 --- a/filesystem/file_test.go +++ b/filesystem/file_test.go @@ -31,16 +31,17 @@ func (s *FileTestSuite) SetupTest() { s.mockConfig.On("GetString", "filesystems.default").Return("local").Once() ConfigFacade = s.mockConfig - var err error - s.file, err = NewFile("./file.go") + f, err := NewFile("./file.go") s.Nil(err) - s.NotNil(s.file) + s.NotNil(f) + + s.file = f } func (s *FileTestSuite) TestNewFile_Error() { - file, err := NewFile("./file1.go") + f, err := NewFile("./file1.go") s.EqualError(err, "file doesn't exist") - s.Nil(file) + s.Nil(f) } func (s *FileTestSuite) TestGetClientOriginalName() { diff --git a/session/session.go b/session/session.go index 108fc3943..4e9fc0e4e 100644 --- a/session/session.go +++ b/session/session.go @@ -156,7 +156,7 @@ func (s *Session) Save() error { return err } - if err := s.validateDriver(); err != nil { + if err = s.validateDriver(); err != nil { return err } From 5b438042beaa8ea98f5ae2b32ba0e790394b6426 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Wed, 18 Sep 2024 00:09:54 +0530 Subject: [PATCH 23/32] nilaway:fix for file --- filesystem/local_test.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/filesystem/local_test.go b/filesystem/local_test.go index 13bf57d11..cb9881215 100644 --- a/filesystem/local_test.go +++ b/filesystem/local_test.go @@ -46,13 +46,17 @@ func (s *LocalTestSuite) SetupTest() { s.mockConfig.On("GetString", "filesystems.disks.local.url").Return("https://goravel.dev").Once() ConfigFacade = s.mockConfig - s.local, err = NewLocal(s.mockConfig, "local") + l, err := NewLocal(s.mockConfig, "local") s.Nil(err) - s.NotNil(s.local) + s.NotNil(l) - s.file, err = NewFile("./file.go") + s.local = l + + f, err := NewFile("./file.go") s.Nil(err) - s.NotNil(s.file) + s.NotNil(f) + + s.file = f s.mockConfig.AssertExpectations(s.T()) } From fa97fd20b6b803d422511da9e2ac721ce0cc8e43 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Wed, 18 Sep 2024 00:17:37 +0530 Subject: [PATCH 24/32] nilaway:fix for json --- support/json/errors.go | 7 +++++++ support/json/json.go | 14 ++++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 support/json/errors.go diff --git a/support/json/errors.go b/support/json/errors.go new file mode 100644 index 000000000..7adff9010 --- /dev/null +++ b/support/json/errors.go @@ -0,0 +1,7 @@ +package json + +import "errors" + +var ( + ErrApplicationNotSet = errors.New("application instance not initialized") +) diff --git a/support/json/json.go b/support/json/json.go index 5ec84650e..4092dd966 100644 --- a/support/json/json.go +++ b/support/json/json.go @@ -4,12 +4,22 @@ import "github.com/goravel/framework/foundation" // Marshal serializes the given value to a JSON-encoded byte slice. func Marshal(v any) ([]byte, error) { - return foundation.App.GetJson().Marshal(v) + app := foundation.App + if app == nil { + return nil, ErrApplicationNotSet + } + + return app.GetJson().Marshal(v) } // Unmarshal deserializes the given JSON-encoded byte slice into the provided value. func Unmarshal(data []byte, v any) error { - return foundation.App.GetJson().Unmarshal(data, v) + app := foundation.App + if app == nil { + return ErrApplicationNotSet + } + + return app.GetJson().Unmarshal(data, v) } // MarshalString serializes the given value to a JSON-encoded string. From 4a2f4aad8325a94c15596941c342f8e50375edd9 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Wed, 18 Sep 2024 09:31:43 +0530 Subject: [PATCH 25/32] fix:lint --- filesystem/errors.go | 1 - filesystem/file.go | 8 -------- 2 files changed, 9 deletions(-) diff --git a/filesystem/errors.go b/filesystem/errors.go index 6879f1881..4751296a4 100644 --- a/filesystem/errors.go +++ b/filesystem/errors.go @@ -3,6 +3,5 @@ package filesystem import "errors" var ( - ErrConfigFacadeNotSet = errors.New("config facade not set") ErrStorageFacadeNotSet = errors.New("storage facade not set") ) diff --git a/filesystem/file.go b/filesystem/file.go index 389b3dd07..324e90a60 100644 --- a/filesystem/file.go +++ b/filesystem/file.go @@ -150,14 +150,6 @@ func (f *File) StoreAs(path string, name string) (string, error) { return f.storage.Disk(f.disk).PutFileAs(path, f, name) } -func (f *File) validateConfigFacade() error { - if f.config == nil { - return ErrConfigFacadeNotSet - } - - return nil -} - func (f *File) validateStorageFacade() error { if f.storage == nil { return ErrStorageFacadeNotSet From f505eed4168bc770364091578b33714377eeee46 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Wed, 18 Sep 2024 09:36:40 +0530 Subject: [PATCH 26/32] fix:test --- foundation/application_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/foundation/application_test.go b/foundation/application_test.go index a84972fce..53c4a856e 100644 --- a/foundation/application_test.go +++ b/foundation/application_test.go @@ -19,6 +19,7 @@ import ( "github.com/goravel/framework/database/gorm" "github.com/goravel/framework/event" "github.com/goravel/framework/filesystem" + "github.com/goravel/framework/foundation/json" "github.com/goravel/framework/grpc" "github.com/goravel/framework/hash" "github.com/goravel/framework/http" @@ -204,6 +205,7 @@ func (s *ApplicationTestSuite) TestMakeCrypt() { s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { return mockConfig, nil }) + s.app.SetJson(json.NewJson()) serviceProvider := &crypt.ServiceProvider{} serviceProvider.Register(s.app) From c01fbc938129e1e828a5dfa7d8d7b640e223a85a Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Fri, 27 Sep 2024 05:35:19 +0530 Subject: [PATCH 27/32] resolve comments --- auth/service_provider.go | 10 ++++----- cache/service_provider.go | 8 +++---- console/application.go | 28 ++++++++++++++---------- console/application_test.go | 2 -- console/console/key_generate_command.go | 5 ----- console/service_provider.go | 25 ++++++++++++++------- crypt/aes.go | 8 ------- database/gorm/gorm.go | 10 +++++---- event/service_provider.go | 10 ++++----- facades/app.go | 7 +++--- foundation/application.go | 16 ++++++++++---- http/service_provider.go | 16 ++++++++------ mail/job.go | 16 +++++++------- mail/service_provider.go | 29 ++++++++++++++++++------- queue/service_provider.go | 8 +++---- session/errors.go | 4 +++- session/service_provider.go | 8 +++++++ testing/service_provider.go | 4 ++++ testing/test_case.go | 9 -------- 19 files changed, 121 insertions(+), 102 deletions(-) diff --git a/auth/service_provider.go b/auth/service_provider.go index 384007274..2f2d41155 100644 --- a/auth/service_provider.go +++ b/auth/service_provider.go @@ -32,10 +32,8 @@ func (database *ServiceProvider) Boot(app foundation.Application) { } func (database *ServiceProvider) registerCommands(app foundation.Application) { - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Register([]contractconsole.Command{ - console.NewJwtSecretCommand(app.MakeConfig()), - console.NewPolicyMakeCommand(), - }) - } + app.Commands([]contractconsole.Command{ + console.NewJwtSecretCommand(app.MakeConfig()), + console.NewPolicyMakeCommand(), + }) } diff --git a/cache/service_provider.go b/cache/service_provider.go index 3405ee47d..7ed8bfd12 100644 --- a/cache/service_provider.go +++ b/cache/service_provider.go @@ -26,9 +26,7 @@ func (database *ServiceProvider) Boot(app foundation.Application) { } func (database *ServiceProvider) registerCommands(app foundation.Application) { - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Register([]contractsconsole.Command{ - console.NewClearCommand(app.MakeCache()), - }) - } + app.Commands([]contractsconsole.Command{ + console.NewClearCommand(app.MakeCache()), + }) } diff --git a/console/application.go b/console/application.go index 2da4ee378..a5a858836 100644 --- a/console/application.go +++ b/console/application.go @@ -47,28 +47,32 @@ func (c *Application) Register(commands []console.Command) { // Call Run an Artisan console command by name. func (c *Application) Call(command string) { - if len(os.Args) > 0 { - commands := []string{os.Args[0]} + if len(os.Args) == 0 { + return + } - if c.isArtisan { - commands = append(commands, "artisan") - } + commands := []string{os.Args[0]} - c.Run(append(commands, strings.Split(command, " ")...), false) + if c.isArtisan { + commands = append(commands, "artisan") } + + c.Run(append(commands, strings.Split(command, " ")...), false) } // CallAndExit Run an Artisan console command by name and exit. func (c *Application) CallAndExit(command string) { - if len(os.Args) > 0 { - commands := []string{os.Args[0]} + if len(os.Args) == 0 { + return + } - if c.isArtisan { - commands = append(commands, "artisan") - } + commands := []string{os.Args[0]} - c.Run(append(commands, strings.Split(command, " ")...), true) + if c.isArtisan { + commands = append(commands, "artisan") } + + c.Run(append(commands, strings.Split(command, " ")...), true) } // Run a command. Args come from os.Args. diff --git a/console/application_test.go b/console/application_test.go index f528b6868..f1d01305b 100644 --- a/console/application_test.go +++ b/console/application_test.go @@ -40,8 +40,6 @@ func TestFlagsToCliFlags(t *testing.T) { // Convert command flags to CLI flags cliFlags := flagsToCliFlags(flags) - assert.NotEmpty(t, cliFlags, "cliFlags should not be empty") - // Assert that the number of CLI flags matches the number of command flags assert.Equal(t, len(cliFlags), len(flags)) diff --git a/console/console/key_generate_command.go b/console/console/key_generate_command.go index facf2d283..9eb6935de 100644 --- a/console/console/key_generate_command.go +++ b/console/console/key_generate_command.go @@ -1,7 +1,6 @@ package console import ( - "errors" "os" "strings" @@ -42,10 +41,6 @@ func (receiver *KeyGenerateCommand) Extend() command.Extend { // Handle Execute the console command. func (receiver *KeyGenerateCommand) Handle(ctx console.Context) error { - if receiver.config == nil { - return errors.New("config facade not set") - } - if receiver.config.GetString("app.env") == "production" { color.Yellow().Println("**************************************") color.Yellow().Println("* Application In Production! *") diff --git a/console/service_provider.go b/console/service_provider.go index facede36c..f31bae2e9 100644 --- a/console/service_provider.go +++ b/console/service_provider.go @@ -4,6 +4,7 @@ import ( "github.com/goravel/framework/console/console" consolecontract "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" + "github.com/goravel/framework/support/color" ) const Binding = "goravel.console" @@ -25,13 +26,21 @@ func (receiver *ServiceProvider) Boot(app foundation.Application) { } func (receiver *ServiceProvider) registerCommands(app foundation.Application) { - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - config := app.MakeConfig() - artisanFacade.Register([]consolecontract.Command{ - console.NewListCommand(artisanFacade), - console.NewKeyGenerateCommand(config), - console.NewMakeCommand(), - console.NewBuildCommand(config), - }) + artisanFacade := app.MakeArtisan() + if artisanFacade == nil { + color.Yellow().Println("Warning: Artisan Facade is not initialized. Skipping command registration.") + return } + + configFacade := app.MakeConfig() + if configFacade == nil { + color.Yellow().Println("Warning: Config Facade is not initialized. Skipping certain command registrations.") + } + + artisanFacade.Register([]consolecontract.Command{ + console.NewListCommand(artisanFacade), + console.NewKeyGenerateCommand(configFacade), + console.NewMakeCommand(), + console.NewBuildCommand(configFacade), + }) } diff --git a/crypt/aes.go b/crypt/aes.go index a8b3bdb51..ef82b83e0 100644 --- a/crypt/aes.go +++ b/crypt/aes.go @@ -22,14 +22,6 @@ type AES struct { // NewAES returns a new AES hasher. func NewAES(config config.Config, json foundation.Json) (*AES, error) { - if config == nil { - return nil, ErrConfigNotSet - } - - if json == nil { - return nil, ErrJsonParserNotSet - } - key := config.GetString("app.key") // Don't use AES in artisan when the key is empty. diff --git a/database/gorm/gorm.go b/database/gorm/gorm.go index ff9efeac7..d8a923851 100644 --- a/database/gorm/gorm.go +++ b/database/gorm/gorm.go @@ -52,10 +52,12 @@ func (r *GormImpl) Make() (*gormio.DB, error) { return nil, fmt.Errorf("init gorm dialector error: %v", err) } - if len(writeDialectors) > 0 { - if err := r.init(writeDialectors[0]); err != nil { - return nil, err - } + if len(writeDialectors) == 0 { + return nil, errors.New("no write dialectors found") + } + + if err := r.init(writeDialectors[0]); err != nil { + return nil, err } if err := r.configurePool(); err != nil { diff --git a/event/service_provider.go b/event/service_provider.go index 4bedea6ab..f4346a2c4 100644 --- a/event/service_provider.go +++ b/event/service_provider.go @@ -22,10 +22,8 @@ func (receiver *ServiceProvider) Boot(app foundation.Application) { } func (receiver *ServiceProvider) registerCommands(app foundation.Application) { - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Register([]console.Command{ - &eventConsole.EventMakeCommand{}, - &eventConsole.ListenerMakeCommand{}, - }) - } + app.Commands([]console.Command{ + &eventConsole.EventMakeCommand{}, + &eventConsole.ListenerMakeCommand{}, + }) } diff --git a/facades/app.go b/facades/app.go index 1b01d05cf..429b6c6fc 100644 --- a/facades/app.go +++ b/facades/app.go @@ -6,10 +6,9 @@ import ( ) func App() foundationcontract.Application { - app := foundation.App - if app == nil { + if foundation.App == nil { panic(ErrApplicationNotSet) + } else { + return foundation.App } - - return app } diff --git a/foundation/application.go b/foundation/application.go index 9fe3eb404..852289a8c 100644 --- a/foundation/application.go +++ b/foundation/application.go @@ -178,9 +178,13 @@ func (app *Application) addPublishGroup(group string, paths map[string]string) { // bootArtisan Boot artisan command. func (app *Application) bootArtisan() { - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Run(os.Args, true) + artisanFacade := app.MakeArtisan() + if artisanFacade == nil { + color.Yellow().Println("Warning: Artisan Facade is not initialized. Skipping artisan command execution.") + return } + + artisanFacade.Run(os.Args, true) } // getBaseServiceProviders Get base service providers. @@ -234,9 +238,13 @@ func (app *Application) bootServiceProviders(serviceProviders []foundation.Servi } func (app *Application) registerCommands(commands []consolecontract.Command) { - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Register(commands) + artisanFacade := app.MakeArtisan() + if artisanFacade == nil { + color.Yellow().Println("Warning: Artisan Facade is not initialized. Skipping command registration.") + return } + + artisanFacade.Register(commands) } func (app *Application) setTimezone() { diff --git a/http/service_provider.go b/http/service_provider.go index 224fda9ee..3d9650d48 100644 --- a/http/service_provider.go +++ b/http/service_provider.go @@ -31,11 +31,13 @@ func (http *ServiceProvider) Boot(app foundation.Application) { CacheFacade = app.MakeCache() RateLimiterFacade = app.MakeRateLimiter() - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Register([]consolecontract.Command{ - &console.RequestMakeCommand{}, - &console.ControllerMakeCommand{}, - &console.MiddlewareMakeCommand{}, - }) - } + http.registerCommands(app) +} + +func (http *ServiceProvider) registerCommands(app foundation.Application) { + app.Commands([]consolecontract.Command{ + &console.RequestMakeCommand{}, + &console.ControllerMakeCommand{}, + &console.MiddlewareMakeCommand{}, + }) } diff --git a/mail/job.go b/mail/job.go index 2eec2ab61..6ea6160fd 100644 --- a/mail/job.go +++ b/mail/job.go @@ -29,42 +29,42 @@ func (r *SendMailJob) Handle(args ...any) error { from, ok := args[0].(string) if !ok { - return fmt.Errorf("argument 0 should be of type string") + return fmt.Errorf("FROM should be of type string") } subject, ok := args[1].(string) if !ok { - return fmt.Errorf("argument 1 should be of type string") + return fmt.Errorf("SUBJECT should be of type string") } body, ok := args[2].(string) if !ok { - return fmt.Errorf("argument 2 should be of type string") + return fmt.Errorf("BODY should be of type string") } recipient, ok := args[3].(string) if !ok { - return fmt.Errorf("argument 3 should be of type string") + return fmt.Errorf("RECIPIENT should be of type string") } cc, ok := args[4].([]string) if !ok { - return fmt.Errorf("argument 4 should be of type []string") + return fmt.Errorf("CC should be of type []string") } bcc, ok := args[5].([]string) if !ok { - return fmt.Errorf("argument 5 should be of type []string") + return fmt.Errorf("BCC should be of type []string") } replyTo, ok := args[6].([]string) if !ok { - return fmt.Errorf("argument 6 should be of type []string") + return fmt.Errorf("ReplyTo should be of type []string") } attachments, ok := args[7].([]string) if !ok { - return fmt.Errorf("argument 7 should be of type []string") + return fmt.Errorf("ATTACHMENTS should be of type []string") } return SendMail(r.config, from, subject, body, recipient, cc, bcc, replyTo, attachments) diff --git a/mail/service_provider.go b/mail/service_provider.go index a77c3401b..5df27ff65 100644 --- a/mail/service_provider.go +++ b/mail/service_provider.go @@ -5,6 +5,7 @@ import ( "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/contracts/queue" "github.com/goravel/framework/mail/console" + "github.com/goravel/framework/support/color" ) const Binding = "goravel.mail" @@ -19,15 +20,27 @@ func (route *ServiceProvider) Register(app foundation.Application) { } func (route *ServiceProvider) Boot(app foundation.Application) { - if queueFacade := app.MakeQueue(); queueFacade != nil { - queueFacade.Register([]queue.Job{ - NewSendMailJob(app.MakeConfig()), - }) + app.Commands([]consolecontract.Command{ + console.NewMailMakeCommand(), + }) + + route.registerJobs(app) +} + +func (route *ServiceProvider) registerJobs(app foundation.Application) { + queueFacade := app.MakeQueue() + if queueFacade == nil { + color.Yellow().Println("Warning: Queue Facade is not initialized. Skipping job registration.") + return } - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Register([]consolecontract.Command{ - console.NewMailMakeCommand(), - }) + configFacade := app.MakeConfig() + if configFacade == nil { + color.Yellow().Println("Warning: Config Facade is not initialized. Skipping job registration.") + return } + + queueFacade.Register([]queue.Job{ + NewSendMailJob(configFacade), + }) } diff --git a/queue/service_provider.go b/queue/service_provider.go index 0a91b4383..5325cc74b 100644 --- a/queue/service_provider.go +++ b/queue/service_provider.go @@ -18,9 +18,7 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { } func (receiver *ServiceProvider) Boot(app foundation.Application) { - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Register([]console.Command{ - &queueConsole.JobMakeCommand{}, - }) - } + app.Commands([]console.Command{ + &queueConsole.JobMakeCommand{}, + }) } diff --git a/session/errors.go b/session/errors.go index a8904053d..87118d632 100644 --- a/session/errors.go +++ b/session/errors.go @@ -3,5 +3,7 @@ package session import "errors" var ( - ErrDriverNotSet = errors.New("session driver is not set") + ErrDriverNotSet = errors.New("session driver is not set") + ErrConfigFacadeNotSet = errors.New("config facade is not initialized") + ErrJSONNotSet = errors.New("JSON parser is not initialized") ) diff --git a/session/service_provider.go b/session/service_provider.go index a3c3d2c44..682b18d9a 100644 --- a/session/service_provider.go +++ b/session/service_provider.go @@ -19,7 +19,15 @@ type ServiceProvider struct { func (receiver *ServiceProvider) Register(app foundation.Application) { app.Singleton(Binding, func(app foundation.Application) (any, error) { c := app.MakeConfig() + if c == nil { + return nil, ErrConfigFacadeNotSet + } + j := app.GetJson() + if j == nil { + return nil, ErrJSONNotSet + } + return NewManager(c, j), nil }) } diff --git a/testing/service_provider.go b/testing/service_provider.go index edbbc3d50..8e9c1b175 100644 --- a/testing/service_provider.go +++ b/testing/service_provider.go @@ -3,6 +3,7 @@ package testing import ( contractsconsole "github.com/goravel/framework/contracts/console" "github.com/goravel/framework/contracts/foundation" + "github.com/goravel/framework/support/color" ) const Binding = "goravel.testing" @@ -20,4 +21,7 @@ func (receiver *ServiceProvider) Register(app foundation.Application) { func (receiver *ServiceProvider) Boot(app foundation.Application) { artisanFacade = app.MakeArtisan() + if artisanFacade == nil { + color.Red().Println("Warning: Artisan facade is not initialized") + } } diff --git a/testing/test_case.go b/testing/test_case.go index f058d41c6..d8b28b9ee 100644 --- a/testing/test_case.go +++ b/testing/test_case.go @@ -4,7 +4,6 @@ import ( "fmt" "github.com/goravel/framework/contracts/database/seeder" - "github.com/goravel/framework/support/color" ) type TestCase struct { @@ -18,18 +17,10 @@ func (receiver *TestCase) Seed(seeds ...seeder.Seeder) { command += fmt.Sprintf(" %s", seed.Signature()) } } - if artisanFacade == nil { - color.Red().Println("Error: Artisan facade is not initialized. Cannot seed the database.") - return - } artisanFacade.Call(command) } func (receiver *TestCase) RefreshDatabase(seeds ...seeder.Seeder) { - if artisanFacade == nil { - color.Red().Println("Error: Artisan facade is not initialized. Cannot refresh the database.") - return - } artisanFacade.Call("migrate:refresh") } From 70f075416403367177baf4599beb26dc126748d7 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Fri, 27 Sep 2024 05:51:34 +0530 Subject: [PATCH 28/32] fix:test --- foundation/application_test.go | 1 + testing/docker/database.go | 31 +++++++++++-------------------- testing/docker/database_test.go | 3 ++- testing/docker/docker.go | 4 ++-- testing/docker/errors.go | 8 ++++++++ 5 files changed, 24 insertions(+), 23 deletions(-) create mode 100644 testing/docker/errors.go diff --git a/foundation/application_test.go b/foundation/application_test.go index 53c4a856e..9c5a52f53 100644 --- a/foundation/application_test.go +++ b/foundation/application_test.go @@ -409,6 +409,7 @@ func (s *ApplicationTestSuite) TestMakeSession() { s.app.Singleton(frameworkconfig.Binding, func(app foundation.Application) (any, error) { return mockConfig, nil }) + s.app.SetJson(json.NewJson()) serviceProvider := &frameworksession.ServiceProvider{} // error diff --git a/testing/docker/database.go b/testing/docker/database.go index 7d8f6e284..67205011a 100644 --- a/testing/docker/database.go +++ b/testing/docker/database.go @@ -2,7 +2,6 @@ package docker import ( "context" - "errors" "fmt" contractsconfig "github.com/goravel/framework/contracts/config" @@ -11,7 +10,6 @@ import ( "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/contracts/testing" frameworkdatabase "github.com/goravel/framework/database" - "github.com/goravel/framework/support/color" supportdocker "github.com/goravel/framework/support/docker" ) @@ -23,17 +21,21 @@ type Database struct { connection string } -func NewDatabase(app foundation.Application, connection string) *Database { +func NewDatabase(app foundation.Application, connection string) (*Database, error) { config := app.MakeConfig() - if config == nil { - return nil, errors.New("config facade is not set") + return nil, ErrConfigNotSet } if connection == "" { connection = config.GetString("database.default") } + artisanFacade := app.MakeArtisan() + if artisanFacade == nil { + return nil, ErrArtisanNotSet + } + driver := config.GetString(fmt.Sprintf("database.connections.%s.driver", connection)) database := config.GetString(fmt.Sprintf("database.connections.%s.database", connection)) username := config.GetString(fmt.Sprintf("database.connections.%s.username", connection)) @@ -42,11 +44,11 @@ func NewDatabase(app foundation.Application, connection string) *Database { return &Database{ app: app, - artisan: app.MakeArtisan(), + artisan: artisanFacade, config: config, connection: connection, DatabaseDriver: databaseDriver, - } + }, nil } func (receiver *Database) Build() error { @@ -55,12 +57,7 @@ func (receiver *Database) Build() error { } receiver.config.Add(fmt.Sprintf("database.connections.%s.port", receiver.connection), receiver.DatabaseDriver.Config().Port) - artisan := receiver.app.MakeArtisan() - if artisan == nil { - return errors.New("artisan instance is not available") - } - - artisan.Call("migrate") + receiver.artisan.Call("migrate") // TODO Find a better way to refresh the database connection receiver.app.Singleton(frameworkdatabase.BindingOrm, func(app foundation.Application) (any, error) { @@ -87,11 +84,5 @@ func (receiver *Database) Seed(seeds ...seeder.Seeder) { } } - artisan := receiver.app.MakeArtisan() - if artisan == nil { - color.Red().Println("artisan instance is not available") - return - } - - artisan.Call(command) + receiver.artisan.Call(command) } diff --git a/testing/docker/database_test.go b/testing/docker/database_test.go index 7bb6449f1..bb9505a8f 100644 --- a/testing/docker/database_test.go +++ b/testing/docker/database_test.go @@ -145,8 +145,9 @@ func TestNewDatabase(t *testing.T) { t.Run(tt.name, func(t *testing.T) { beforeEach() tt.setup() - gotDatabase := NewDatabase(mockApp, tt.connection) + gotDatabase, err := NewDatabase(mockApp, tt.connection) + assert.Nil(t, err) assert.Equal(t, tt.wantDatabase(), gotDatabase) }) } diff --git a/testing/docker/docker.go b/testing/docker/docker.go index 34fd1d63b..f6008ce72 100644 --- a/testing/docker/docker.go +++ b/testing/docker/docker.go @@ -17,8 +17,8 @@ func NewDocker(app foundation.Application) *Docker { func (receiver *Docker) Database(connection ...string) (testing.Database, error) { if len(connection) == 0 { - return NewDatabase(receiver.app, ""), nil + return NewDatabase(receiver.app, "") } else { - return NewDatabase(receiver.app, connection[0]), nil + return NewDatabase(receiver.app, connection[0]) } } diff --git a/testing/docker/errors.go b/testing/docker/errors.go new file mode 100644 index 000000000..e4431d72f --- /dev/null +++ b/testing/docker/errors.go @@ -0,0 +1,8 @@ +package docker + +import "errors" + +var ( + ErrArtisanNotSet = errors.New("artisan facade is not initialized") + ErrConfigNotSet = errors.New("config facade is not initialized") +) From 58b5a40a5211aace50efa4aa3b81d7714f005d48 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Fri, 27 Sep 2024 06:02:13 +0530 Subject: [PATCH 29/32] fix:nilaway --- database/gorm/dialector_test.go | 12 ++++++++---- filesystem/file_test.go | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/database/gorm/dialector_test.go b/database/gorm/dialector_test.go index 87dc71a87..f39ec21db 100644 --- a/database/gorm/dialector_test.go +++ b/database/gorm/dialector_test.go @@ -46,11 +46,12 @@ func (s *DialectorTestSuite) TestMysql() { s.mockConfig.On("GetString", "database.connections.mysql.loc"). Return("Local").Once() dialectors, err := dialector.Make([]databasecontract.Config{s.config}) + s.Nil(err) + s.NotEmpty(dialectors) s.Equal(mysql.New(mysql.Config{ DSN: fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%t&loc=%s&multiStatements=true", s.config.Username, s.config.Password, s.config.Host, s.config.Port, s.config.Database, "utf8mb4", true, "Local"), }), dialectors[0]) - s.Nil(err) } func (s *DialectorTestSuite) TestPostgres() { @@ -62,11 +63,12 @@ func (s *DialectorTestSuite) TestPostgres() { s.mockConfig.On("GetString", "database.connections.postgres.timezone"). Return("UTC").Once() dialectors, err := dialector.Make([]databasecontract.Config{s.config}) + s.Nil(err) + s.NotEmpty(dialectors) s.Equal(postgres.New(postgres.Config{ DSN: fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s&timezone=%s", s.config.Username, s.config.Password, s.config.Host, s.config.Port, s.config.Database, "disable", "UTC"), }), dialectors[0]) - s.Nil(err) } func (s *DialectorTestSuite) TestSqlite() { @@ -74,8 +76,9 @@ func (s *DialectorTestSuite) TestSqlite() { s.mockConfig.On("GetString", "database.connections.sqlite.driver"). Return(orm.DriverSqlite.String()).Once() dialectors, err := dialector.Make([]databasecontract.Config{s.config}) - s.Equal(sqlite.Open(fmt.Sprintf("%s?multi_stmts=true", s.config.Database)), dialectors[0]) s.Nil(err) + s.NotEmpty(dialectors) + s.Equal(sqlite.Open(fmt.Sprintf("%s?multi_stmts=true", s.config.Database)), dialectors[0]) } func (s *DialectorTestSuite) TestSqlserver() { @@ -85,9 +88,10 @@ func (s *DialectorTestSuite) TestSqlserver() { s.mockConfig.On("GetString", "database.connections.sqlserver.charset"). Return("utf8mb4").Once() dialectors, err := dialector.Make([]databasecontract.Config{s.config}) + s.Nil(err) + s.NotEmpty(dialectors) s.Equal(sqlserver.New(sqlserver.Config{ DSN: fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s&charset=%s&MultipleActiveResultSets=true", s.config.Username, s.config.Password, s.config.Host, s.config.Port, s.config.Database, "utf8mb4"), }), dialectors[0]) - s.Nil(err) } diff --git a/filesystem/file_test.go b/filesystem/file_test.go index 12d5bdc83..82735f66a 100644 --- a/filesystem/file_test.go +++ b/filesystem/file_test.go @@ -71,6 +71,7 @@ func TestNewFileFromRequest(t *testing.T) { buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) w, err := mw.CreateFormFile("file", "test.txt") + assert.NotNil(t, w) if assert.NoError(t, err) { _, err = w.Write([]byte("test")) assert.NoError(t, err) From 1697335633fb9975c3669b76087e87cf01648d37 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Sun, 29 Sep 2024 20:11:55 +0530 Subject: [PATCH 30/32] update recommendation --- console/service_provider.go | 1 + validation/service_provider.go | 10 ++++------ 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/console/service_provider.go b/console/service_provider.go index f31bae2e9..c89aaebc3 100644 --- a/console/service_provider.go +++ b/console/service_provider.go @@ -35,6 +35,7 @@ func (receiver *ServiceProvider) registerCommands(app foundation.Application) { configFacade := app.MakeConfig() if configFacade == nil { color.Yellow().Println("Warning: Config Facade is not initialized. Skipping certain command registrations.") + return } artisanFacade.Register([]consolecontract.Command{ diff --git a/validation/service_provider.go b/validation/service_provider.go index b68254ba9..6d0658ba0 100644 --- a/validation/service_provider.go +++ b/validation/service_provider.go @@ -18,10 +18,8 @@ func (database *ServiceProvider) Register(app foundation.Application) { } func (database *ServiceProvider) Boot(app foundation.Application) { - if artisanFacade := app.MakeArtisan(); artisanFacade != nil { - artisanFacade.Register([]consolecontract.Command{ - &console.RuleMakeCommand{}, - &console.FilterMakeCommand{}, - }) - } + app.Commands([]consolecontract.Command{ + &console.RuleMakeCommand{}, + &console.FilterMakeCommand{}, + }) } From bdcffb4c6889248a47a6fcc80904e26be1497a0e Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Sun, 29 Sep 2024 20:14:26 +0530 Subject: [PATCH 31/32] update aes registration --- crypt/service_provider.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crypt/service_provider.go b/crypt/service_provider.go index ac9d1170d..8b00d018b 100644 --- a/crypt/service_provider.go +++ b/crypt/service_provider.go @@ -11,7 +11,17 @@ type ServiceProvider struct { func (crypt *ServiceProvider) Register(app foundation.Application) { app.Singleton(Binding, func(app foundation.Application) (any, error) { - return NewAES(app.MakeConfig(), app.GetJson()) + c := app.MakeConfig() + if c == nil { + return nil, ErrConfigNotSet + } + + j := app.GetJson() + if j == nil { + return nil, ErrJsonParserNotSet + } + + return NewAES(c, j) }) } From bb2b1af467f4f126febd1257692221e6fd6b1ee7 Mon Sep 17 00:00:00 2001 From: kkumar-gcc Date: Sun, 29 Sep 2024 20:25:49 +0530 Subject: [PATCH 32/32] . --- foundation/application.go | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/foundation/application.go b/foundation/application.go index 852289a8c..60f65f876 100644 --- a/foundation/application.go +++ b/foundation/application.go @@ -196,11 +196,18 @@ func (app *Application) getBaseServiceProviders() []foundation.ServiceProvider { // getConfiguredServiceProviders Get configured service providers. func (app *Application) getConfiguredServiceProviders() []foundation.ServiceProvider { - if configFacade := app.MakeConfig(); configFacade != nil { - return configFacade.Get("app.providers").([]foundation.ServiceProvider) + configFacade := app.MakeConfig() + if configFacade == nil { + color.Yellow().Println("Warning: config facade is not initialized. Skipping registering service providers.") + return []foundation.ServiceProvider{} } - return []foundation.ServiceProvider{} + providers, ok := configFacade.Get("app.providers").([]foundation.ServiceProvider) + if !ok { + color.Yellow().Println("Warning: providers configuration is not of type []foundation.ServiceProvider. Skipping registering service providers.") + return []foundation.ServiceProvider{} + } + return providers } // registerBaseServiceProviders Register base service providers. @@ -248,9 +255,15 @@ func (app *Application) registerCommands(commands []consolecontract.Command) { } func (app *Application) setTimezone() { - if configFacade := app.MakeConfig(); configFacade != nil { - carbon.SetTimezone(configFacade.GetString("app.timezone", carbon.UTC)) + configFacade := app.MakeConfig() + if configFacade == nil { + color.Yellow().Println("Warning: config facade is not initialized. Using default timezone UTC.") + carbon.SetTimezone(carbon.UTC) + return } + + carbon.SetTimezone(configFacade.GetString("app.timezone", carbon.UTC)) + } func setEnv() {