laravelcf

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 27 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

codicefiscale (Go)

Italian codice fiscale parsing, generation, validation and omocodia handling for Go, ported from the PHP package robertogallea/laravel-codicefiscale 3.x. The full plan is in the spec, issue #1.

This repository holds two Go modules (ADR-0008). Each has its own README, and every Go example in them is an Example function that go test compiles and, where it has an output, checks.

Module Purpose README
github.com/robertogallea/laravel-codicefiscale-go/codicefiscale Framework-agnostic core. No third-party dependency; builds for wasip1/wasm and js/wasm. codicefiscale
github.com/robertogallea/laravel-codicefiscale-go Adapter for Laravel for Go (go.laravel.com v0.1.x, a beta): package, env config, validation rule, matching rules, the codice-fiscale:update-places and codice-fiscale:install-skill commands, dataset hot reload and a Faker helper. ADAPTER.md

Start with the adapter README if you use Laravel for Go, and with the core README otherwise. Domain terms are defined in CONTEXT.md; decisions are in docs/adr.

Parity with PHP

Behaviour matches PHP robertogallea/laravel-codicefiscale 3.3.0, commit a66afc919befbb6b8e5a038d39ee76759959687c, the version recorded in the header of the golden corpus in codicefiscale/testdata/golden/. Every corpus case is asserted by the Go tests (ADR-0009); regenerating the corpus from PHP is the only way to change what parity means. The core is released independently of the Laravel for Go beta, so a framework change only forces an adapter release.

Compatibility
Adapter Core go.laravel.com PHP version PHP commit
v0.1.x codicefiscale/v0.1.x v0.1.x 3.3.0 a66afc919befbb6b8e5a038d39ee76759959687c
Differences from PHP
  • The core never reads a clock: Parser, Validator and Matcher take an explicit reference date. The adapter passes the framework clock's date.
  • codice-fiscale:update-places has no --municipalities-only or --countries-only: the dataset is one file built from all four sources and written atomically.
  • Sibling matching is one Matches rule per field, not a fluent matching(...) builder, because a Laravel for Go rule returns one message per rule.
  • Message overrides are set in code, through package options, not in a config file, because the framework has none.
  • Fake codici fiscali come from a free function over the framework's Faker (laravelcf.FakeCodiceFiscale), not a Faker provider method.
  • The agent skill is installed on request by codice-fiscale:install-skill, not discovered by Boost, and there is no upgrade skill.
  • Birthplace data is never bundled (ADR-0001); build it with the update command, or with the core's sources package.

Framework version

The adapter is built against go.laravel.com v0.1.1, a beta, and needs Go 1.27, the framework's floor. The framework has no package auto-discovery, so the package is added to Packages by hand. Framework bumps are made by hand, and a breaking framework release brings an adapter minor release. The core builds with Go 1.23.

Developing

Run go test ./... in each module: codicefiscale/, codicefiscale/internal/sqltest and the repository root. A README code block that is not the body of an Example function fails the tests (readme_test.go in the core and the adapter), and so does one in the agent skill, skills/using-laravel-codicefiscale/SKILL.md. The golden corpus is exported from the PHP repo; never edit it by hand. See AGENTS.md for the conventions in full.

Releasing

Release order: merge, tag and push codicefiscale/vX.Y.Z, wait for the module proxy, make the adapter's go.mod require that version, run the GOWORK=off check (the adapter-gowork-off CI job), tag vX.Y.Z, confirm on pkg.go.dev. The exact commands are in AGENTS.md.

License

MIT.

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())
}
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)))
}
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.")),
		},
	}
}
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")))
}
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()
		},
	}
}
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()},
	}
}

Index

Examples

Constants

The fields a MatchRule can compare a codice fiscale with.

View Source
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

View Source
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

func FakeCodiceFiscale(f *factory.Faker) string

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

func FakeCodiceFiscaleOn(f *factory.Faker, reference date.Date) string

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) Name

func (*InstallSkill) Name() string

Name implements laravel.Command.

func (*InstallSkill) Run

func (c *InstallSkill) Run(ctx context.Context, con *console.Console) error

Run implements laravel.Command.

type Locale

type Locale string

A Locale selects the language of the built-in validation messages.

const (
	// English is the default locale.
	English Locale = "en"
	// Italian selects the Italian messages.
	Italian Locale = "it"
)

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

func (r MatchRule) Locale(locale Locale) MatchRule

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

func (r MatchRule) Validate(ctx context.Context, field validation.Field) error

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

func From(ctx context.Context) *Package

From returns the package that ctx's application installed. It panics if the application did not list the package.

func New

func New(opts ...Option) *Package

New returns the package to list in laravel.Options.Packages. Each option changes the settings read from the environment.

func (*Package) Config

func (p *Package) Config() Config

Config returns the package's settings.

func (*Package) Register

func (p *Package) Register(app *laravel.Registrar) error

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 CodiceFiscale

func CodiceFiscale() Rule

CodiceFiscale returns the validation rule.

func (Rule) Locale

func (r Rule) Locale(locale Locale) Rule

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

func (r Rule) Validate(ctx context.Context, field validation.Field) error

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) Name

func (*UpdatePlaces) Name() string

Name implements laravel.Command.

func (*UpdatePlaces) Run

Run implements laravel.Command.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL