Skip to content

✅ Validate

Validate the format, schema, and consistency of composer.json and composer.lock, and check constraints such as security vulnerabilities and platform prohibitions.

Composer's validate command is the entry point for dependency governance. Composer Skills breaks it into a set of semantic methods: from the basic Validate, to strict mode, skipping specific checks, schema-only validation, lock sync checks, and the structured ValidateStructured. Each method corresponds to a "check granularity", avoiding hand-stitching command-line arguments in scripts.

When to Use

  • ✅ Pre-commit local validation: whether composer.json conforms to the schema and fields are complete.
  • 📦 Pre-publish checks: whether Packagist publishing requirements are met (the inverse of --no-check-publish).
  • 🔄 CI sync checks: whether composer.lock is in sync with composer.json and properly formatted.
  • 🛡️ Security integration: CheckForSecurityVulnerabilities returns "output + whether there are vulnerabilities" in a single call.
  • 🧩 Platform constraint inspection: Prohibit shows which packages are prohibited from installation by the current platform requirements.

Structured Return Types

ValidateResult

Returned by ValidateStructured / ParseValidateOutput.

go
type ValidateResult struct {
    Valid    bool     `json:"valid"`
    Errors   []string `json:"errors,omitempty"`
    Warnings []string `json:"warnings,omitempty"`
}
FieldTypeDescription
ValidboolWhether validation passes overall
Errors[]stringList of error messages (presence means Valid=false)
Warnings[]stringList of warning messages (does not affect Valid)

Parsing Logic

ParseValidateOutput scans the output line by line: lines containing error/Error go into Errors and set Valid=false; lines containing warning/Warning go into Warnings. ValidateStructured also forces Valid=false when the command returns a non-zero exit code.


Validate

✅ Validate that composer.json is valid (convenience form with no return value).

Signature

go
func (c *Composer) Validate() error

Parameters

None.

Return Values

ValueTypeDescription
ErrorerrorReturns an error when validation fails; nil means passed

Definition Location

This method is defined in config.go; its signature differs from the other methods in validate.go that return (string, error) — it only cares about "whether it passed" and does not return output text. To get the output, use ValidateStructured or the ValidateXxx methods below.

Example

go
if err := comp.Validate(); err != nil {
    log.Fatalf("composer.json validation failed: %v", err)
}
fmt.Println("composer.json validation passed")

ValidateStrict

✅ Validate composer.json in strict mode.

Signature

go
func (c *Composer) ValidateStrict() (string, error)

Parameters

None.

Return Values

ValueTypeDescription
OutputstringOutput of composer validate --strict
ErrorerrorReturned when validation fails

Equivalent Command

composer validate --strict

Example

go
output, err := comp.ValidateStrict()
if err != nil {
    log.Fatalf("Strict validation failed: %v", err)
}
fmt.Println("Validation result:", output)

ValidateWithNoCheck

✅ Validate composer.json but do not check all platform requirements and other constraints.

Signature

go
func (c *Composer) ValidateWithNoCheck() (string, error)

Parameters

None.

Return Values

ValueTypeDescription
OutputstringValidation output
ErrorerrorReturned when validation fails

Equivalent Command

composer validate --no-check-all

Example

go
output, err := comp.ValidateWithNoCheck()
if err != nil {
    log.Fatalf("Validation failed: %v", err)
}
fmt.Println("Format-only validation result:", output)

ValidateWithCheckVersion

✅ Validate composer.json and check dependency version constraints (including transitive dependencies).

Signature

go
func (c *Composer) ValidateWithCheckVersion() (string, error)

Parameters

None.

Return Values

ValueTypeDescription
OutputstringValidation output
ErrorerrorReturned when validation fails

Equivalent Command

composer validate --with-dependencies

Example

go
output, err := comp.ValidateWithCheckVersion()
if err != nil {
    log.Fatalf("Version constraint validation failed: %v", err)
}
fmt.Println("Version constraint validation result:", output)

ValidateSchema

✅ Only validate that composer.json and composer.lock conform to the JSON schema, without checking other constraints.

Signature

go
func (c *Composer) ValidateSchema() (string, error)

Parameters

None.

Return Values

ValueTypeDescription
OutputstringValidation output
ErrorerrorReturned when validation fails

Equivalent Command

composer validate --no-check-all --no-check-publish --no-check-version

Example

go
output, err := comp.ValidateSchema()
if err != nil {
    log.Fatalf("Schema validation failed: %v", err)
}
fmt.Println("Schema validation result:", output)

NormalizeComposerJson

✅ Format composer.json to conform to the canonical format.

Signature

go
func (c *Composer) NormalizeComposerJson() (string, error)

Parameters

None.

Return Values

ValueTypeDescription
OutputstringOutput of the normalize command
ErrorerrorReturned when formatting fails

Equivalent Command

composer normalize (requires the ergebnis/composer-normalize plugin)

Example

go
output, err := comp.NormalizeComposerJson()
if err != nil {
    if strings.Contains(err.Error(), "command not found") {
        fmt.Println("Please install the normalize plugin first: composer global require ergebnis/composer-normalize")
    } else {
        log.Fatalf("Formatting failed: %v", err)
    }
}
fmt.Println("Formatting result:", output)

Depends on External Plugin

normalize is not a built-in Composer command; without the plugin installed it reports "command not found". You can pair it with CheckNormalization to first detect whether formatting is needed.


ValidateComposerLock

✅ Validate that composer.lock exists and is in sync with composer.json.

Signature

go
func (c *Composer) ValidateComposerLock() (string, error)

Parameters

None.

Return Values

ValueTypeDescription
OutputstringValidation output
ErrorerrorReturned when validation fails

Equivalent Command

composer validate --check-lock

Example

go
output, err := comp.ValidateComposerLock()
if err != nil {
    if strings.Contains(output, "not found") {
        fmt.Println("Missing composer.lock file")
    } else if strings.Contains(output, "not up to date") {
        fmt.Println("composer.lock needs updating, please run composer update")
    } else {
        log.Fatalf("Failed to validate composer.lock: %v", err)
    }
} else {
    fmt.Println("composer.lock is valid:", output)
}

Prohibit

✅ Show packages prohibited by the current platform requirements.

Signature

go
func (c *Composer) Prohibit() (string, error)

Parameters

None.

Return Values

ValueTypeDescription
OutputstringList of prohibited packages
ErrorerrorReturned when the query fails

Equivalent Command

composer prohibit

Example

go
output, err := comp.Prohibit()
if err != nil {
    log.Fatalf("Failed to query prohibited packages: %v", err)
}
fmt.Println("Prohibited packages:", output)

Advanced Variants

  • ProhibitWithFormat(format string) (string, error): equivalent to composer prohibit --format=format, where format can be text or json.
  • ProhibitWithOptions(options map[string]string) (string, error): custom option combination, e.g., specifying both format=json and fixed.
go
// JSON format + full path
options := map[string]string{
    "format": "json",
    "fixed":  "",
}
output, err := comp.ProhibitWithOptions(options)

CheckForSecurityVulnerabilities

✅ Check whether the project dependencies have known security vulnerabilities, returning an "output + whether there are vulnerabilities" triple.

Signature

go
func (c *Composer) CheckForSecurityVulnerabilities() (string, bool, error)

Parameters

None.

Return Values

ValueTypeDescription
OutputstringRaw output of composer audit
Has vulnerabilitiesbooltrue means vulnerabilities were detected
ErrorerrorReturned when an unexpected error occurs during the check

Implementation Notes

Runs composer audit. Composer returns a non-zero exit code when it finds vulnerabilities; this method analyzes the output: if it contains keywords like Found + vulnerability/vulnerabilities or Security vulnerability, it considers there to be vulnerabilities and returns (output, true, nil), not surfacing the exit code as an error. Other genuine execution errors are returned as error.

Example

go
output, hasVulnerabilities, err := comp.CheckForSecurityVulnerabilities()
if err != nil {
    log.Fatalf("Security check failed: %v", err)
}
if hasVulnerabilities {
    fmt.Println("Warning: security vulnerabilities found!")
    fmt.Println(output)
} else {
    fmt.Println("No security vulnerabilities found")
}

Difference from HasVulnerabilities

Security Audit - HasVulnerabilities returns (bool, error) and internally goes through the JSON parsing path for greater accuracy; this method returns the raw text output + a boolean, suitable for scenarios where you also need the output text for log archiving.


Advanced

ValidateStructured

Structured validation, returns *ValidateResult, making it easy to programmatically inspect errors and warnings.

go
func (c *Composer) ValidateStructured() (*ValidateResult, error)
ValueTypeDescription
Result*ValidateResultContains Valid/Errors/Warnings
ErrorerrorExecution error (note: a failed validation does not necessarily produce an error — check the Valid field)
go
result, err := comp.ValidateStructured()
if err != nil {
    log.Fatalf("Validation failed: %v", err)
}
if !result.Valid {
    for _, e := range result.Errors {
        fmt.Println("Error:", e)
    }
}
for _, w := range result.Warnings {
    fmt.Println("Warning:", w)
}

ValidateWithOptions

Combine multiple validation flags, equivalent to composer validate <flags>.

go
func (c *Composer) ValidateWithOptions(options map[string]string) (string, error)
go
// Strict validation and check dependencies
options := map[string]string{
    "strict":            "",
    "with-dependencies": "",
}
output, err := comp.ValidateWithOptions(options)

ParseValidateOutput

A pure function that parses any composer validate text output into *ValidateResult, useful for post-processing old output from caches or logs.

go
func ParseValidateOutput(output string) *ValidateResult
MethodEquivalent CommandDescription
ValidateWithNoCheckPublish()validate --no-check-publishDon't check fields required for publishing to Packagist
ValidateQuiet()validate --quietQuiet validation, only outputs on error
CheckNormalization()validate --no-check-all --check-normalizedCheck whether composer.json is canonically formatted
CheckPlatformReqsLock()check-platform-reqs --lockCheck platform requirements in composer.lock
CheckForOutdatedPackages(direct, minor, format)outdated [--direct] [--minor-only] [--format F]Check for outdated packages, see table below

CheckForOutdatedPackages Parameters

ParameterTypeDescription
directbooltrue to only check direct dependencies
minorbooltrue to only show minor updates
formatstringOutput format, e.g., text, json; empty string means unspecified
go
// Only check minor updates of direct dependencies, output as JSON
output, err := comp.CheckForOutdatedPackages(true, true, "json")
  • Security Audit: structured vulnerability analysis centered on audit.
  • Platform: CheckPlatformReqsStructured returns a structured check result of platform requirements.
  • Diagnosis & Health Check: HealthCheck internally calls ValidateStructured and writes the result to the Valid field.

Released under the MIT License