diff --git a/auth/access/response.go b/auth/access/response.go index b778702a3..1ff47563e 100644 --- a/auth/access/response.go +++ b/auth/access/response.go @@ -11,8 +11,8 @@ func NewDenyResponse(message string) access.Response { } type ResponseImpl struct { - allowed bool message string + allowed bool } func (r *ResponseImpl) Allowed() bool { diff --git a/auth/auth.go b/auth/auth.go index 82b591a39..f8e70231d 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -20,8 +20,8 @@ type Auth struct { contractsauth.GuardDriver config config.Config ctx http.Context - defaultGuardName string log log.Log + defaultGuardName string } func NewAuth(ctx http.Context, config config.Config, log log.Log) (*Auth, error) { diff --git a/auth/jwt_guard_test.go b/auth/jwt_guard_test.go index 99f9309ae..471d0fc0b 100644 --- a/auth/jwt_guard_test.go +++ b/auth/jwt_guard_test.go @@ -321,7 +321,7 @@ func (s *JwtGuardTestSuite) TestUser_Success() { s.Nil(err) var user User - s.mockUserProvider.EXPECT().RetriveByID(&user, "1").RunAndReturn(func(user interface{}, id interface{}) error { + s.mockUserProvider.EXPECT().RetriveByID(&user, "1").RunAndReturn(func(user any, id any) error { user.(*User).ID = 1 return nil }).Once() @@ -367,7 +367,7 @@ func (s *JwtGuardTestSuite) TestUser_Success_MultipleParse() { s.Equal("2", payload.Key) var user1 User - s.mockUserProvider.EXPECT().RetriveByID(&user1, "1").RunAndReturn(func(user interface{}, id interface{}) error { + s.mockUserProvider.EXPECT().RetriveByID(&user1, "1").RunAndReturn(func(user any, id any) error { user.(*User).ID = 1 return nil }).Once() @@ -377,7 +377,7 @@ func (s *JwtGuardTestSuite) TestUser_Success_MultipleParse() { s.Equal(uint(1), user1.ID) var user2 User - s.mockUserProvider.EXPECT().RetriveByID(&user2, "2").RunAndReturn(func(user interface{}, id interface{}) error { + s.mockUserProvider.EXPECT().RetriveByID(&user2, "2").RunAndReturn(func(user any, id any) error { user.(*User).ID = 2 return nil }).Once() @@ -504,7 +504,7 @@ func (r *Context) Err() error { return r.ctx.Err() } -func (r *Context) Value(key interface{}) any { +func (r *Context) Value(key any) any { if k, ok := key.(string); ok { r.mu.RLock() v, ok := r.values[k] diff --git a/auth/session_guard.go b/auth/session_guard.go index 03458a6d1..68b5d46f9 100644 --- a/auth/session_guard.go +++ b/auth/session_guard.go @@ -14,8 +14,8 @@ import ( type SessionGuard struct { session contractsession.Session ctx http.Context - guard string provider contractsauth.UserProvider + guard string } func NewSessionGuard(ctx http.Context, name string, userProvider contractsauth.UserProvider) (contractsauth.GuardDriver, error) { diff --git a/cache/lock.go b/cache/lock.go index 1be2f525a..280402c63 100644 --- a/cache/lock.go +++ b/cache/lock.go @@ -8,8 +8,8 @@ import ( type Lock struct { store contractscache.Driver - key string time *time.Duration + key string get bool } diff --git a/cache/memory_test.go b/cache/memory_test.go index 680f397db..bb8ee7c79 100644 --- a/cache/memory_test.go +++ b/cache/memory_test.go @@ -72,7 +72,7 @@ func (s *MemoryTestSuite) TestDecrementWithConcurrent() { s.Nil(err) var wg sync.WaitGroup - for i := 0; i < 1000; i++ { + for range 1000 { wg.Add(1) go func() { _, err = s.memory.Decrement("decrement_concurrent", 1) @@ -180,7 +180,7 @@ func (s *MemoryTestSuite) TestIncrementWithConcurrent() { s.Nil(err) var wg sync.WaitGroup - for i := 0; i < 1000; i++ { + for range 1000 { wg.Add(1) go func() { _, err = s.memory.Increment("increment_concurrent", 1) diff --git a/console/cli_helper.go b/console/cli_helper.go index eb2fb7e3b..7250521b7 100644 --- a/console/cli_helper.go +++ b/console/cli_helper.go @@ -232,12 +232,9 @@ func lexicographicLess(i, j string) bool { iRunes := []rune(i) jRunes := []rune(j) - lenShared := len(iRunes) - if lenShared > len(jRunes) { - lenShared = len(jRunes) - } + lenShared := min(len(iRunes), len(jRunes)) - for index := 0; index < lenShared; index++ { + for index := range lenShared { ir := iRunes[index] jr := jRunes[index] @@ -297,7 +294,7 @@ func onUsageError(_ context.Context, _ *cli.Command, err error, _ bool) error { return err } -func printHelpCustom(out io.Writer, templ string, data interface{}, _ map[string]interface{}) { +func printHelpCustom(out io.Writer, templ string, data any, _ map[string]any) { funcMap := template.FuncMap{ "capitalize": capitalize, "colorize": colorize, diff --git a/contracts/auth/auth.go b/contracts/auth/auth.go index dbe83aa96..177764d38 100644 --- a/contracts/auth/auth.go +++ b/contracts/auth/auth.go @@ -42,10 +42,10 @@ type UserProvider interface { } type Payload struct { - Guard string - Key string ExpireAt time.Time IssuedAt time.Time + Guard string + Key string } type GuardFunc func(ctx http.Context, name string, userProvider UserProvider) (GuardDriver, error) diff --git a/contracts/console/command.go b/contracts/console/command.go index b39e1fa9b..771931ff3 100644 --- a/contracts/console/command.go +++ b/contracts/console/command.go @@ -92,75 +92,75 @@ type Progress interface { type Choice struct { // Key the choice key. Key string - // Selected determines if the choice is selected. - Selected bool // Value the choice value. Value string + // Selected determines if the choice is selected. + Selected bool } type AskOption struct { + // Validate the input validation function. + Validate func(string) error // Default the default value for the input. Default string // Description the input description. Description string + // Placeholder the input placeholder. + Placeholder string + // Prompt the prompt message.(use for single line input) + Prompt string // Lines the number of lines for the input.(use for multiple lines text) Lines int // Limit the character limit for the input. Limit int // Multiple determines if input is single line or multiple lines text Multiple bool - // Placeholder the input placeholder. - Placeholder string - // Prompt the prompt message.(use for single line input) - Prompt string - // Validate the input validation function. - Validate func(string) error } type ChoiceOption struct { + // Validate the input validation function. + Validate func(string) error // Default the default value for the input. Default string // Description the input description. Description string - // Validate the input validation function. - Validate func(string) error } type ConfirmOption struct { // Affirmative label for the affirmative button. Affirmative string - // Default the default value for the input. - Default bool // Description the input description. Description string // Negative label for the negative button. Negative string + // Default the default value for the input. + Default bool } type SecretOption struct { + // Validate the input validation function. + Validate func(string) error // Default the default value for the input. Default string // Description the input description. Description string - // Limit the character limit for the input. - Limit int // Placeholder the input placeholder. Placeholder string - // Validate the input validation function. - Validate func(string) error + // Limit the character limit for the input. + Limit int } type MultiSelectOption struct { - // Default the default value for the input. - Default []string + // Validate the input validation function. + Validate func([]string) error // Description the input description. Description string - // Filterable determines if the choices can be filtered. - Filterable bool + // Default the default value for the input. + Default []string // Limit the number of choices that can be selected. Limit int - // Validate the input validation function. - Validate func([]string) error + // Filterable determines if the choices can be filtered. + Filterable bool } type SpinnerOption struct { diff --git a/contracts/console/command/command.go b/contracts/console/command/command.go index 667564101..a28e5c2c9 100644 --- a/contracts/console/command/command.go +++ b/contracts/console/command/command.go @@ -25,9 +25,9 @@ type Flag interface { type BoolFlag struct { Name string + Usage string Aliases []string DisableDefaultText bool - Usage string Required bool Value bool } @@ -38,10 +38,10 @@ func (receiver *BoolFlag) Type() string { type Float64Flag struct { Name string - Aliases []string Usage string - Required bool + Aliases []string Value float64 + Required bool } func (receiver *Float64Flag) Type() string { @@ -50,10 +50,10 @@ func (receiver *Float64Flag) Type() string { type Float64SliceFlag struct { Name string - Aliases []string Usage string - Required bool + Aliases []string Value []float64 + Required bool } func (receiver *Float64SliceFlag) Type() string { @@ -62,10 +62,10 @@ func (receiver *Float64SliceFlag) Type() string { type IntFlag struct { Name string - Aliases []string Usage string - Required bool + Aliases []string Value int + Required bool } func (receiver *IntFlag) Type() string { @@ -74,10 +74,10 @@ func (receiver *IntFlag) Type() string { type IntSliceFlag struct { Name string - Aliases []string Usage string - Required bool + Aliases []string Value []int + Required bool } func (receiver *IntSliceFlag) Type() string { @@ -86,10 +86,10 @@ func (receiver *IntSliceFlag) Type() string { type Int64Flag struct { Name string - Aliases []string Usage string - Required bool + Aliases []string Value int64 + Required bool } func (receiver *Int64Flag) Type() string { @@ -98,10 +98,10 @@ func (receiver *Int64Flag) Type() string { type Int64SliceFlag struct { Name string - Aliases []string Usage string - Required bool + Aliases []string Value []int64 + Required bool } func (receiver *Int64SliceFlag) Type() string { @@ -110,10 +110,10 @@ func (receiver *Int64SliceFlag) Type() string { type StringFlag struct { Name string - Aliases []string Usage string - Required bool Value string + Aliases []string + Required bool } func (receiver *StringFlag) Type() string { @@ -122,10 +122,10 @@ func (receiver *StringFlag) Type() string { type StringSliceFlag struct { Name string - Aliases []string Usage string - Required bool + Aliases []string Value []string + Required bool } func (receiver *StringSliceFlag) Type() string { diff --git a/contracts/database/config.go b/contracts/database/config.go index 6c656c050..532b59dd6 100644 --- a/contracts/database/config.go +++ b/contracts/database/config.go @@ -8,23 +8,23 @@ type Pool struct { } type Config struct { + Dialector gorm.Dialector + NameReplacer Replacer Charset string Connection string Dsn string Database string - Dialector gorm.Dialector Driver string Host string - NameReplacer Replacer - NoLowerCase bool Password string - Port int Prefix string Schema string - Singular bool Sslmode string Timezone string Username string + Port int + NoLowerCase bool + Singular bool } // Replacer replacer interface like strings.Replacer diff --git a/contracts/database/driver/column.go b/contracts/database/driver/column.go index fe378b882..064f28815 100644 --- a/contracts/database/driver/column.go +++ b/contracts/database/driver/column.go @@ -78,13 +78,13 @@ type ColumnDefinition interface { } type Column struct { - Autoincrement bool Collation string Comment string Default string Extra string Name string - Nullable bool Type string TypeName string + Autoincrement bool + Nullable bool } diff --git a/contracts/database/driver/conditions.go b/contracts/database/driver/conditions.go index b28d0f69d..22a65d2a0 100644 --- a/contracts/database/driver/conditions.go +++ b/contracts/database/driver/conditions.go @@ -40,9 +40,9 @@ type Join struct { } type Where struct { - Type WhereType Query any Args []any + Type WhereType Or bool IsNot bool } diff --git a/contracts/database/driver/grammar.go b/contracts/database/driver/grammar.go index 23507643c..57e88c93a 100644 --- a/contracts/database/driver/grammar.go +++ b/contracts/database/driver/grammar.go @@ -194,22 +194,22 @@ type PlaceholderFormat interface { } type Command struct { - Algorithm string Column ColumnDefinition - Columns []string Deferrable *bool + InitiallyImmediate *bool + Algorithm string From string Index string - InitiallyImmediate *bool Language string Name string On string OnDelete string OnUpdate string - References []string - ShouldBeSkipped bool To string Value string + Columns []string + References []string + ShouldBeSkipped bool } type Table struct { @@ -223,10 +223,10 @@ type Table struct { type Type struct { Category string - Implicit bool Name string Schema string Type string + Implicit bool } type View struct { diff --git a/contracts/database/driver/processor.go b/contracts/database/driver/processor.go index bbf6a3cd3..f757c9b8d 100644 --- a/contracts/database/driver/processor.go +++ b/contracts/database/driver/processor.go @@ -8,19 +8,19 @@ type Processor interface { } type DBColumn struct { - Autoincrement bool Collation string Comment string Default string Extra string - Length int Name string Nullable string + Type string + TypeName string + Length int Places int Precision int + Autoincrement bool Primary bool - Type string - TypeName string } type DBForeignKey struct { @@ -36,25 +36,25 @@ type DBForeignKey struct { type DBIndex struct { Columns string Name string - Primary bool Type string + Primary bool Unique bool } type ForeignKey struct { Name string - Columns []string ForeignSchema string ForeignTable string - ForeignColumns []string OnUpdate string OnDelete string + Columns []string + ForeignColumns []string } type Index struct { - Columns []string Name string - Primary bool Type string + Columns []string + Primary bool Unique bool } diff --git a/contracts/database/migration/repository.go b/contracts/database/migration/repository.go index 8293353e1..4d9e30540 100644 --- a/contracts/database/migration/repository.go +++ b/contracts/database/migration/repository.go @@ -1,8 +1,8 @@ package migration type File struct { - ID uint Migration string + ID uint Batch int } diff --git a/contracts/event/events.go b/contracts/event/events.go index 5b1e96a44..525136f95 100644 --- a/contracts/event/events.go +++ b/contracts/event/events.go @@ -29,12 +29,12 @@ type Task interface { } type Arg struct { - Type string Value any + Type string } type Queue struct { - Enable bool Connection string Queue string + Enable bool } diff --git a/contracts/http/cookie.go b/contracts/http/cookie.go index 7611d55ca..a08b0289f 100644 --- a/contracts/http/cookie.go +++ b/contracts/http/cookie.go @@ -4,6 +4,11 @@ import "time" // Cookie represents an HTTP cookie as defined by RFC 6265. type Cookie struct { + + // Expires specifies the maximum age of the cookie.It is considered + // expired if the current time is after the Expires value. + Expires time.Time + // Name is the name of the cookie. Name string @@ -16,9 +21,14 @@ type Cookie struct { // Domain specifies the domain for which the cookie is valid. Domain string - // Expires specifies the maximum age of the cookie.It is considered - // expired if the current time is after the Expires value. - Expires time.Time + // Raw is the unparsed value of the "Set-Cookie" header received from + // the server. + Raw string + + // SameSite allows a server to define a cookie attribute, making it + // impossible for the browser to send this cookie along with cross-site + // requests.It helps mitigate the risk of cross-origin information leaks. + SameSite string // MaxAge specifies the maximum age of the cookie in seconds.A zero or // negative MaxAge means that the cookie is not persistent and will be @@ -32,13 +42,4 @@ type Cookie struct { // HttpOnly indicates whether the cookie is accessible only through // HTTP requests, and not through JavaScript. HttpOnly bool - - // Raw is the unparsed value of the "Set-Cookie" header received from - // the server. - Raw string - - // SameSite allows a server to define a cookie attribute, making it - // impossible for the browser to send this cookie along with cross-site - // requests.It helps mitigate the risk of cross-origin information leaks. - SameSite string } diff --git a/contracts/queue/job.go b/contracts/queue/job.go index 761b09ff7..2d5b704a5 100644 --- a/contracts/queue/job.go +++ b/contracts/queue/job.go @@ -40,7 +40,7 @@ type JobStorer interface { type Jobs = ChainJob type ChainJob struct { + Delay time.Time `json:"delay"` Job Job `json:"job"` Args []Arg `json:"args"` - Delay time.Time `json:"delay"` } diff --git a/contracts/queue/queue.go b/contracts/queue/queue.go index 5fe1840f6..0885ae0ed 100644 --- a/contracts/queue/queue.go +++ b/contracts/queue/queue.go @@ -36,6 +36,6 @@ type Args struct { } type Arg struct { - Type string `json:"type"` Value any `json:"value"` + Type string `json:"type"` } diff --git a/contracts/testing/docker/cache.go b/contracts/testing/docker/cache.go index 1b4a1f3b1..68eb86454 100644 --- a/contracts/testing/docker/cache.go +++ b/contracts/testing/docker/cache.go @@ -23,6 +23,6 @@ type CacheConfig struct { Database string Host string Password string - Port int Username string + Port int } diff --git a/contracts/testing/docker/database.go b/contracts/testing/docker/database.go index e5baf4981..5c544d2e5 100644 --- a/contracts/testing/docker/database.go +++ b/contracts/testing/docker/database.go @@ -35,9 +35,9 @@ type DatabaseDriver interface { type DatabaseConfig struct { Driver string Host string - Port int Database string Username string Password string ContainerID string + Port int } diff --git a/contracts/translation/translator.go b/contracts/translation/translator.go index f34ebbc23..11bec3475 100644 --- a/contracts/translation/translator.go +++ b/contracts/translation/translator.go @@ -23,8 +23,8 @@ type Translator interface { type Option struct { Fallback *bool - Locale string Replace map[string]string + Locale string } func Bool(value bool) *bool { diff --git a/crypt/aes.go b/crypt/aes.go index fc0c3f9d3..85cf3ac6e 100644 --- a/crypt/aes.go +++ b/crypt/aes.go @@ -16,8 +16,8 @@ import ( ) type AES struct { - key []byte json foundation.Json + key []byte } // NewAES returns a new AES hasher. diff --git a/database/console/model_make_command.go b/database/console/model_make_command.go index 0ea3ceb37..178187881 100644 --- a/database/console/model_make_command.go +++ b/database/console/model_make_command.go @@ -20,10 +20,10 @@ import ( ) type modelDefinition struct { - Fields []string - Embeds []string Imports map[string]struct{} TableNameMethod string + Fields []string + Embeds []string } type fieldDefinition struct { @@ -241,12 +241,12 @@ func (r *ModelMakeCommand) buildField(name, goType, tags string) string { func (r *ModelMakeCommand) populateStub(stub, packageName, structName string, modelInfo modelDefinition) (string, error) { templateData := struct { + Imports map[string]struct{} PackageName string StructName string + TableNameMethod string Embeds []string Fields []string - TableNameMethod string - Imports map[string]struct{} }{ PackageName: packageName, StructName: structName, diff --git a/database/console/show_command.go b/database/console/show_command.go index 0878aa7f2..5ebfbedd9 100644 --- a/database/console/show_command.go +++ b/database/console/show_command.go @@ -19,16 +19,16 @@ type ShowCommand struct { } type databaseInfo struct { - Database string - Host string - Name string - OpenConnections int - Port int - Tables []driver.Table - Username string + Database string + Host string + Name string + Username string + Tables []driver.Table // TODO: We want to reconstruct the way to get the version of the database, comment it out temporarily. // Version string - Views []driver.View + Views []driver.View + OpenConnections int + Port int } func NewShowCommand(config config.Config, schema schema.Schema) *ShowCommand { diff --git a/database/db/db.go b/database/db/db.go index 5deaa46f0..cfb234d1c 100644 --- a/database/db/db.go +++ b/database/db/db.go @@ -119,12 +119,12 @@ func (r *DB) WithContext(ctx context.Context) contractsdb.DB { type Tx struct { ctx context.Context - driverName string - gormDB *gorm.DB grammar contractsdriver.Grammar logger contractslogger.Logger txBuilder contractsdb.TxBuilder + gormDB *gorm.DB txLogs *[]TxLog + driverName string } func NewTx( diff --git a/database/db/query.go b/database/db/query.go index 05326d850..2f93e5713 100644 --- a/database/db/query.go +++ b/database/db/query.go @@ -4,6 +4,7 @@ import ( "context" databasesql "database/sql" "fmt" + "maps" "reflect" "sort" "strings" @@ -21,14 +22,14 @@ import ( ) type Query struct { - conditions contractsdriver.Conditions ctx context.Context err error grammar contractsdriver.Grammar logger logger.Logger readBuilder db.CommonBuilder - txLogs *[]TxLog writeBuilder db.CommonBuilder + txLogs *[]TxLog + conditions contractsdriver.Conditions } func NewQuery(ctx context.Context, readBuilder db.CommonBuilder, writeBuilder db.CommonBuilder, grammar contractsdriver.Grammar, logger logger.Logger, table string, txLogs *[]TxLog) *Query { @@ -799,9 +800,7 @@ func (r *Query) UpdateOrInsert(attributes any, values any) (*db.Result, error) { return r.Where(mapAttributes).Update(values) } - for k, v := range mapValues { - mapAttributes[k] = v - } + maps.Copy(mapAttributes, mapValues) return r.Insert(mapAttributes) } diff --git a/database/db/query_log.go b/database/db/query_log.go index 6111f880b..11db31b54 100644 --- a/database/db/query_log.go +++ b/database/db/query_log.go @@ -7,8 +7,8 @@ import ( type queryLogKey struct{} type queryLogValue struct { - enabled bool queryLogs []QueryLog + enabled bool } type QueryLog struct { diff --git a/database/db/utils.go b/database/db/utils.go index 617ab7afc..45dd1b931 100644 --- a/database/db/utils.go +++ b/database/db/utils.go @@ -2,6 +2,7 @@ package db import ( "context" + "maps" "reflect" "strings" @@ -11,10 +12,10 @@ import ( type TxLog struct { ctx context.Context + err error begin *carbon.Carbon sql string rowsAffected int64 - err error } func convertToSliceMap(data any) ([]map[string]any, error) { @@ -46,7 +47,7 @@ func convertToSliceMap(data any) ([]map[string]any, error) { } result := make([]map[string]any, length) - for i := 0; i < length; i++ { + for i := range length { elem := val.Index(i) m, err := convertToMap(elem.Interface()) if err != nil { @@ -114,9 +115,7 @@ func convertToMap(data any) (map[string]any, error) { if err != nil { return nil, err } - for k, v := range embedded { - result[k] = v - } + maps.Copy(result, embedded) } continue } diff --git a/database/factory/factory.go b/database/factory/factory.go index 5d4fa4698..9d019a0e6 100644 --- a/database/factory/factory.go +++ b/database/factory/factory.go @@ -1,6 +1,7 @@ package factory import ( + "maps" "reflect" "github.com/go-viper/mapstructure/v2" @@ -123,9 +124,7 @@ func getRawAttributes(value any, attributes ...map[string]any) (map[string]any, definition := factoryModel.Factory().Definition() if len(attributes) > 0 { - for key, value := range attributes[0] { - definition[key] = value - } + maps.Copy(definition, attributes[0]) } return definition, nil diff --git a/database/gorm/conditions.go b/database/gorm/conditions.go index aa04efa4c..3ba54c417 100644 --- a/database/gorm/conditions.go +++ b/database/gorm/conditions.go @@ -7,22 +7,22 @@ import ( type Conditions struct { dest any - distinct bool - groupBy []string + model any having *contractsdriver.Having - join []contractsdriver.Join limit *int - lockForUpdate bool - model any offset *int + table *Table + groupBy []string + join []contractsdriver.Join omit []string order []any scopes []func(contractsorm.Query) contractsorm.Query selectColumns []string - sharedLock bool - table *Table where []contractsdriver.Where with []With + distinct bool + lockForUpdate bool + sharedLock bool withoutEvents bool withTrashed bool } diff --git a/database/gorm/event.go b/database/gorm/event.go index 3240052de..2b0889b01 100644 --- a/database/gorm/event.go +++ b/database/gorm/event.go @@ -2,6 +2,7 @@ package gorm import ( "context" + "maps" "reflect" "strings" @@ -308,9 +309,7 @@ func fetchColumnNames(model any) map[string]string { fieldValue := modelValue.Field(i) if fieldValue.Kind() == reflect.Struct && fieldType.Anonymous { subStructMap := fetchColumnNames(fieldValue.Interface()) - for key, value := range subStructMap { - res[key] = value - } + maps.Copy(res, subStructMap) continue } @@ -354,9 +353,7 @@ func structToMap(data any) map[string]any { if (fieldValue.Kind() == reflect.Struct || fieldValue.Kind() == reflect.Pointer) && fieldType.Anonymous { subStructMap := structToMap(fieldValue.Interface()) - for key, value := range subStructMap { - res[key] = value - } + maps.Copy(res, subStructMap) } else { res[dbColumn] = fieldValue.Interface() } diff --git a/database/gorm/query.go b/database/gorm/query.go index 9a6cd27e3..bb5d74281 100644 --- a/database/gorm/query.go +++ b/database/gorm/query.go @@ -5,6 +5,7 @@ import ( "database/sql" "fmt" "reflect" + "slices" "strings" "sync" @@ -28,16 +29,16 @@ import ( const Associations = clause.Associations type Query struct { - conditions Conditions config config.Config ctx context.Context - dbConfig contractsdatabase.Config - instance *gormio.DB grammar driver.Grammar log log.Log + instance *gormio.DB + queries map[string]*Query modelToObserver []contractsorm.ModelToObserver + conditions Conditions + dbConfig contractsdatabase.Config mutex sync.Mutex - queries map[string]*Query } func NewQuery( @@ -1564,10 +1565,8 @@ func (r *Query) new(db *gormio.DB) *Query { func (r *Query) omitCreate(value any) error { if len(r.instance.Statement.Omits) > 1 { - for _, val := range r.instance.Statement.Omits { - if val == Associations { - return errors.OrmQueryAssociationsConflict - } + if slices.Contains(r.instance.Statement.Omits, Associations) { + return errors.OrmQueryAssociationsConflict } } @@ -1603,10 +1602,8 @@ func (r *Query) omitCreate(value any) error { } func (r *Query) omitSave(value any) error { - for _, val := range r.instance.Statement.Omits { - if val == Associations { - return r.instance.Omit(Associations).Save(value).Error - } + if slices.Contains(r.instance.Statement.Omits, Associations) { + return r.instance.Omit(Associations).Save(value).Error } return r.instance.Save(value).Error @@ -1663,10 +1660,8 @@ func (r *Query) saving(dest any) error { func (r *Query) selectCreate(value any) error { if len(r.instance.Statement.Selects) > 1 { - for _, val := range r.instance.Statement.Selects { - if val == Associations { - return errors.OrmQueryAssociationsConflict - } + if slices.Contains(r.instance.Statement.Selects, Associations) { + return errors.OrmQueryAssociationsConflict } } @@ -1696,10 +1691,8 @@ func (r *Query) selectCreate(value any) error { } func (r *Query) selectSave(value any) error { - for _, val := range r.instance.Statement.Selects { - if val == Associations { - return r.instance.Session(&gormio.Session{FullSaveAssociations: true}).Save(value).Error - } + if slices.Contains(r.instance.Statement.Selects, Associations) { + return r.instance.Session(&gormio.Session{FullSaveAssociations: true}).Save(value).Error } if err := r.instance.Save(value).Error; err != nil { @@ -1737,13 +1730,11 @@ func (r *Query) update(values any) (*contractsdb.Result, error) { } if len(r.instance.Statement.Selects) > 0 { - for _, val := range r.instance.Statement.Selects { - if val == Associations { - result := r.instance.Session(&gormio.Session{FullSaveAssociations: true}).Updates(values) - return &contractsdb.Result{ - RowsAffected: result.RowsAffected, - }, result.Error - } + if slices.Contains(r.instance.Statement.Selects, Associations) { + result := r.instance.Session(&gormio.Session{FullSaveAssociations: true}).Updates(values) + return &contractsdb.Result{ + RowsAffected: result.RowsAffected, + }, result.Error } result := r.instance.Updates(values) @@ -1754,14 +1745,12 @@ func (r *Query) update(values any) (*contractsdb.Result, error) { } if len(r.instance.Statement.Omits) > 0 { - for _, val := range r.instance.Statement.Omits { - if val == Associations { - result := r.instance.Omit(Associations).Updates(values) + if slices.Contains(r.instance.Statement.Omits, Associations) { + result := r.instance.Omit(Associations).Updates(values) - return &contractsdb.Result{ - RowsAffected: result.RowsAffected, - }, result.Error - } + return &contractsdb.Result{ + RowsAffected: result.RowsAffected, + }, result.Error } result := r.instance.Updates(values) diff --git a/database/orm/model.go b/database/orm/model.go index 280d1ecb1..950df92a1 100644 --- a/database/orm/model.go +++ b/database/orm/model.go @@ -12,8 +12,8 @@ const Associations = clause.Associations // Model is the base model for all models in the application. // @Deprecated use BaseModel instead. type Model struct { - ID uint `gorm:"primaryKey" json:"id"` Timestamps + ID uint `gorm:"primaryKey" json:"id"` } // SoftDeletes is used to add soft delete functionality to a model. @@ -30,8 +30,8 @@ type Timestamps struct { } type BaseModel struct { - ID uint `gorm:"primaryKey" json:"id"` NullableTimestamps + ID uint `gorm:"primaryKey" json:"id"` } type NullableSoftDeletes struct { diff --git a/database/orm/orm.go b/database/orm/orm.go index 6f86e5f55..9e1cf70f1 100644 --- a/database/orm/orm.go +++ b/database/orm/orm.go @@ -17,14 +17,14 @@ import ( type Orm struct { ctx context.Context config config.Config - connection string - dbConfig database.Config log log.Log - modelToObserver []contractsorm.ModelToObserver - mutex sync.Mutex query contractsorm.Query queries map[string]contractsorm.Query fresh func(key ...any) + connection string + modelToObserver []contractsorm.ModelToObserver + dbConfig database.Config + mutex sync.Mutex } func NewOrm( diff --git a/database/schema/blueprint.go b/database/schema/blueprint.go index e5ae4bc80..a2b935c76 100644 --- a/database/schema/blueprint.go +++ b/database/schema/blueprint.go @@ -36,11 +36,11 @@ const ( ) type Blueprint struct { - columns []*ColumnDefinition - commands []*driver.Command - prefix string schema schema.Schema + prefix string table string + columns []*ColumnDefinition + commands []*driver.Command } func NewBlueprint(schema schema.Schema, prefix, table string) *Blueprint { diff --git a/database/schema/column.go b/database/schema/column.go index 529730375..0197a29ed 100644 --- a/database/schema/column.go +++ b/database/schema/column.go @@ -6,19 +6,14 @@ import ( ) type ColumnDefinition struct { - after string - allowed []any - always bool + def any + onUpdate any autoIncrement *bool - change bool comment *string - def any - first bool generatedAs *string length *int name *string nullable *bool - onUpdate any places *int precision *int total *int @@ -26,6 +21,11 @@ type ColumnDefinition struct { unsigned *bool useCurrent *bool useCurrentOnUpdate *bool + after string + allowed []any + always bool + change bool + first bool } func NewColumnDefinition(name string, ttype string) driver.ColumnDefinition { diff --git a/database/schema/wrap.go b/database/schema/wrap.go index df9da42ca..9dbda4597 100644 --- a/database/schema/wrap.go +++ b/database/schema/wrap.go @@ -16,8 +16,8 @@ var ( ) type Wrap struct { - prefix string wrapValue func(string) string + prefix string } func NewWrap(prefix string) *Wrap { diff --git a/database/seeder/seeder.go b/database/seeder/seeder.go index f257a604f..9e2b2c7b7 100644 --- a/database/seeder/seeder.go +++ b/database/seeder/seeder.go @@ -1,6 +1,8 @@ package seeder import ( + "slices" + "github.com/goravel/framework/contracts/database/seeder" "github.com/goravel/framework/support/color" ) @@ -56,7 +58,7 @@ func (s *SeederFacade) Call(seeders []seeder.Seeder) error { return err } - if !contains(s.Called, signature) { + if !slices.Contains(s.Called, signature) { s.Called = append(s.Called, signature) } } @@ -68,7 +70,7 @@ func (s *SeederFacade) CallOnce(seeders []seeder.Seeder) error { for _, item := range seeders { signature := item.Signature() - if contains(s.Called, signature) { + if slices.Contains(s.Called, signature) { continue } @@ -78,13 +80,3 @@ func (s *SeederFacade) CallOnce(seeders []seeder.Seeder) error { } return nil } - -// contains checks if a string exists in a slice. -func contains(slice []string, str string) bool { - for _, s := range slice { - if s == str { - return true - } - } - return false -} diff --git a/event/task.go b/event/task.go index 82b9aa1a2..fcb3a59b5 100644 --- a/event/task.go +++ b/event/task.go @@ -7,10 +7,10 @@ import ( ) type Task struct { - args []event.Arg event event.Event - listeners []event.Listener queue contractsqueue.Queue + args []event.Arg + listeners []event.Listener } func NewTask(queue contractsqueue.Queue, args []event.Arg, event event.Event, listeners []event.Listener) *Task { diff --git a/filesystem/file.go b/filesystem/file.go index 035d8f9a5..62a8af000 100644 --- a/filesystem/file.go +++ b/filesystem/file.go @@ -18,10 +18,10 @@ import ( type File struct { config config.Config + storage filesystem.Storage disk string path string name string - storage filesystem.Storage } func NewFile(file string) (*File, error) { diff --git a/foundation/application.go b/foundation/application.go index 590e6c60a..a434cb2ec 100644 --- a/foundation/application.go +++ b/foundation/application.go @@ -3,6 +3,7 @@ package foundation import ( "context" "flag" + "maps" "os" "path/filepath" "slices" @@ -131,9 +132,7 @@ func (r *Application) Publishes(packageName string, paths map[string]string, gro if _, exist := r.publishes[packageName]; !exist { r.publishes[packageName] = make(map[string]string) } - for key, value := range paths { - r.publishes[packageName][key] = value - } + maps.Copy(r.publishes[packageName], paths) for _, group := range groups { r.addPublishGroup(group, paths) } @@ -196,9 +195,7 @@ func (r *Application) addPublishGroup(group string, paths map[string]string) { r.publishGroups[group] = make(map[string]string) } - for key, value := range paths { - r.publishGroups[group][key] = value - } + maps.Copy(r.publishGroups[group], paths) } // bootArtisan Boot artisan command. @@ -312,7 +309,7 @@ func setEnv() { testEnv = envFilePath ) - for i := 0; i < 50; i++ { + for range 50 { if _, err := os.Stat(testEnv); err == nil { envExist = true @@ -340,24 +337,21 @@ func getEnvFilePath() string { envFilePath := ".env" args := os.Args for index, arg := range args { - if strings.HasPrefix(arg, "--env=") { - if path := strings.TrimPrefix(arg, "--env="); path != "" { - envFilePath = path - break - } + if path, ok := strings.CutPrefix(arg, "--env="); ok && len(path) > 0 { + envFilePath = path + break } - if strings.HasPrefix(arg, "-env=") { - if path := strings.TrimPrefix(arg, "-env="); path != "" { - envFilePath = path - break - } + + if path, ok := strings.CutPrefix(arg, "-env="); ok && len(path) > 0 { + envFilePath = path + break } - if strings.HasPrefix(arg, "-e=") { - if path := strings.TrimPrefix(arg, "-e="); path != "" { - envFilePath = path - break - } + + if path, ok := strings.CutPrefix(arg, "-e="); ok && len(path) > 0 { + envFilePath = path + break } + if arg == "--env" || arg == "-env" || arg == "-e" { if len(args) >= index+1 && !strings.HasPrefix(args[index+1], "-") { envFilePath = args[index+1] diff --git a/foundation/console/about_command_test.go b/foundation/console/about_command_test.go index e36d4e6ee..3e08bc4be 100644 --- a/foundation/console/about_command_test.go +++ b/foundation/console/about_command_test.go @@ -56,8 +56,8 @@ func (s *AboutCommandTestSuite) TestExtend() { testCases := []struct { name string - got interface{} - expected interface{} + got any + expected any }{ {"Name", flag.Name, "only"}, {"Usage", flag.Usage, "The section to display"}, diff --git a/foundation/console/env_decrypt_command_test.go b/foundation/console/env_decrypt_command_test.go index daf88370b..1a1ff28ff 100644 --- a/foundation/console/env_decrypt_command_test.go +++ b/foundation/console/env_decrypt_command_test.go @@ -60,8 +60,8 @@ func (s *EnvDecryptCommandTestSuite) TestExtend() { testCases := []struct { name string - got interface{} - expected interface{} + got any + expected any }{ {"Name", flag.Name, "key"}, {"Aliases", flag.Aliases, []string{"k"}}, diff --git a/foundation/console/env_encrypt_command_test.go b/foundation/console/env_encrypt_command_test.go index e7973f81c..c5edc2865 100644 --- a/foundation/console/env_encrypt_command_test.go +++ b/foundation/console/env_encrypt_command_test.go @@ -55,8 +55,8 @@ func (s *EnvEncryptCommandTestSuite) TestExtend() { testCases := []struct { name string - got interface{} - expected interface{} + got any + expected any }{ {"Name", flag.Name, "key"}, {"Aliases", flag.Aliases, []string{"k"}}, diff --git a/foundation/console/package_make_command_test.go b/foundation/console/package_make_command_test.go index 819ad622e..8ca877b40 100644 --- a/foundation/console/package_make_command_test.go +++ b/foundation/console/package_make_command_test.go @@ -49,8 +49,8 @@ func (s *PackageMakeCommandTestSuite) TestExtend() { testCases := []struct { name string - got interface{} - expected interface{} + got any + expected any }{ {"Name", flag.Name, "root"}, {"Aliases", flag.Aliases, []string{"r"}}, diff --git a/foundation/console/test_make_command_test.go b/foundation/console/test_make_command_test.go index fdbcc2a6c..183ab79b6 100644 --- a/foundation/console/test_make_command_test.go +++ b/foundation/console/test_make_command_test.go @@ -51,8 +51,8 @@ func (s *TestMakeCommandTestSuite) TestExtend() { testCases := []struct { name string - got interface{} - expected interface{} + got any + expected any }{ {"Name", flag.Name, "force"}, {"Aliases", flag.Aliases, []string{"f"}}, diff --git a/foundation/console/vendor_publish_command_test.go b/foundation/console/vendor_publish_command_test.go index 2cc0b2883..1f5c9a9a9 100644 --- a/foundation/console/vendor_publish_command_test.go +++ b/foundation/console/vendor_publish_command_test.go @@ -54,8 +54,8 @@ func (s *VendorPublishCommandTestSuite) TestExtend() { testCases := []struct { name string - got interface{} - expected interface{} + got any + expected any }{ {"Name", flag.Name, "existing"}, {"Aliases", flag.Aliases, []string{"e"}}, diff --git a/http/client/request.go b/http/client/request.go index 4b4e2d3b6..06e8ebfdd 100644 --- a/http/client/request.go +++ b/http/client/request.go @@ -5,27 +5,28 @@ import ( "encoding/base64" "fmt" "io" + "maps" "net/http" "net/url" "strings" "github.com/goravel/framework/contracts/foundation" "github.com/goravel/framework/contracts/http/client" - "github.com/goravel/framework/support/maps" + supportmaps "github.com/goravel/framework/support/maps" ) var _ client.Request = (*Request)(nil) type Request struct { ctx context.Context + bind any + json foundation.Json client *http.Client config *client.Config - bind any headers http.Header - cookies []*http.Cookie queryParams url.Values urlParams map[string]string - json foundation.Json + cookies []*http.Cookie } func NewRequest(config *client.Config, json foundation.Json) *Request { @@ -96,9 +97,7 @@ func (r *Request) Clone() client.Request { } clone.urlParams = make(map[string]string) - for k, v := range r.urlParams { - clone.urlParams[k] = v - } + maps.Copy(clone.urlParams, r.urlParams) return &clone } @@ -113,7 +112,7 @@ func (r *Request) ReplaceHeaders(headers map[string]string) client.Request { } func (r *Request) WithBasicAuth(username, password string) client.Request { - encoded := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) + encoded := base64.StdEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", username, password)) return r.WithToken(encoded, "Basic") } @@ -188,7 +187,7 @@ func (r *Request) WithoutToken() client.Request { } func (r *Request) WithUrlParameter(key, value string) client.Request { - maps.Set(r.urlParams, key, url.PathEscape(value)) + supportmaps.Set(r.urlParams, key, url.PathEscape(value)) return r } diff --git a/http/client/request_test.go b/http/client/request_test.go index e5a336477..d1aa6c617 100644 --- a/http/client/request_test.go +++ b/http/client/request_test.go @@ -76,7 +76,7 @@ func (s *RequestTestSuite) TestDoRequest_Success() { jsonData, err := resp.Json() s.NoError(err) - s.Equal(map[string]interface{}{"message": "success"}, jsonData) + s.Equal(map[string]any{"message": "success"}, jsonData) } func (s *RequestTestSuite) TestDoRequest_Bind() { @@ -275,7 +275,7 @@ func (s *RequestTestSuite) TestConcurrentRequests() { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) time.Sleep(5 * time.Millisecond) - _, _ = w.Write([]byte(fmt.Sprintf(`{"message":"success-%s"}`, r.URL.Path))) + _, _ = w.Write(fmt.Appendf(nil, `{"message":"success-%s"}`, r.URL.Path)) })) defer server.Close() diff --git a/http/client/response.go b/http/client/response.go index 0ce7100d4..fa00f0b9c 100644 --- a/http/client/response.go +++ b/http/client/response.go @@ -13,11 +13,11 @@ import ( var _ client.Response = (*Response)(nil) type Response struct { - mu sync.Mutex - content string - decoded map[string]any json foundation.Json + decoded map[string]any response *http.Response + content string + mu sync.Mutex } func NewResponse(response *http.Response, json foundation.Json) *Response { diff --git a/http/limit/limit.go b/http/limit/limit.go index a6dfc9e25..cea6e684a 100644 --- a/http/limit/limit.go +++ b/http/limit/limit.go @@ -32,12 +32,12 @@ func PerDays(decayDays, maxAttempts int) contractshttp.Limit { } type Limit struct { - // The rate limit signature key. - Key string // The store instance. Store contractshttp.Store // The response generator callback. ResponseCallback func(ctx contractshttp.Context) + // The rate limit signature key. + Key string } func NewLimit(maxAttempts, decayMinutes int) *Limit { diff --git a/http/limit/store.go b/http/limit/store.go index e49e9d79f..213237923 100644 --- a/http/limit/store.go +++ b/http/limit/store.go @@ -10,10 +10,10 @@ import ( ) type Store struct { - tokens uint64 - interval time.Duration cache cache.Cache json foundation.Json + tokens uint64 + interval time.Duration } func NewStore(cache cache.Cache, json foundation.Json, tokens uint64, interval time.Duration) *Store { diff --git a/log/entry.go b/log/entry.go index e43c60eda..4a177addc 100644 --- a/log/entry.go +++ b/log/entry.go @@ -8,21 +8,21 @@ import ( ) type Entry struct { - code string + time time.Time ctx context.Context - data log.Data - domain string - hint string - level log.Level - message string owner any + user any + data log.Data request map[string]any response map[string]any stacktrace map[string]any - tags []string - time time.Time - user any with map[string]any + code string + domain string + hint string + message string + tags []string + level log.Level } func (r *Entry) Code() string { diff --git a/log/logrus_writer.go b/log/logrus_writer.go index f2fba2f64..70539dba0 100644 --- a/log/logrus_writer.go +++ b/log/logrus_writer.go @@ -3,6 +3,7 @@ package log import ( "fmt" "io" + "maps" "os" "github.com/rotisserie/eris" @@ -26,19 +27,19 @@ func NewLogrus() *logrus.Logger { } type Writer struct { - code string - domain string - hint string - instance *logrus.Entry - message string owner any request http.ContextRequest response http.ContextResponse - stackEnabled bool - stacktrace map[string]any - tags []string user any + instance *logrus.Entry + stacktrace map[string]any with map[string]any + code string + domain string + hint string + message string + tags []string + stackEnabled bool } func NewWriter(instance *logrus.Entry) log.Writer { @@ -172,9 +173,7 @@ func (r *Writer) User(user any) log.Writer { // With adds key-value pairs to the context of the log entry func (r *Writer) With(data map[string]any) log.Writer { - for k, v := range data { - r.with[k] = v - } + maps.Copy(r.with, data) return r } diff --git a/log/logrus_writer_test.go b/log/logrus_writer_test.go index 8ef092484..89a9fa98f 100644 --- a/log/logrus_writer_test.go +++ b/log/logrus_writer_test.go @@ -631,7 +631,7 @@ func (r *TestRequest) FullUrl() string { } func (r *TestRequest) All() map[string]any { - return map[string]interface{}{ + return map[string]any{ "key1": "value1", "key2": "value2", } diff --git a/mail/application.go b/mail/application.go index 058b6a42f..b153a39fd 100644 --- a/mail/application.go +++ b/mail/application.go @@ -11,17 +11,17 @@ import ( ) type Application struct { - attachments []string - bcc []string - cc []string - clone int config config.Config - from mail.Address + queue queuecontract.Queue headers map[string]string + from mail.Address html string - queue queuecontract.Queue subject string + attachments []string + bcc []string + cc []string to []string + clone int } func NewApplication(config config.Config, queue queuecontract.Queue) *Application { diff --git a/packages/match/match.go b/packages/match/match.go index dc2f01083..85d43a62b 100644 --- a/packages/match/match.go +++ b/packages/match/match.go @@ -12,8 +12,8 @@ import ( type ( GoNode struct { - first, last bool match func(node dst.Node) bool + first, last bool } GoNodes []match.GoNode ) diff --git a/packages/setup.go b/packages/setup.go index a345ae6aa..b6bf9e799 100644 --- a/packages/setup.go +++ b/packages/setup.go @@ -14,10 +14,10 @@ import ( type setup struct { command string - force bool module string onInstall []modify.File onUninstall []modify.File + force bool } var osExit = os.Exit diff --git a/queue/config.go b/queue/config.go index f531e23f1..8f8674f00 100644 --- a/queue/config.go +++ b/queue/config.go @@ -10,22 +10,18 @@ type Config struct { contractsconfig.Config appName string - debug bool defaultConnection string defaultQueue string - defaultConcurrent int failedDatabase string failedTable string + defaultConcurrent int + debug bool } func NewConfig(config contractsconfig.Config) *Config { defaultConnection := config.GetString("queue.default") defaultQueue := config.GetString(fmt.Sprintf("queue.connections.%s.queue", defaultConnection), "default") - defaultConcurrent := config.GetInt(fmt.Sprintf("queue.connections.%s.concurrent", defaultConnection), 1) - - if defaultConcurrent < 1 { - defaultConcurrent = 1 - } + defaultConcurrent := max(config.GetInt(fmt.Sprintf("queue.connections.%s.concurrent", defaultConnection), 1), 1) c := &Config{ Config: config, diff --git a/queue/driver_machinery.go b/queue/driver_machinery.go index 5193f42c7..f5fc9b9bb 100644 --- a/queue/driver_machinery.go +++ b/queue/driver_machinery.go @@ -19,11 +19,11 @@ import ( ) type Machinery struct { - appName string log contractslog.Log queueToServer map[string]*machinery.Server - redisDatabase int + appName string redisDSN string + redisDatabase int } func NewMachinery(config config.Config, log contractslog.Log, connection string) *Machinery { diff --git a/queue/driver_machinery_log.go b/queue/driver_machinery_log.go index fac8fa578..a6d9600fe 100644 --- a/queue/driver_machinery_log.go +++ b/queue/driver_machinery_log.go @@ -6,8 +6,8 @@ import ( ) type Debug struct { - debug bool log log.Log + debug bool } func NewDebug(debug bool, log log.Log) *Debug { @@ -60,8 +60,8 @@ func (r *Debug) Panicln(args ...any) { } type Info struct { - debug bool log log.Log + debug bool } func NewInfo(debug bool, log log.Log) *Info { @@ -114,8 +114,8 @@ func (r *Info) Panicln(args ...any) { } type Warning struct { - debug bool log log.Log + debug bool } func NewWarning(debug bool, log log.Log) *Warning { @@ -162,8 +162,8 @@ func (r *Warning) Panicln(args ...any) { } type Error struct { - debug bool log log.Log + debug bool } func NewError(debug bool, log log.Log) *Error { @@ -210,8 +210,8 @@ func (r *Error) Panicln(args ...any) { } type Fatal struct { - debug bool log log.Log + debug bool } func NewFatal(debug bool, log log.Log) *Fatal { diff --git a/queue/failer.go b/queue/failer.go index 94fbf651a..b03b5b519 100644 --- a/queue/failer.go +++ b/queue/failer.go @@ -70,10 +70,10 @@ func (r *Failer) modelFailedJobsToFailedJobs(modelFailedJobs []models.FailedJob) } type FailedJob struct { - failedJob models.FailedJob query db.Query queue contractsqueue.Queue json foundation.Json + failedJob models.FailedJob } func NewFailedJob(failedJob models.FailedJob, query db.Query, queue contractsqueue.Queue, json foundation.Json) *FailedJob { diff --git a/queue/failer_test.go b/queue/failer_test.go index 12d4e5905..bc5bffc03 100644 --- a/queue/failer_test.go +++ b/queue/failer_test.go @@ -73,7 +73,7 @@ func (s *FailerTestSuite) TestAll() { name: "success", setup: func() { var failedJobs []models.FailedJob - s.mockQuery.EXPECT().Get(&failedJobs).Run(func(dest interface{}) { + s.mockQuery.EXPECT().Get(&failedJobs).Run(func(dest any) { *dest.(*[]models.FailedJob) = modelFailedJobs }).Return(nil).Once() }, @@ -152,7 +152,7 @@ func (s *FailerTestSuite) TestGet() { s.mockQuery.EXPECT().WhereIn("uuid", []any{"test-uuid-1", "test-uuid-2"}).Return(s.mockQuery).Once() var failedJobs []models.FailedJob - s.mockQuery.EXPECT().Get(&failedJobs).Run(func(dest interface{}) { + s.mockQuery.EXPECT().Get(&failedJobs).Run(func(dest any) { *dest.(*[]models.FailedJob) = modelFailedJobs }).Return(nil).Once() }, @@ -168,7 +168,7 @@ func (s *FailerTestSuite) TestGet() { uuids: []string{}, setup: func() { var failedJobs []models.FailedJob - s.mockQuery.EXPECT().Get(&failedJobs).Run(func(dest interface{}) { + s.mockQuery.EXPECT().Get(&failedJobs).Run(func(dest any) { *dest.(*[]models.FailedJob) = modelFailedJobs }).Return(nil).Once() }, @@ -277,7 +277,7 @@ func (s *FailedJobTestSuite) TestRetry() { } var task utils.Task - s.mockJson.EXPECT().UnmarshalString(s.modelFailedJob.Payload, &task).Run(func(json string, dest interface{}) { + s.mockJson.EXPECT().UnmarshalString(s.modelFailedJob.Payload, &task).Run(func(json string, dest any) { *dest.(*utils.Task) = destTask }).Return(nil).Once() @@ -332,7 +332,7 @@ func (s *FailedJobTestSuite) TestRetry() { } var task utils.Task - s.mockJson.EXPECT().UnmarshalString(s.modelFailedJob.Payload, &task).Run(func(json string, dest interface{}) { + s.mockJson.EXPECT().UnmarshalString(s.modelFailedJob.Payload, &task).Run(func(json string, dest any) { *dest.(*utils.Task) = destTask }).Return(nil).Once() @@ -365,7 +365,7 @@ func (s *FailedJobTestSuite) TestRetry() { } var task utils.Task - s.mockJson.EXPECT().UnmarshalString(s.modelFailedJob.Payload, &task).Run(func(json string, dest interface{}) { + s.mockJson.EXPECT().UnmarshalString(s.modelFailedJob.Payload, &task).Run(func(json string, dest any) { *dest.(*utils.Task) = destTask }).Return(nil).Once() @@ -426,7 +426,7 @@ func (s *FailedJobTestSuite) TestSignature() { } var task utils.Task - s.mockJson.EXPECT().UnmarshalString(s.modelFailedJob.Payload, &task).Run(func(json string, dest interface{}) { + s.mockJson.EXPECT().UnmarshalString(s.modelFailedJob.Payload, &task).Run(func(json string, dest any) { *dest.(*utils.Task) = destTask }).Return(nil).Once() }, diff --git a/queue/models/job.go b/queue/models/job.go index e486302e7..d3e8949c0 100644 --- a/queue/models/job.go +++ b/queue/models/job.go @@ -3,13 +3,13 @@ package models import "github.com/goravel/framework/support/carbon" type Job struct { - ID uint `db:"id"` - Queue string `db:"queue"` - Payload string `db:"payload"` - Attempts int `db:"attempts"` ReservedAt *carbon.DateTime `db:"reserved_at"` AvailableAt *carbon.DateTime `db:"available_at"` CreatedAt *carbon.DateTime `db:"created_at"` + Queue string `db:"queue"` + Payload string `db:"payload"` + ID uint `db:"id"` + Attempts int `db:"attempts"` } func (r *Job) Increment() int { @@ -25,11 +25,11 @@ func (r *Job) Touch() *carbon.DateTime { } type FailedJob struct { - ID uint `db:"id"` + FailedAt *carbon.DateTime `db:"failed_at"` UUID string `db:"uuid"` Connection string `db:"connection"` Queue string `db:"queue"` Payload string `db:"payload"` Exception string `db:"exception"` - FailedAt *carbon.DateTime `db:"failed_at"` + ID uint `db:"id"` } diff --git a/queue/utils/convert.go b/queue/utils/convert.go index 56211c14e..9811f5d4a 100644 --- a/queue/utils/convert.go +++ b/queue/utils/convert.go @@ -17,9 +17,9 @@ type Task struct { } type Job struct { + Delay *time.Time `json:"delay"` Signature string `json:"signature"` Args []contractsqueue.Arg `json:"args"` - Delay *time.Time `json:"delay"` } func TaskToJson(task contractsqueue.Task, json foundation.Json) (string, error) { diff --git a/queue/worker.go b/queue/worker.go index 9bc3c7e23..37fdb307a 100644 --- a/queue/worker.go +++ b/queue/worker.go @@ -27,17 +27,18 @@ type Worker struct { json foundation.Json log log.Log + failedJobChan chan models.FailedJob + machinery *machinery.Worker + connection string queue string + wg sync.WaitGroup concurrent int - debug bool - currentDelay time.Duration - failedJobChan chan models.FailedJob - isShutdown atomic.Bool - maxDelay time.Duration - machinery *machinery.Worker - wg sync.WaitGroup + currentDelay time.Duration + maxDelay time.Duration + isShutdown atomic.Bool + debug bool } func NewWorker(config queue.Config, db db.DB, job queue.JobStorer, json foundation.Json, log log.Log, connection, queue string, concurrent int) (*Worker, error) { diff --git a/schedule/application.go b/schedule/application.go index 88308e46c..72fe5b11a 100644 --- a/schedule/application.go +++ b/schedule/application.go @@ -17,9 +17,9 @@ import ( type Application struct { artisan console.Artisan cache cache.Cache + log log.Log cron *cron.Cron events []schedule.Event - log log.Log debug bool } diff --git a/schedule/event.go b/schedule/event.go index bed2a93ad..0b2f88b19 100644 --- a/schedule/event.go +++ b/schedule/event.go @@ -13,8 +13,8 @@ type Event struct { callback func() command string cron string - delayIfStillRunning bool name string + delayIfStillRunning bool onOneServer bool skipIfStillRunning bool } diff --git a/session/manager.go b/session/manager.go index a9ab1b117..166c455c3 100644 --- a/session/manager.go +++ b/session/manager.go @@ -17,8 +17,11 @@ import ( var _ contractssession.Manager = (*Manager)(nil) type Manager struct { - config config.Config - json foundation.Json + sessionPool sync.Pool + config config.Config + json foundation.Json + + drivers map[string]contractssession.Driver cookie string defaultDriver string @@ -26,9 +29,7 @@ type Manager struct { gcInterval int lifetime int - drivers map[string]contractssession.Driver - sessionPool sync.Pool - mu sync.RWMutex + mu sync.RWMutex } func NewManager(config config.Config, json foundation.Json) *Manager { diff --git a/session/session.go b/session/session.go index e77a03cbf..95bdca390 100644 --- a/session/session.go +++ b/session/session.go @@ -14,12 +14,12 @@ import ( ) type Session struct { + driver sessioncontract.Driver + json foundation.Json + attributes map[string]any id string name string - attributes map[string]any - driver sessioncontract.Driver started bool - json foundation.Json } func NewSession(name string, driver sessioncontract.Driver, json foundation.Json, id ...string) *Session { diff --git a/support/color/color.go b/support/color/color.go index 341b92ec3..fe7a72ad5 100644 --- a/support/color/color.go +++ b/support/color/color.go @@ -112,19 +112,19 @@ func Magenta() support.Printer { type Color uint8 -func (c Color) Sprint(a ...interface{}) string { +func (c Color) Sprint(a ...any) string { return pterm.Color(c).Sprint(a...) } -func (c Color) Sprintln(a ...interface{}) string { +func (c Color) Sprintln(a ...any) string { return pterm.Color(c).Sprintln(a...) } -func (c Color) Sprintf(format string, a ...interface{}) string { +func (c Color) Sprintf(format string, a ...any) string { return pterm.Color(c).Sprintf(format, a...) } -func (c Color) Sprintfln(format string, a ...interface{}) string { +func (c Color) Sprintfln(format string, a ...any) string { return pterm.Color(c).Sprintfln(format, a...) } diff --git a/support/debug/func.go b/support/debug/func.go index be2dcea36..0573c0bd7 100644 --- a/support/debug/func.go +++ b/support/debug/func.go @@ -8,11 +8,11 @@ import ( type FuncInfo struct { File string - Line int Name string pkgName string pkgPath string shortName string + Line int } func (f *FuncInfo) PackageName() string { diff --git a/support/env/env.go b/support/env/env.go index 23489740a..1884a9af8 100644 --- a/support/env/env.go +++ b/support/env/env.go @@ -5,6 +5,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" ) @@ -26,13 +27,7 @@ func IsArm() bool { } func IsArtisan() bool { - for _, arg := range os.Args { - if arg == "artisan" { - return true - } - } - - return false + return slices.Contains(os.Args, "artisan") } // IsDarwin returns whether the current operating system is Darwin. @@ -68,13 +63,7 @@ func IsLinux() bool { // IsNoANSI checks if the application is running with the --no-ansi flag. func IsNoANSI() bool { - for _, arg := range os.Args { - if arg == "--no-ansi" { - return true - } - } - - return false + return slices.Contains(os.Args, "--no-ansi") } // IsTesting checks if the application is running in testing mode. diff --git a/support/maps/maps.go b/support/maps/maps.go index 3ea550b52..2af324241 100644 --- a/support/maps/maps.go +++ b/support/maps/maps.go @@ -1,6 +1,7 @@ package maps import ( + "maps" "reflect" ) @@ -63,9 +64,7 @@ func FromStruct(data any) map[string]any { if fieldValue.Kind() == reflect.Struct { subStructMap := FromStruct(fieldValue.Interface()) if fieldType.Anonymous { - for key, value := range subStructMap { - res[key] = value - } + maps.Copy(res, subStructMap) } else { res[fieldType.Name] = subStructMap } diff --git a/support/process/utils.go b/support/process/utils.go index a247026fe..e053d4ca8 100644 --- a/support/process/utils.go +++ b/support/process/utils.go @@ -23,7 +23,7 @@ func IsPortUsing(port int) bool { } func ValidPort() int { - for i := 0; i < 60; i++ { + for range 60 { random := rand.Intn(10000) + 10000 if !IsPortUsing(random) { return random diff --git a/support/str/str.go b/support/str/str.go index 2dfa1c377..20d82ef68 100644 --- a/support/str/str.go +++ b/support/str/str.go @@ -22,8 +22,8 @@ type String struct { // ExcerptOption is the option for Excerpt method type ExcerptOption struct { - Radius int Omission string + Radius int } // Of creates a new String instance with the given value. @@ -342,13 +342,13 @@ func (s *String) IsAscii() bool { // IsMap returns true if the string is a valid Map. func (s *String) IsMap() bool { - var obj map[string]interface{} + var obj map[string]any return json.Unmarshal([]byte(s.value), &obj) == nil } // IsSlice returns true if the string is a valid Slice. func (s *String) IsSlice() bool { - var arr []interface{} + var arr []any return json.Unmarshal([]byte(s.value), &arr) == nil } @@ -920,10 +920,7 @@ func Substr(str string, start int, length ...int) string { // If the start index is negative, count backwards from the end of the string. if start < 0 { - start = strLen + start - if start < 0 { - start = 0 - } + start = max(strLen+start, 0) } if len(length) > 0 { diff --git a/testing/docker/database.go b/testing/docker/database.go index 1c9a9917b..31536a330 100644 --- a/testing/docker/database.go +++ b/testing/docker/database.go @@ -16,8 +16,8 @@ type Database struct { docker.DatabaseDriver artisan contractsconsole.Artisan config contractsconfig.Config - connection string orm contractsorm.Orm + connection string } func NewDatabase(artisan contractsconsole.Artisan, config contractsconfig.Config, orm contractsorm.Orm, connection string) (*Database, error) { diff --git a/testing/http/assertable_json.go b/testing/http/assertable_json.go index 0272bb498..311e3db06 100644 --- a/testing/http/assertable_json.go +++ b/testing/http/assertable_json.go @@ -12,10 +12,10 @@ import ( ) type AssertableJson struct { - t *testing.T json foundation.Json - jsonStr string + t *testing.T decoded map[string]any + jsonStr string } func NewAssertableJSON(t *testing.T, json foundation.Json, jsonStr string) (contractshttp.AssertableJSON, error) { diff --git a/testing/http/test_request.go b/testing/http/test_request.go index 50d1dc982..64dbdbc3b 100644 --- a/testing/http/test_request.go +++ b/testing/http/test_request.go @@ -129,7 +129,7 @@ func (r *TestRequest) WithToken(token string, ttype ...string) contractshttp.Req } func (r *TestRequest) WithBasicAuth(username, password string) contractshttp.Request { - encoded := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password))) + encoded := base64.StdEncoding.EncodeToString(fmt.Appendf(nil, "%s:%s", username, password)) return r.WithToken(encoded, "Basic") } diff --git a/testing/http/test_response.go b/testing/http/test_response.go index 99765ede1..f6bcb13bf 100644 --- a/testing/http/test_response.go +++ b/testing/http/test_response.go @@ -20,13 +20,13 @@ import ( ) type TestResponseImpl struct { - t *testing.T - mu sync.Mutex - response *http.Response - content string json foundation.Json session contractssession.Manager + t *testing.T + response *http.Response sessionAttributes map[string]any + content string + mu sync.Mutex } func NewTestResponse(t *testing.T, response *http.Response, json foundation.Json, session contractssession.Manager) contractshttp.Response { diff --git a/translation/file_loader.go b/translation/file_loader.go index 7c765ea96..dda8767fd 100644 --- a/translation/file_loader.go +++ b/translation/file_loader.go @@ -11,8 +11,8 @@ import ( ) type FileLoader struct { - paths []string json foundation.Json + paths []string } func NewFileLoader(paths []string, json foundation.Json) contractstranslation.Loader { diff --git a/translation/fs_loader.go b/translation/fs_loader.go index c883918c2..0ff12464a 100644 --- a/translation/fs_loader.go +++ b/translation/fs_loader.go @@ -10,9 +10,9 @@ import ( ) type FSLoader struct { - path string fs fs.FS json foundation.Json + path string } func NewFSLoader(path string, fs fs.FS, json foundation.Json) contractstranslation.Loader { diff --git a/translation/translator.go b/translation/translator.go index 04f2c8a4a..66747eab2 100644 --- a/translation/translator.go +++ b/translation/translator.go @@ -20,11 +20,11 @@ type Translator struct { ctx context.Context fsLoader translationcontract.Loader fileLoader translationcontract.Loader + logger logcontract.Log + selector *MessageSelector locale string fallback string - selector *MessageSelector key string - logger logcontract.Log mu sync.Mutex } diff --git a/validation/validation.go b/validation/validation.go index aaaab14d0..42b058f42 100644 --- a/validation/validation.go +++ b/validation/validation.go @@ -2,6 +2,7 @@ package validation import ( "net/url" + "slices" "github.com/gookit/validate" @@ -77,10 +78,8 @@ func (r *Validation) Make(data any, rules map[string]string, options ...validate func (r *Validation) AddFilters(filters []validatecontract.Filter) error { existFilterNames := r.existFilterNames() for _, filter := range filters { - for _, existFilterName := range existFilterNames { - if existFilterName == filter.Signature() { - return errors.ValidationDuplicateFilter.Args(filter.Signature()) - } + if slices.Contains(existFilterNames, filter.Signature()) { + return errors.ValidationDuplicateFilter.Args(filter.Signature()) } } @@ -91,10 +90,8 @@ func (r *Validation) AddFilters(filters []validatecontract.Filter) error { func (r *Validation) AddRules(rules []validatecontract.Rule) error { existRuleNames := r.existRuleNames() for _, rule := range rules { - for _, existRuleName := range existRuleNames { - if existRuleName == rule.Signature() { - return errors.ValidationDuplicateRule.Args(rule.Signature()) - } + if slices.Contains(existRuleNames, rule.Signature()) { + return errors.ValidationDuplicateRule.Args(rule.Signature()) } }