celestifyx/stellaris

A powerful, elegant, and extensible configuration management library for PHP.

Maintainers

👁 celestifyx

Package info

gitlab.com/celestifyx/stellaris

Issues

pkg:composer/celestifyx/stellaris

Statistics

Installs: 53

Dependents: 1

Suggesters: 0

Stars: 1

1.0.5 2025-09-06 16:23 UTC

Requires

Requires (Dev)

None

Suggests

None

Provides

None

Conflicts

None

Replaces

None

GPL-3.0-or-later d2c5bc7b6061a80d553c2f095438e7e52eb17f85

  • CELESTIFYX Team <celestifyx.woop@gmail.com>

yamlphpjsonxmlconfigurationiniconfiglistpropertiesdotenvtomlserializedtxthjsonJSON5stellarisjsonc

This package is not auto-updated.

Last update: 2026-06-16 22:04:06 UTC


README

👁 PHP Version
👁 License: GPL v3 or later
👁 Packagist version
👁 Downloads

A powerful, elegant, and extensible configuration management library for PHP that supports multiple formats, advanced caching, comprehensive validation, and enterprise-grade features.

Table of Contents

✨ Features

🚀 Multi-Format Support

  • JSON - Perfect for structured data and APIs
  • YAML - Human-readable with comments and advanced features
  • XML - Hierarchical data with attributes and namespaces
  • INI - Simple key-value pairs with sections
  • PHP - Native PHP arrays with full language support
  • TOML - Modern configuration format
  • Properties – Java-style key-value format
  • Dotenv - Environment variable files
  • Serialized - PHP serialized data format
  • Hjson - Human-friendly JSON format with optional comments and relaxed syntax
  • Json5 - Extended JSON format with comments, trailing commas, and more relaxed syntax
  • TXT/List - Plain text lists, one item per line
  • JSONC - JSON with Comments

💾 Advanced Caching System

  • Memory Cache - Lightning-fast in-memory storage
  • File Cache - Persistent file-based caching
  • Null Cache - No-op cache for development

Comprehensive Validation

  • Type Validation - Ensure correct data types
  • Range Validation - Numeric min/max constraints
  • Email Validation - RFC-compliant email format checking
  • URL Validation - Valid URL format with scheme restrictions
  • Custom Validators - Extensible validation system
  • Pattern Matching - Wildcard pattern support for bulk validation

🔄 Auto-Reload & File Watching

  • File Monitoring - Automatic detection of configuration changes
  • Hot Reload - Live configuration updates without restart
  • Change Callbacks - Custom handlers for configuration updates
  • Diff Tracking - Track what changed between configurations

📊 Configuration Management

  • Dot Notation - Access nested values with simple syntax (app.database.host)
  • Array Access - Use configuration like native PHP arrays
  • Typed Access - Get values with automatic type casting
  • Metadata Support - Attach metadata to configuration keys
  • Merge Strategies - Combine multiple configurations intelligently

🔒 Enterprise Features

  • Type Safety - Strong typing with PHP 8.5+ features
  • PSR-3 Logging - Compatible with any PSR-3 logger
  • Exception Handling - Detailed error reporting with context
  • Memory Efficient - Optimized for large configurations
  • Thread Safe - Safe for concurrent access

🧩 Extensibility

  • Custom Readers - Add support for new configuration formats
  • Custom Caches - Implement your own caching mechanisms
  • Configuration Locking - Prevent accidental modifications with flexible locking mechanisms

📦 Installation

composer require celestifyx/stellaris

⚙️ Framework Integration

Stellaris is framework-agnostic and works seamlessly with any PHP project — Laravel, Symfony, Slim, Yii, or custom code.

🚀 Quick Start

<?php

use Stellaris\ConfigManager;
use Stellaris\Cache\MemoryCache;
use Stellaris\Exception\InvalidArgumentException;
use Stellaris\Exception\RuntimeException;
use Stellaris\Exception\ValidationException;
use Stellaris\Exception\ConfigLockException;

// Create configuration manager with caching
$config = new ConfigManager(cache: new MemoryCache());

// Load configuration from file
try {
 $config->load('config/app.json');
} catch (InvalidArgumentException|RuntimeException $e) {
 echo "Failed to load configuration: " . $e->getMessage();
}

// Set values with dot notation
try {
 $config->set('app.name', 'My Application');
 $config->set('database.host', 'localhost');
} catch (InvalidArgumentException|RuntimeException|ValidationException|ConfigLockException $e) {
 echo "Failed to set configuration: " . $e->getMessage();
}

// Get values with defaults
$appName = $config->get('app.name');
$dbHost = $config->get('database.host', 'localhost');

// Use array access
$config['api.key'] = 'secret-key';
$apiKey = $config['api.key'];

// Lock configuration to prevent modifications
try {
 $config->lock();
 $config->set('app.name', 'New Name'); // This would throw ConfigLockException
} catch (ConfigLockException $e) {
 echo "Configuration is locked: " . $e->getMessage();
}

// Unlock configuration
$config->unlock();

// Save configuration
try {
 $config->save();
} catch (InvalidArgumentException|RuntimeException $e) {
 echo "Failed to save configuration: " . $e->getMessage();
}

📖 Comprehensive Documentation

Loading Configuration

From Files

// Single file
$config->load('config/app.json');

// Single file with explicit formats
$config->load('config/.env.local', format: ConfigFormat::ENV);

// Multiple files (merged in order)
$config->load([
 'config/app.json',
 'config/database.yaml',
 'config/cache.ini',
 'config/services.xml',
 'config/features.php'
]);

// Load multiple files with explicit formats
$config->load([
 ['path' => 'config/app.json', 'format' => ConfigFormat::JSON],
 ['path' => 'config/database.yaml', 'format' => ConfigFormat::YAML],
 ['path' => 'config/.env.local', 'format' => ConfigFormat::ENV],
 ['path' => 'config/cache.data', 'format' => ConfigFormat::SERIALIZED],
 'config/services.xml'
]);

From String Content

use Stellaris\Enum\ConfigFormat;

// YAML from string
$yamlString = "
app:
 name: My App
 debug: true

 features:
 - authentication
 - caching
 - logging
";

$config->loadFromString($yamlString, ConfigFormat::YAML);

// JSON from string
$jsonString = '{"api": {"version": "v2", "timeout": 30}}';
$config->loadFromString($jsonString, ConfigFormat::JSON);

Advanced Configuration Access

Dot Notation

// Set nested values
$config->set('app.database.connections.mysql.host', 'localhost');
$config->set('app.database.connections.mysql.port', 3306);

// Get nested values
$host = $config->get('app.database.connections.mysql.host');
$port = $config->get('app.database.connections.mysql.port', 3306);

// Check if nested key exists
if ($config->has('app.database.connections.redis')) echo "Redis configuration exists";

Typed Access

// Get values with automatic type casting
$port = $config->getTyped('database.port', 'int'); // Always returns int
$timeout = $config->getTyped('api.timeout', 'float'); // Always returns float
$enabled = $config->getTyped('features.cache', 'bool'); // Always returns bool
$hosts = $config->getTyped('database.hosts', 'array'); // Always returns array

// Supported types: string, int, integer, float, double, bool, boolean, array

Array Access Interface

// Use configuration like a native PHP array
$config['app']['name'] = 'My Application';
$config['database']['host'] = 'localhost';

// Check existence
if (isset($config['app']['debug'])) $debug = $config['app']['debug'];

// Iterate over configuration
foreach ($config as $key => $value) echo $key . ": " . json_encode($value) . PHP_EOL;

Validation System

Built-in Validators

use Stellaris\Validator\TypeValidator;
use Stellaris\Validator\RangeValidator;
use Stellaris\Validator\EmailValidator;
use Stellaris\Validator\UrlValidator;

// Type validation
$config->addValidator('app.name', new TypeValidator('string'));
$config->addValidator('app.port', new TypeValidator('int'));
$config->addValidator('app.debug', new TypeValidator('bool'));

// Range validation for numbers
$config->addValidator('app.port', new RangeValidator(1000, 65535));
$config->addValidator('cache.ttl', new RangeValidator(60, 86400));

// Email validation
$config->addValidator('mail.from', new EmailValidator());

// URL validation
$config->addValidator('api.webhook_url', new UrlValidator(['https']));

// Pattern matching (wildcards)
$config->addValidator('database.*', new TypeValidator('string'));
$config->addValidator('cache.stores.*.ttl', new RangeValidator(0, 86400));

Custom Validators

use Stellaris\Validator\ValidatorInterface;

class DatabaseNameValidator implements ValidatorInterface {
 private string $errorMessage = '';

 /**
 * @param mixed $value
 *
 * @return bool
 */
 function validate(mixed $value): bool {
 if (!is_string($value)) {
 $this->errorMessage = 'Database name must be a string';
 return false;
 }

 if (!preg_match('/^[a-zA-Z][a-zA-Z0-9_]*$/', $value)) {
 $this->errorMessage = 'Database name must start with letter and contain only letters, numbers, and underscores';
 return false;
 }

 return true;
 }

 /**
 * @return string
 */
 function getName(): string {
 return 'database_name';
 }

 /**
 * @return array
 */
 function getOptions(): array {
 return [];
 }
}

$config->addValidator('database.name', new DatabaseNameValidator());

Validation Execution

try {
 // Validate entire configuration
 $config->validate();
 echo "Configuration is valid!";
} catch (ValidationException $e) {
 echo "Validation failed: " . $e->getMessage() . PHP_EOL;

 // Get detailed violations
 foreach ($e->getViolations() as $field => $message) echo " " . $field . ": " . $message . PHP_EOL;
}

Caching System

Memory Cache

use Stellaris\Cache\MemoryCache;

$config = new ConfigManager(cache: new MemoryCache());

// Get cache statistics
$cache = $config->getCache();

if ($cache instanceof MemoryCache) {
 $stats = $cache->getStats();

 echo "Cache hits: " . $stats['total_keys'] . PHP_EOL;
 echo "Memory usage: " . ($stats['memory_usage'] / 1024 / 1024) . " MB\n";
}

File Cache

use Stellaris\Cache\FileCache;

$config = new ConfigManager(cache: new FileCache('/tmp/config_cache'));

Custom Cache Implementation

use Stellaris\Cache\CacheInterface;

use Redis;

class RedisCache implements CacheInterface {
 private Redis $redis;

 /**
 * @param Redis $redisClient
 *
 * @return void
 */
 function __construct(Redis $redisClient) {
 $this->redis = $redisClient;
 }

 /**
 * @param string $key
 * @param mixed|null $default
 *
 * @return mixed
 */
 function get(string $key, mixed $default = null): mixed {
 $value = $this->redis->get($key);
 return (($value !== false) ? unserialize($value) : $default);
 }

 /**
 * @param string $key
 * @param mixed $value
 * @param int $ttl
 *
 * @return bool
 */
 function set(string $key, mixed $value, int $ttl = 0): bool {
 return $this->redis->setex($key, ($ttl ?: 3600), serialize($value));
 }

 // ... implement other methods
}

$config = new ConfigManager(cache: new RedisCache($redisClient));

File Watching

// Watch single file for changes
$config->watch('config/app.json', function (string $path) {
 echo "Configuration file " . $path . " changed!";
 // Custom reload logic here
});

// Watch multiple files
$config->watch('config/database.yaml');
$config->watch('config/cache.ini');

// Check for changes manually
if ($config->checkForChanges()) echo "Configuration updated!";

Auto-save Configuration

use Stellaris\Exception\AutoSaveException;

// Enable auto-save (saves immediately on changes)
try {
 $config->enableAutoSave();
 $config->set('app.version', '2.0.0'); // Automatically saved
} catch (AutoSaveException $e) {
 echo "Enable auto-save failed: " . $e->getMessage();
}

// Disable auto-save
try {
 $config->disableAutoSave();
} catch (AutoSaveException $e) {
 echo "Disable auto-save failed: " . $e->getMessage();
}

// Check auto-save enabled
if ($config->isAutoSaveEnabled()) echo "Auto-save is enabled\n";

Configuration Export & Import

use Stellaris\Enum\ConfigFormat;

// Export to different formats
$json = $config->export(ConfigFormat::JSON);
$yaml = $config->export(ConfigFormat::YAML);
$xml = $config->export(ConfigFormat::XML);
$ini = $config->export(ConfigFormat::INI);
$php = $config->export(ConfigFormat::PHP);

// Save exported configuration
file_put_contents('backup/config.yaml', $yaml);

// Get configuration diff
$diff = $config->getDiff();

if (!empty($diff)) {
 echo "Changes detected:\n";
 foreach ($diff as $key => $change) echo " " . $key . ": " . $change['action'] . PHP_EOL;
}

Metadata Management

// Set metadata for configuration keys
$config->setMetadata('database.password', [
 'sensitive' => true,
 'description' => 'Database password - handle with care',
 'last_updated' => date('Y-m-d H:i:s'),
 'updated_by' => 'admin',
 'validation_rules' => ['required', 'min:8']
]);

// Get metadata
$metadata = $config->getMetadata('database.password');

if ($metadata['sensitive']) {
 // Handle sensitive data appropriately
}

// Get all metadata
$allMetadata = $config->getMetadata();

Advanced Features

Configuration Merging

// Merge additional configuration
$config->merge([
 'new_feature' => [
 'enabled' => true,
 'settings' => ['option1' => 'value1']
 ]
]);

// Merge without recursion (replace arrays entirely)
$config->merge($newConfig, false);

Configuration Reset & Reload

// Reset to original state
$config->reset();

// Reload from files
$config->reload();

// Clear all configuration
$config->clear();

Iterator Support

// Iterate over all configuration
foreach ($config as $key => $value) echo $key . ": " . json_encode($value) . PHP_EOL;

// Count configuration keys
echo "Total keys: " . count($config) . PHP_EOL;

// Check if empty
if ($config->isEmpty()) echo "No configuration loaded\n";

Configuration Locking

use Stellaris\Exception\ConfigLockException;

// Lock configuration permanently
try {
 $config->lock();
 echo "Configuration is now locked\n";
} catch (ConfigLockException $e) {
 echo "Failed to lock: " . $e->getMessage() . PHP_EOL;
}

// Lock configuration for specific time (in seconds)
try {
 $config->lockFor(3600); // Lock for 1 hour
 echo "Configuration locked for 1 hour\n";
} catch (ConfigLockException $e) {
 echo "Failed to lock: " . $e->getMessage() . PHP_EOL;
}

// Check if configuration is locked
if ($config->isLocked()) echo "Configuration is currently locked\n";

// Try to modify locked configuration
try {
 $config->set('app.name', 'New Name');
} catch (ConfigLockException $e) {
 echo "Cannot modify: " . $e->getMessage() . PHP_EOL;
}

// Unlock configuration
try {
 $config->unlock();
 echo "Configuration is now unlocked\n";
} catch (ConfigLockException $e) {
 echo "Failed to unlock: " . $e->getMessage() . PHP_EOL;
}

// Special cases for lockFor():
$config->lockFor(0); // Does not lock (0 seconds)
$config->lockFor(-1); // Does not lock (negative time)
$config->lockFor(PHP_INT_MAX); // Locks normally
$config->lockFor(PHP_INT_MAX + 1); // Does not lock (would overflow to float)

🎯 Format-Specific Examples

JSON Configuration

{
 "app": {
 "name": "My Application",
 "version": "1.0.0",
 "debug": true
 },

 "database": {
 "default": "mysql",

 "connections": {
 "mysql": {
 "host": "localhost",
 "port": 3306,
 "database": "myapp"
 }
 }
 },

 "features": ["auth", "cache", "logging"]
}

YAML Configuration

# Application configuration
app:
 name: My Application
 version: 1.0.0
 debug: true

# Database with multiple connections
database:
 default: mysql

 connections:
 mysql:
 host: localhost
 port: 3306
 database: myapp

# Features array
features:
 - auth
 - cache
 - logging

XML Configuration

<?xml version="1.0" encoding="UTF-8" ?>

<config>
 <!-- Application configuration -->
 <app>
 <name>My Application</name>
 <version>1.0.0</version>
 <debug>true</debug>
 </app>

 <!-- Database configuration -->
 <database default="mysql">
 <connections>
 <mysql>
 <host>localhost</host>
 <port>3306</port>
 <database>myapp</database>
 </mysql>
 </connections>
 </database>

 <!-- Features array -->
 <features>
 <feature>auth</feature>
 <feature>cache</feature>
 <feature>logging</feature>
 </features>
</config>

INI Configuration

; Application configuration
[app]
name = "My Application"
version = 1.0.0
debug = true

; Database configuration
[database]
default = mysql

[database.mysql]
host = localhost
port = 3306
database = myapp

; Features array (using indexed notation)
[features]
0 = auth
1 = cache
2 = logging

PHP Configuration

<?php

return [
 // Application configuration
 'app' => [
 'name' => 'My Application',
 'version' => '1.0.0',
 'debug' => env('APP_DEBUG', true)
 ],

 // Database configuration
 'database' => [
 'default' => 'mysql',

 'connections' => [
 'mysql' => [
 'host' => env('DB_HOST', 'localhost'),
 'port' => env('DB_PORT', 3306),
 'database' => env('DB_DATABASE', 'myapp')
 ]
 ]
 ],

 // Features array
 'features' => ['auth', 'cache', 'logging']
];

/**
 * @param string $key
 * @param mixed|null $default
 *
 * @return mixed
 */
function env(string $key, mixed $default = null): mixed {
 return ($_ENV[$key] ?? $default);
}

TOML Configuration

# Application configuration
[app]
name = "My Application"
version = "1.0.0"
debug = true

# Database configuration
[database]
default = "mysql"

[database.mysql]
host = "localhost"
port = 3306
database = "myapp"

# Features array
features = ["auth", "cache", "logging"]

Properties Configuration

# Application configuration
app.name=My Application
app.version=1.0.0
app.debug=true

# Database configuration
database.default=mysql
database.mysql.host=localhost
database.mysql.port=3306
database.mysql.database=myapp

# Features array (comma-separated)
features=auth,cache,logging

Dotenv Configuration

# Application configuration
APP_NAME="My Application"
APP_VERSION=1.0.0
APP_DEBUG=true

# Database configuration
DATABASE_DEFAULT=mysql
DATABASE_MYSQL_HOST=localhost
DATABASE_MYSQL_PORT=3306
DATABASE_MYSQL_DATABASE=myapp

# Features array
FEATURES=auth,cache,logging

Serialized Configuration

a:3:{s:3:"app";a:3:{s:4:"name";s:14:"My Application";s:7:"version";s:5:"1.0.0";s:5:"debug";b:1;}s:8:"database";a:2:{s:7:"default";s:5:"mysql";s:11:"connections";a:1:{s:5:"mysql";a:3:{s:4:"host";s:9:"localhost";s:4:"port";i:3306;s:8:"database";s:5:"myapp";}}}s:8:"features";a:3:{i:0;s:4:"auth";i:1;s:5:"cache";i:2;s:7:"logging";}}

Hjson Configuration

// Application configuration
app: {
 name: My Application
 version: 1.0.0
 debug: true
}

// Database configuration
database: {
 default: mysql

 connections: {
 mysql: {
 host: localhost
 port: 3306
 database: myapp
 }
 }
}

// Features array
features: [
 auth
 cache
 logging
]

Json5 Configuration

{
 // Application configuration
 app: {
 name: "My Application",
 version: "1.0.0",
 debug: true
 },

 // Database configuration
 database: {
 default: "mysql",

 connections: {
 mysql: {
 host: "localhost",
 port: 3306,
 database: "myapp"
 }
 }
 },

 // Features array
 features: [
 "auth",
 "cache",
 "logging"
 ]
}

JSONC Configuration

{
 // Application configuration
 "app": {
 "name": "My Application",
 "version": "1.0.0",
 "debug": true
 },

 // Database configuration
 "database": {
 "default": "mysql",

 "connections": {
 "mysql": {
 "host": "localhost",
 "port": 3306,
 "database": "myapp"
 }
 }
 },

 // Features array
 "features": ["auth", "cache", "logging"]
}

📋 Requirements

  • PHP 8.5+ - Modern PHP with strong typing support
  • ext-json - JSON processing (usually included)
  • ext-simplexml - XML processing (usually included)
  • ext-dom - XML DOM manipulation (usually included)
  • ext-libxml - Core XML library used by DOM and SimpleXML
  • ext-mbstring - Multibyte string support for handling UTF-8 and non-ASCII characters
  • symfony/yaml - Loads and dumps YAML files
  • psr/cache - Common interface for caching libraries
  • psr/log - Common interface for logging libraries
  • yosymfony/toml - A PHP parser for TOML compatible with specification 0.4.0
  • laktak/hjson - JSON for Humans. A configuration file format with relaxed syntax, fewer mistakes and more comments.
  • colinodell/json5 - UTF-8 compatible JSON5 parser for PHP

📄 License

This project is licensed under the GNU General Public License v3.0 or later - see the LICENSE file for details.

🌟 Why Choose Stellaris?

🚀 Performance

  • Optimized for speed with intelligent caching
  • Memory-efficient handling of large configurations
  • Lazy loading and on-demand parsing

🛡️ Reliability

  • Comprehensive test suite with 100% coverage
  • Battle-tested in production environments
  • Robust error handling and recovery
  • Configuration locking to prevent accidental modifications

🔧 Flexibility

  • Support for 13 different configuration formats
  • Extensible architecture for custom needs
  • Framework-agnostic design
  • Flexible locking mechanisms for different use cases

📚 Developer Experience

  • Intuitive API with excellent IDE support
  • Comprehensive documentation with examples
  • Strong typing for better code quality
  • Clear error messages and exception handling

🏢 Enterprise Ready

  • Validation and security features
  • Monitoring and debugging capabilities
  • Scalable architecture for large applications
  • Configuration locking for production safety

Stellaris - A powerful, elegant, and extensible configuration management library for PHP. ⭐

Built with ❤️ by the CELESTIFYX Team