Skip to content

⚙️ Configuration

The Composer SDK's configuration module covers all capabilities of the composer config subcommand — validation, cache, config item read/write, source tracking, platform requirement checking, and structured config --list parsing. All methods are attached to the core type Composer, defined in pkg/composer/config.go.

Difference from composer.json File Operations

Methods on this page go through the composer config subcommand (which actually calls the composer binary and affects global/project configuration). If you just want pure file read/write of the config field or top-level properties in composer.json, see composer.json Operations (ReadComposerJSON, SetConfig, SetProperty, AddRequire, etc.).

Package path: github.com/scagogogo/composer-skills/pkg/composer

Capability Overview ⚙️

MethodPurposeReturn Value
ValidateValidate composer.jsonerror
GetComposerHomeGet Composer home directory(string, error)
ClearCacheClear Composer cacheerror
GetConfigWithGlobalRead config item, optional global(string, error)
SetConfigWithGlobalSet config item, optional globalerror
ListConfigList all config values(string, error)
ListConfigWithGlobalList global or project config(string, error)
GetConfigSourceQuery source file of config item(string, error)
CheckPlatformReqsCheck platform requirements(string, error)
ValidateComposerJsonValidate composer.json with optionserror
GetConfigStructuredList config and return as structured result(*ConfigResult, error)

⚙️ Validate

Validate composer.json, equivalent to composer validate.

When to Use

Use after writing or modifying composer.json, before committing code, to confirm the file structure and fields are valid.

Signature

go
func (c *Composer) Validate() error

Return Values

  • error: Error returned on validation failure.

Example

go
package main

import (
	"log"

	"github.com/scagogogo/composer-skills/pkg/composer"
)

func main() {
	comp, err := composer.New(composer.DefaultOptions())
	if err != nil {
		log.Fatalf("Failed to initialize Composer: %v", err)
	}

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

Advanced

For finer-grained validation, use ValidateComposerJson(strict, withDependencies), or refer to ValidateStrict, ValidateSchema, ValidateQuiet and other variants in the Validate module.


⚙️ GetComposerHome

Get Composer home directory, equivalent to composer config --global home.

When to Use

Use to locate Composer's global configuration file, global vendor directory, or auth.json.

Signature

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

Return Values

  • string: Composer home directory path (whitespace trimmed).
  • error: Error returned on failure.

Example

go
home, err := comp.GetComposerHome()
if err != nil {
	log.Fatalf("Failed to get Composer home directory: %v", err)
}
fmt.Printf("Composer home directory: %s\n", home)

Convenience Alias

GetComposerHomeDir in the Convenience module provides the same capability, plus GetCacheDir, GetVendorDir, GetBinDir and other directory location methods.


⚙️ ClearCache

Clear Composer cache, equivalent to composer clear-cache.

When to Use

Use when package downloads are corrupted, mirror sync is lagging, or disk space is tight.

Signature

go
func (c *Composer) ClearCache() error

Return Values

  • error: Error that occurred during clearing.

Example

go
if err := comp.ClearCache(); err != nil {
	log.Fatalf("Failed to clear cache: %v", err)
}
fmt.Println("Cache cleared")

⚙️ GetConfigWithGlobal

Get the value of a Composer config item, optionally reading global config, equivalent to composer config [--global] setting.

When to Use

Use when you need to read a config item (like process-timeout, preferred-install, bin-dir) in your program.

Signature

go
func (c *Composer) GetConfigWithGlobal(setting string, global bool) (string, error)

Parameters

ParameterTypeDescription
settingstringConfig item name, e.g., process-timeout
globalbooltrue reads global config, false reads project config

Return Values

  • string: Config item value (whitespace trimmed).
  • error: Error returned on failure.

Example

go
// Read project-level process-timeout
timeout, err := comp.GetConfigWithGlobal("process-timeout", false)
if err != nil {
	log.Fatalf("Failed to read config: %v", err)
}
fmt.Printf("process-timeout = %s\n", timeout)

// Read global bin-dir
binDir, err := comp.GetConfigWithGlobal("bin-dir", true)
if err != nil {
	log.Fatalf("Failed to read global config: %v", err)
}
fmt.Printf("global bin-dir = %s\n", binDir)

⚙️ SetConfigWithGlobal

Set the value of a Composer config item, optionally writing to global config, equivalent to composer config [--global] setting value.

When to Use

Use when you need to programmatically adjust a config item — for example, switching preferred-install to dist in CI, or setting global bin-dir when initializing a container.

Signature

go
func (c *Composer) SetConfigWithGlobal(setting string, value string, global bool) error

Parameters

ParameterTypeDescription
settingstringConfig item name
valuestringValue to set
globalbooltrue writes to global config, false writes to project config

Return Values

  • error: Error returned on failure.

Example

go
// Set preferred-install to dist globally
if err := comp.SetConfigWithGlobal("preferred-install", "dist", true); err != nil {
	log.Fatalf("Failed to set global config: %v", err)
}

// Set process-timeout at project level
if err := comp.SetConfigWithGlobal("process-timeout", "300", false); err != nil {
	log.Fatalf("Failed to set project config: %v", err)
}

Write Location

When global=false, the value is written to the config field of the current project's composer.json; when global=true, it's written to the global config.json. Ensure the Composer's working directory is correct.


⚙️ ListConfig

List all config values, equivalent to composer config --list.

When to Use

Use when you need to see all Composer config items and their values for the current project at once, commonly for debugging and diagnostics.

Signature

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

Return Values

  • string: List of all config values (raw output).
  • error: Error returned when listing config fails (wrapped as "failed to list config").

Example

go
output, err := comp.ListConfig()
if err != nil {
	log.Fatalf("Failed to list config: %v", err)
}
fmt.Println("Config list:")
fmt.Println(output)

Advanced

For structured results (split by Key/Value/Source), use GetConfigStructured; to distinguish global/project, use ListConfigWithGlobal.


⚙️ ListConfigWithGlobal

List all config values, optionally listing global or project config, equivalent to composer config --list [--global].

When to Use

Use when you need to view global and project-level config separately — for example, to troubleshoot which layer overrides a config item.

Signature

go
func (c *Composer) ListConfigWithGlobal(global bool) (string, error)

Parameters

ParameterTypeDescription
globalbooltrue lists global config, false lists project config

Return Values

  • string: Config value list.
  • error: Error returned when listing config fails.

Example

go
// List global config
globalCfg, err := comp.ListConfigWithGlobal(true)
if err != nil {
	log.Fatalf("Failed to list global config: %v", err)
}
fmt.Println("Global config:")
fmt.Println(globalCfg)

// List project config
projectCfg, err := comp.ListConfigWithGlobal(false)
if err != nil {
	log.Fatalf("Failed to list project config: %v", err)
}
fmt.Println("Project config:")
fmt.Println(projectCfg)

⚙️ GetConfigSource

Get source information for a specified config item, equivalent to composer config key --source.

When to Use

Use to debug config issues — it tells you whether a value was loaded from the project composer.json, global config.json, or a default.

Signature

go
func (c *Composer) GetConfigSource(key string) (string, error)

Parameters

ParameterTypeDescription
keystringConfig item name to query source for

Return Values

  • string: Source information for the config item (whitespace trimmed).
  • error: Error returned on failure (wrapped as "failed to get config source").

Example

go
source, err := comp.GetConfigSource("preferred-install")
if err != nil {
	log.Fatalf("Failed to get config source: %v", err)
}
fmt.Printf("Source of preferred-install: %s\n", source)

⚙️ CheckPlatformReqs

Check platform requirements, equivalent to composer check-platform-reqs.

When to Use

Use before deployment to confirm the current PHP version and extensions meet the platform requirements of the project (including dependencies).

Signature

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

Return Values

  • string: Raw output of platform requirement check.
  • error: Error returned on check failure.

Example

go
output, err := comp.CheckPlatformReqs()
if err != nil {
	log.Fatalf("Platform requirements check failed: %v", err)
}
fmt.Println(output)

Advanced

For structured results (each requirement's Package/Version/Status/Required), use CheckPlatformReqsStructured (defined in result_types.go, returns *PlatformCheckResult); for formatted output, see CheckPlatformReqsWithFormat (additional_methods.go).


⚙️ ValidateComposerJson

Validate composer.json with options, equivalent to composer validate [--strict] [--with-dependencies].

When to Use

Use when you need strict mode validation, or want to check dependencies' composer.json validity along with the project.

Signature

go
func (c *Composer) ValidateComposerJson(strict bool, withDependencies bool) error

Parameters

ParameterTypeDescription
strictbooltrue enables --strict strict mode
withDependenciesbooltrue checks dependencies' composer.json as well

Return Values

  • error: Error returned on validation failure.

Example

go
// Strict mode + check dependencies
if err := comp.ValidateComposerJson(true, true); err != nil {
	log.Fatalf("Validation failed: %v", err)
}
fmt.Println("composer.json and its dependencies all passed validation")

⚙️ GetConfigStructured

List config and return as structured result. Internally executes composer config --list and parses with ParseConfigList.

When to Use

Use when you need to iterate config items and process by Key/Value/Source in your program — for example, generating config reports or comparing differences between two environments.

Signature

go
func (c *Composer) GetConfigStructured() (*ConfigResult, error)

Return Values

  • *ConfigResult: Structured config result, Items is []ConfigItem.
  • error: Execution or parsing error.

Example

go
result, err := comp.GetConfigStructured()
if err != nil {
	log.Fatalf("Failed to get structured config: %v", err)
}
for _, item := range result.Items {
	fmt.Printf("%s = %s\n", item.Key, item.Value)
}

⚙️ ConfigItem / ConfigResult Types

Struct returned by GetConfigStructured, defined in pkg/composer/result_types.go.

go
type ConfigItem struct {
	Key    string `json:"key"`
	Value  string `json:"value"`
	Source string `json:"source,omitempty"`
}

type ConfigResult struct {
	Items []ConfigItem `json:"items,omitempty"`
}
TypeFieldDescription
ConfigItemKeyConfig item name
ConfigItemValueConfig item value
ConfigItemSourceSource information (may be empty)
ConfigResultItemsList of all config items

Parsing Logic

ParseConfigList splits the output of composer config --list by lines, and splits each line into Key and Value at the first space. Empty lines are skipped.


📄 Relationship with composer.json File Operations

The config module goes through the composer config subcommand, while the following methods (from composer_json.go) use pure file read/write; the two are complementary:

MethodSignaturePurpose
ReadComposerJSONfunc (c *Composer) ReadComposerJSON() (*ComposerJSON, error)Read and parse entire composer.json
WriteComposerJSONfunc (c *Composer) WriteComposerJSON(composerJSON *ComposerJSON) errorWrite struct back to composer.json
AddRequirefunc (c *Composer) AddRequire(packageName, version string, isDev bool) errorAppend dependency to require/require-dev
AddScriptfunc (c *Composer) AddScript(name string, script interface{}, description string) errorAdd script with optional description
AddAutoloadfunc (c *Composer) AddAutoload(type_ string, namespace string, paths interface{}, isDev bool) errorAdd autoload rule
SetConfigfunc (c *Composer) SetConfig(key string, value interface{}) errorSet composer.json's config field
GetConfigfunc (c *Composer) GetConfig(key string) (interface{}, error)Read composer.json's config field
SetPropertyfunc (c *Composer) SetProperty(property string, value interface{}) errorSet top-level property (name/description/type, etc.)

SetConfig vs SetConfigWithGlobal

  • SetConfig(key, value) (composer_json.go): Directly modifies the config field of the composer.json file, does not call composer, value can be any interface{} (number, boolean, object).
  • SetConfigWithGlobal(setting, value, global) (config.go, this page): Goes through the composer config command, value can only be string, can write globally.

Choose as needed: use the former for batch structured writes, use the latter for single command-style writes.

For full signatures, parameters, examples, and notes on the above methods, see composer.json Operations.


  • 📄 composer.json Operations: All methods for pure file read/write of composer.json.
  • Validate module: Finer-grained validation variants like ValidateStrict, ValidateSchema, ValidateComposerLock.
  • 🧱 Platform module: Platform check capabilities like CheckPlatform, GetPHPVersion, HasExtension.
  • 🏗️ Repository module: Methods that modify repository and stability related config via composer config, like SetPreferredInstall, SetMinimumStability, SetPreferStable.

Released under the MIT License