Documentation
¶
Overview ¶
Package laravelcf integrates the codicefiscale core with Laravel for Go: env config, the validation rule CodiceFiscale, the matching rules Matches, the codice-fiscale:update-places and codice-fiscale:install-skill commands, dataset reload and FakeCodiceFiscale.
Add the package to Packages in bootstrap/app.go; the framework has no auto-discovery:
Packages: []laravel.Package{laravelcf.New()},
The package never touches the app's database and imports no database driver. To store a codice fiscale, use codicefiscale.CodiceFiscale (or codicefiscale.Lenient) as a model field. Without a dataset file the application still boots and logs a warning, and every codice fiscale then fails with unknown_birth_place until codice-fiscale:update-places has built it; the package never schedules that command.
The setup, settings, rules, messages and commands are documented, with examples that go test checks, in ADAPTER.md at https://github.com/robertogallea/laravel-codicefiscale-go/blob/main/ADAPTER.md. Domain terms are defined in CONTEXT.md in the same repository.
Example (Factory) ¶
package main
import (
"context"
"fmt"
"go.laravel.com/factory"
laravelcf "github.com/robertogallea/laravel-codicefiscale-go"
"github.com/robertogallea/laravel-codicefiscale-go/codicefiscale"
)
func main() {
// In a factory or a seeder, draw from the run's faker: laraveltest seeds it
// from the test's name, and db:seed shares one per run.
ctx := context.Background()
fake := factory.FakerOf(ctx)
tax, err := codicefiscale.Parse(laravelcf.FakeCodiceFiscale(fake))
if err != nil {
panic(err)
}
fmt.Println(tax.HasValidCheckCharacter())
}
Output:
Example (Locale) ¶
package main
import (
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
laravelcf "github.com/robertogallea/laravel-codicefiscale-go"
)
func main() {
// One rule's messages in Italian, whatever CODICEFISCALE_LOCALE says.
var in struct {
CodiceFiscale string `json:"codice_fiscale"`
Nome string `json:"nome"`
}
_ = validation.For(&in,
rule.Field(&in.CodiceFiscale,
rule.Required,
laravelcf.CodiceFiscale().Locale(laravelcf.Italian),
laravelcf.Matches(laravelcf.FirstName, "nome").Locale(laravelcf.Italian)))
}
Output:
Example (Messages) ¶
package main
import (
laravel "go.laravel.com"
laravelcf "github.com/robertogallea/laravel-codicefiscale-go"
)
func main() {
// Message overrides are set in code; the framework has no config files.
_ = laravel.Options{
Packages: []laravel.Package{
laravelcf.New(laravelcf.WithMessage(laravelcf.MessageInvalidChecksum,
"The :attribute has a wrong check character.")),
},
}
}
Output:
Example (Model) ¶
package main
import (
"fmt"
"github.com/robertogallea/laravel-codicefiscale-go/codicefiscale"
)
func main() {
// The core types are model fields as they are; the package adds no column
// type.
type Person struct {
ID int64
Tax codicefiscale.CodiceFiscale // NOT NULL; a corrupt value fails to load
Spouse *codicefiscale.CodiceFiscale // nullable column
Legacy codicefiscale.Lenient // never fails a row
}
tax, _ := codicefiscale.Parse(" rssmra95e05f205z ")
person := Person{Tax: tax, Legacy: codicefiscale.Lenient{}}
stored, _ := person.Tax.Value() // what the column holds
fmt.Println(stored, person.Legacy.Valid)
}
Output: RSSMRA95E05F205Z false
Example (Rules) ¶
package main
import (
"go.laravel.com/validation"
"go.laravel.com/validation/rule"
laravelcf "github.com/robertogallea/laravel-codicefiscale-go"
)
func main() {
type Registration struct {
CodiceFiscale string `json:"codice_fiscale"`
Nome string `json:"nome"`
Cognome string `json:"cognome"`
DataNascita string `json:"data_nascita"`
LuogoNascita string `json:"luogo_nascita"`
Sesso string `json:"sesso"`
}
var in Registration
_ = validation.For(&in,
rule.Field(&in.CodiceFiscale,
rule.Required,
laravelcf.CodiceFiscale(),
laravelcf.Matches(laravelcf.FirstName, "nome"),
laravelcf.Matches(laravelcf.LastName, "cognome"),
laravelcf.Matches(laravelcf.BirthDate, "data_nascita"),
laravelcf.Matches(laravelcf.BirthPlace, "luogo_nascita"),
laravelcf.Matches(laravelcf.Gender, "sesso")))
}
Output:
Example (Schedule) ¶
package main
import (
"context"
laravel "go.laravel.com"
"go.laravel.com/schedule"
laravelcf "github.com/robertogallea/laravel-codicefiscale-go"
)
func main() {
// The package never schedules the update command; to refresh the data
// weekly, schedule it by name in your application.
_ = laravel.Options{
Packages: []laravel.Package{laravelcf.New()},
Schedule: func(_ context.Context, s *schedule.Schedule) {
s.Command("codice-fiscale:update-places").Weekly()
},
}
}
Output:
Example (Setup) ¶
package main
import (
laravel "go.laravel.com"
laravelcf "github.com/robertogallea/laravel-codicefiscale-go"
)
func main() {
// In bootstrap/app.go. The framework has no package auto-discovery.
_ = laravel.Options{
Packages: []laravel.Package{laravelcf.New()},
}
}
Output:
Index ¶
Examples ¶
Constants ¶
const ( FirstName = codicefiscale.PersonFieldFirstName LastName = codicefiscale.PersonFieldLastName BirthDate = codicefiscale.PersonFieldBirthDate BirthPlace = codicefiscale.PersonFieldBirthPlace Gender = codicefiscale.PersonFieldGender )
The fields a MatchRule can compare a codice fiscale with.
const ReloadTick = "codice-fiscale:reload-places"
ReloadTick is the name of the tick that reloads the dataset when its file is replaced. The package registers it unless CODICEFISCALE_RELOAD_INTERVAL is 0.
Variables ¶
var Skill string
Skill is the usage skill for AI agents that codice-fiscale:install-skill writes: a SKILL.md in the agentskills.io format that describes the Go API of the core and the adapter, and nothing else.
Functions ¶
func FakeCodiceFiscale ¶
FakeCodiceFiscale returns a random, structurally valid codice fiscale for a factory or a seeder, as seen from today's date on the faker's clock.
It draws only from the public methods of f (Pick, FirstName, LastName and DateBetween), so a seeded Faker, such as the one laraveltest seeds from the test's name, gives the same code every time. The birthplace is one of the ten municipalities of faker.KnownBirthPlaces, so no dataset is needed. The code is built by the core Generator, so its check character is right and it is in Canonical form (no omocodia substitution); it passes Rule.
A Faker with no Clock reads the real time, so a seed gives the same code only within a day; use FakeCodiceFiscaleOn to pin the reference date.
To store it in a model field of type codicefiscale.CodiceFiscale, parse it with codicefiscale.Parse.
func FakeCodiceFiscaleOn ¶
FakeCodiceFiscaleOn is like FakeCodiceFiscale with the reference date given: birth dates fall in the 100 years up to reference (and never before the birthplace's current era), so the same seed and the same date give the same code on any day.
Example ¶
package main
import (
"fmt"
"go.laravel.com/date"
"go.laravel.com/factory"
laravelcf "github.com/robertogallea/laravel-codicefiscale-go"
)
func main() {
// The same Faker seed gives the same codice fiscale.
reference := date.Date{Year: 2026, Month: 12, Day: 3}
first := laravelcf.FakeCodiceFiscaleOn(&factory.Faker{Seed: 7}, reference)
again := laravelcf.FakeCodiceFiscaleOn(&factory.Faker{Seed: 7}, reference)
fmt.Println(first == again, first)
}
Output: true SCHMTT63M11D969I
Types ¶
type Config ¶
type Config struct {
// DatasetPath is the birthplace dataset file loaded at boot.
// CODICEFISCALE_DATASET_PATH sets it; it defaults to
// storage/app/codicefiscale/places.json.
DatasetPath string
// MaxAge is the maximum age, in whole years, a birth date may imply.
// CODICEFISCALE_MAX_AGE sets it; it defaults to
// [codicefiscale.DefaultMaxAge].
MaxAge int
// Locale is the language of the built-in messages.
// CODICEFISCALE_LOCALE sets it (en or it); it defaults to [English].
Locale Locale
// Messages replaces built-in message templates, by key, in every locale.
// A template may use :attribute. It is empty unless set in code.
Messages map[MessageKey]string
// Sources are the URLs the update command downloads from.
Sources Sources
// RetryDelay is how long the update command waits before it retries a
// failed download; it makes three attempts in all.
// CODICEFISCALE_RETRY_DELAY_MS sets it, in milliseconds; it defaults to
// 2000, as in PHP.
RetryDelay time.Duration
// ReloadInterval is how often a running server or worker checks whether
// the dataset file was replaced. CODICEFISCALE_RELOAD_INTERVAL sets it, in
// seconds; it defaults to 10, and 0 turns the check off.
ReloadInterval time.Duration
}
Config is the package's settings: the environment's values, then changed by the [Option]s given to New.
type InstallSkill ¶
type InstallSkill struct {
// contains filtered or unexported fields
}
InstallSkill is the codice-fiscale:install-skill command: it writes Skill to <base>/.agents/skills/using-laravel-codicefiscale/SKILL.md, where Laravel for Go applications already keep their skills.
It is opt-in: nothing runs it for you. It refuses to overwrite an existing file, so the application keeps its own edits, unless --force is given. --path names another skills folder, relative to the application's base path or absolute.
func (*InstallSkill) Description ¶
func (*InstallSkill) Description() string
Description implements laravel.Command.
func (*InstallSkill) Flags ¶
func (c *InstallSkill) Flags(flags *flag.FlagSet)
Flags implements laravel.Command.
func (*InstallSkill) Run ¶
Run implements laravel.Command.
type MatchRule ¶
type MatchRule struct {
// contains filtered or unexported fields
}
MatchRule compares a codice fiscale with one sibling input field, with the core's Matcher. Build it with Matches and give it, after Rule, to the codice fiscale field, one per sibling field:
rule.Field(&in.CodiceFiscale, rule.Required, laravelcf.CodiceFiscale(), laravelcf.Matches(laravelcf.FirstName, "nome"), laravelcf.Matches(laravelcf.Gender, "sesso"))
The framework gives a rule one message, so each field that does not match gives its own: the mismatch message, with :attribute the label of the codice fiscale field and :field the sibling's name, as in the argument.
The sibling is read from the same struct as the codice fiscale field. As in PHP and the Rust adapter, a sibling that is absent, not a string, blank or not readable as what it stands for is skipped, never a mismatch:
- names compare as given;
- a birth date is YYYY-MM-DD, optionally followed by T or a space and a time, which is ignored;
- a birthplace is a birthplace code (a letter and three digits, any case);
- a gender is M or F, any case.
The reference date for the birth year is the framework clock's date, and the maximum age is the configured one. When the codice fiscale itself is not valid, or is not a string, the rule gives nothing and leaves the reporting to Rule.
func Matches ¶
func Matches(field codicefiscale.PersonField, sibling string) MatchRule
Matches returns the rule comparing the codice fiscale with field, taken from the sibling input field named sibling. A field that is not one of FirstName, LastName, BirthDate, BirthPlace and Gender is never compared.
func (MatchRule) Locale ¶
Locale writes this rule's message in locale, whatever CODICEFISCALE_LOCALE says. Each matching rule takes its own locale. A message override still wins over the built-in message.
func (MatchRule) Validate ¶
Validate implements validation.Rule.
type MessageKey ¶
type MessageKey string
A MessageKey names a validation message. The keys are the PHP package's, with BirthPlaceNotAttributable for its pre-3.3 birth_place_not_valid_on_date (ADR-0015).
const ( // MessageInvalidFormat: not a structurally valid codice fiscale. MessageInvalidFormat MessageKey = "invalid_format" // MessageInvalidChecksum: the check character does not match. MessageInvalidChecksum MessageKey = "invalid_checksum" // MessageInvalidDate: no plausible birth date. MessageInvalidDate MessageKey = "invalid_date" // MessageUnknownBirthPlace: the birthplace code has never existed. MessageUnknownBirthPlace MessageKey = "unknown_birth_place" // MessageBirthPlaceNotAttributable: every era of the birthplace code ended // before the birth date. MessageBirthPlaceNotAttributable MessageKey = "birth_place_not_attributable" // MessageMismatch: the code does not match a sibling field. MessageMismatch MessageKey = "mismatch" )
func MessageKeys ¶
func MessageKeys() []MessageKey
MessageKeys lists every key, in the order PHP lists them.
func (MessageKey) Template ¶
func (k MessageKey) Template(locale Locale) string
Template returns the built-in message template of key in locale; an unknown locale reads as English.
type Option ¶
type Option func(cfg *Config)
An Option changes the settings the package read from the environment.
func WithMessage ¶
func WithMessage(key MessageKey, template string) Option
WithMessage overrides the built-in message of one key.
func WithMessages ¶
func WithMessages(messages map[MessageKey]string) Option
WithMessages overrides the built-in message of each key in messages. Any key not listed keeps its built-in text.
type Package ¶
type Package struct {
// contains filtered or unexported fields
}
Package is the Laravel package. It is also the service the rules reach through the context; see From.
func From ¶
From returns the package that ctx's application installed. It panics if the application did not list the package.
func New ¶
New returns the package to list in laravel.Options.Packages. Each option changes the settings read from the environment.
func (*Package) Register ¶
Register implements laravel.Package.
func (*Package) Repository ¶
func (p *Package) Repository() codicefiscale.BirthPlaceRepository
Repository returns the birthplace repository: the dataset loaded at boot, or an empty one when there was no dataset file.
type Rule ¶
type Rule struct {
// contains filtered or unexported fields
}
Rule validates a codice fiscale: format, check character, birth date and birthplace, against the dataset the package loaded. Build it with CodiceFiscale.
Like the framework's own rules it skips a missing or blank field, so add rule.Required to reject one. A value that is not a string fails with invalid_format.
The framework gives a rule one error. When a code has several failures, that error holds every message, in the validator's order, a message equal to the one before it dropped, separated by a space.
func (Rule) Locale ¶
Locale writes this rule's messages in locale, whatever CODICEFISCALE_LOCALE says. A message override still wins over the built-in message.
func (Rule) Validate ¶
Validate implements validation.Rule.
type Sources ¶
type Sources struct {
// Municipalities is ANPR's comuni archive CSV.
// CODICEFISCALE_SOURCE_MUNICIPALITIES sets it.
Municipalities string
// SuppressedMunicipalities is ISTAT's suppressed-comuni report (Situas
// report 128), fetched page by page.
// CODICEFISCALE_SOURCE_SUPPRESSED_MUNICIPALITIES sets it.
SuppressedMunicipalities string
// Countries is MAECI's stati-esteri table (XLSX).
// CODICEFISCALE_SOURCE_COUNTRIES sets it.
Countries string
// HistoricalCountries is ISTAT's historical foreign-countries report
// (469). CODICEFISCALE_SOURCE_HISTORICAL_COUNTRIES sets it.
HistoricalCountries string
}
Sources are the URLs codice-fiscale:update-places downloads from. The defaults are the PHP package's.
type UpdatePlaces ¶
type UpdatePlaces struct{}
UpdatePlaces is the codice-fiscale:update-places command: it downloads every source, rebuilds the birthplace dataset and writes it atomically. A failure at any step leaves the previous dataset file untouched.
The package registers it but never schedules it. To refresh the data weekly, schedule it in the application; see the README.
func (*UpdatePlaces) Description ¶
func (*UpdatePlaces) Description() string
Description implements laravel.Command.
func (*UpdatePlaces) Run ¶
Run implements laravel.Command.