Files
blocky/internal/block/int64_component/int64_component.go

92 lines
2.0 KiB
Go

package int64_component
import (
"blocky/internal/block"
"blocky/internal/block/validation"
"encoding/json"
"fmt"
)
type Int64Component struct {
identifier string
name string
validators []validation.Validator
Int64Validators []Int64Validator
}
func (t Int64Component) Type() block.ComponentType {
return block.Int64ComponentType
}
func (t Int64Component) Name() string {
return t.name
}
func (t Int64Component) Identifier() string {
return t.identifier
}
func (t Int64Component) Validators() []validation.Validator {
return t.validators
}
func NewInt64Component(identifier, name string, validators []validation.ComponentOption, int64Validators []Int64ComponentOption) Int64Component {
cfg := &validation.ComponentConfig{}
for _, opt := range validators {
opt(cfg)
}
int64Cfg := &Int64ComponentConfig{}
for _, opt := range int64Validators {
opt(int64Cfg)
}
return Int64Component{identifier: identifier, name: name, validators: cfg.Validators, Int64Validators: int64Cfg.Validators}
}
func (t Int64Component) NewInstance() block.ComponentInstance {
return &Int64ComponentInstance{}
}
type Int64ComponentInstance struct {
value int64
}
func (t *Int64ComponentInstance) Value() interface{} {
return t.value
}
func (t *Int64ComponentInstance) FromJSON(component block.Component, data json.RawMessage) error {
var s int64
if data != nil {
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
t.value = s
}
for _, v := range component.Validators() {
if err := v(s); err != nil {
return fmt.Errorf("%s: %w", component.Identifier(), err)
}
}
if tc, ok := component.(Int64Component); ok {
for _, v := range tc.Int64Validators {
if err := v(s); err != nil {
return fmt.Errorf("%s: %w", component.Identifier(), err)
}
}
}
return nil
}
type Int64Validator func(value any) error
type Int64ComponentConfig struct {
Validators []Int64Validator
}
type Int64ComponentOption func(*Int64ComponentConfig)