diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..6a6dea2 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,101 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +This is `encoredigitalgroup/stdlib`, a collection of standard library classes and functions for PHP at Encore Digital Group. It provides utilities, helpers, and +standardized patterns for PHP development. + +## Coding Rules + +Always follow these rules when writing code: + +- Casing rules: + - Variables are always camelCase + - Functions are always camelCase + - Paths are always PascalCase + - Classes are always PascalCase +- Comments and docblocks: + - Only add comments when they add real value. Comments should always describe *why* not *what* + - Only add minimal docblocks to help improve code intelligence and static analysis +- Never use `private`, `final`, or `readonly` keywords. If they are needed, the developer will implement them. +- Avoid magic strings when an enum or a const is an option. Look in the existing codebase for an enum—it'll often be there +- Avoid variables if possible. eg. rather than calling `$response = $this->get(...)` followed by `assetsRedirect()`, just chain the calls +- Use the early return pattern where possible +- Prefer arrow functions when the line will stay under 80-100 chars +- Testing: + - All tests should be written using PestPHP. Related tests should be grouped by `describe()` blocks. + - All tests should be written using the `test()` function instead of the `it()` function. + - Avoid tests that are largely testing that the code behaves specifically as it is written, and instead test the intention. eg. a validation message may change over + time, but the invalid input should not be allowed regardless. + - When calling eloquent factories: + - Prefer named factory methods over `state` or passing values to `create` where possible + - Only factory data that is relevant to the test--favor defaults otherwise + - Eloquent factories should create necessary relationships implicitly. If you don't need a relation for the test, let the factory create it rather than creating + it in the test. +- Always run `composer format`, `composer analyse`, and `composer test` on your code before considering it done +- If there are "todo" comments that need to be resolved before the code gets merged, use `// FIXME` + +## Development Commands + +### Testing + +- Run all tests: `vendor/bin/pest` +- Composer Command: `composer test` +- Tests are located in `tests/` directory using Pest testing framework + +### Code Quality & Analysis + +- Static analysis: `composer analyse` +- Code formatting: `composer format` + +## Architecture & Code Structure + +### Core Namespacing + +All classes use the `EncoreDigitalGroup\StdLib` namespace with PSR-4 autoloading from the `src/` directory. + +### Key Directories + +- `src/Objects/` - Main utility classes organized by domain: + - `Support/Types/` - Enhanced type classes (Str, Arr, Number) + - `Http/` - HTTP-related utilities (Url, HttpMethod, HttpStatusCode) + - `Filesystem/` - File and directory utilities + - `Geography/` - Geographic data structures + - `Serializers/` - JSON/XML serialization with normalizers + - `Calendar/` - Date/time utilities +- `src/ObjectHelpers/` - Functional helper files automatically loaded +- `src/Exceptions/` - Custom exception hierarchy +- `src/Attributes/` - Custom PHP attributes (Api, Deprecated, Internal) +- `src/Support/Internal/` - Internal support classes and composer scripts + +### Helper Functions + +Global helper functions are auto-loaded from files in `src/ObjectHelpers/`: + +- `enum_helpers.php` +- `file_helpers.php` +- `php_function_helpers.php` +- `str_helpers.php` +- `url_helpers.php` +- `val_helpers.php` + +### Dependency Strategy + +- Uses Laravel collections and support packages (`illuminate/collections`, `illuminate/support`) +- Supports multiple Laravel versions (^10|^11|^12) +- Wrapper classes like `Once` check minimum dependency versions at runtime + +### Code Style Standards + +- Uses custom PHP-CS-Fixer rules with specific class element ordering +- PHPStan level 8 static analysis +- Cognitive complexity limits: 50 for classes, 10 for functions +- Excludes Attributes, ObjectHelpers, and Exceptions from coverage analysis + +### Testing Approach + +- Pest framework for unit tests +- Test files in `tests/Unit/` directory +- Some wrapper classes marked with `@codeCoverageIgnore` \ No newline at end of file diff --git a/composer.json b/composer.json index e540240..8c36b64 100644 --- a/composer.json +++ b/composer.json @@ -47,7 +47,10 @@ "scripts": { "post-autoload-dump": [ "EncoreDigitalGroup\\StdLib\\Support\\Internal\\Composer\\Scripts::postAutoloadDump" - ] + ], + "format": "vendor/bin/rector && vendor/bin/duster fix", + "analyse": "vendor/bin/phpstan analyse", + "test": "vendor/bin/pest" }, "minimum-stability": "stable" } diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..8638c82 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,173 @@ +# EncoreDigitalGroup/StdLib Documentation + +Welcome to the comprehensive developer documentation for EncoreDigitalGroup/StdLib, a collection of standardized PHP classes and utilities designed to enhance development +productivity and ensure consistency across projects. + +## Overview + +The stdlib provides object-oriented utilities that extend and enhance common PHP operations, with a focus on type safety, performance, and developer experience. All +classes are designed to integrate seamlessly with Laravel applications while remaining framework-agnostic where possible. + +## Documentation Structure + +### [Support/Types Classes](./support-types.md) + +Enhanced type utility classes that extend Laravel's base functionality: + +- **Str** - Advanced string manipulation and formatting +- **Arr** - Sophisticated array operations with structure preservation +- **Number** - Safe number operations with validation + +### [HTTP Classes](./http.md) + +HTTP-related utilities and constants for web applications: + +- **Url** - Safe URL encoding/decoding operations +- **HttpMethod** - Type-safe HTTP method constants +- **HttpStatusCode** - Comprehensive HTTP status code constants +- **HttpStatusName** - Human-readable status descriptions + +### [Filesystem Classes](./filesystem.md) + +File and directory operations with robust error handling: + +- **File** - Safe file operations with proper validation +- **Directory** - Advanced directory analysis and scanning +- **ExitCode** - Standardized CLI application exit codes + +### [Geography Classes](./geography.md) + +Comprehensive geographic data structures and utilities: + +- **Country** - World countries enumeration with enhanced functionality +- **DivisionType** - Political division types (states, provinces, regions) +- **Canada/UnitedStates** - Specific country subdivision enums with abbreviations + +### [Serializers Classes](./serializers.md) + +Object serialization system built on Symfony components: + +- **AbstractSerializer** - Base serialization functionality with normalizer management +- **JsonSerializer/XmlSerializer** - Format-specific serialization implementations +- **CarbonNormalizer** - Specialized Carbon date object handling +- **LaravelCollectionNormalizer** - Laravel Collection serialization support + +### [Calendar Classes](./calendar.md) + +Date and time utilities with type-safe operations: + +- **DayOfWeek** - Type-safe day representation with flexible conversion +- **Month** - Month enumeration with navigation capabilities + +### [Core Objects and Utilities](./core-objects.md) + +Foundational classes providing system-wide functionality: + +- **Once** - Memoization wrapper with version checking +- **Deferred** - Deferred execution capabilities +- **Enum** - Safe enum value extraction utilities +- **StaticCache** - Advanced static caching with partitioning +- **Php** - PHP version detection and comparison +- **Support Traits** - Reusable functionality enhancements + +## Key Features + +### Type Safety + +- Extensive use of PHP 8.1+ enums and type declarations +- Safe conversion methods that validate input types +- Clear exception handling with meaningful error messages +- IDE-friendly interfaces with comprehensive autocompletion + +### Laravel Integration + +- Seamless compatibility with Laravel applications +- Extensions of familiar Laravel classes (Str, Arr, Number) +- Support for Laravel Collections and Carbon dates +- Integration with Laravel's service container and facades + +### Performance Optimization + +- Static caching capabilities for expensive operations +- Memory-efficient operations on large datasets +- Optimized algorithms for common operations +- Minimal overhead wrapper implementations + +### Developer Experience + +- Consistent API patterns across all classes +- Comprehensive error handling and validation +- Clear documentation and usage examples +- IDE autocompletion and static analysis support + +## Architecture Principles + +### Inheritance Strategy + +Many stdlib classes extend their Laravel counterparts, providing: + +- All existing Laravel functionality +- Additional stdlib-specific methods +- Seamless integration with existing code +- Drop-in replacement capability + +### Error Handling + +Robust error handling throughout the system: + +- Custom exceptions for specific error types +- Meaningful error messages with context +- Validation before potentially failing operations +- Safe defaults and fallback behavior + +### Version Safety + +- Automatic dependency version checking +- Clear error messages for version mismatches +- Graceful degradation where possible +- Consistent version requirement handling + +## Getting Started + +### Installation + +The stdlib is designed to be included as a Composer dependency in your PHP projects. + +### Basic Usage Patterns + +1. **Type-Safe Operations** - Use enum-based constants instead of magic strings/numbers +2. **Enhanced Laravel Methods** - Leverage stdlib extensions of Laravel classes +3. **Geographic Data** - Utilize comprehensive country and region enumerations +4. **Serialization** - Implement robust object serialization with custom normalizers +5. **Caching** - Optimize performance with static caching capabilities + +### Integration Guidelines + +- Follow existing patterns when extending stdlib functionality +- Use provided traits to enhance custom classes +- Leverage type-safe enums for constants and options +- Implement proper error handling using stdlib exceptions + +## Support and Development + +### Testing + +All stdlib classes are thoroughly tested using PestPHP with comprehensive test coverage. + +### Code Quality + +The codebase maintains high quality standards through: + +- PHPStan level 8 static analysis +- Custom PHP-CS-Fixer rules for consistent formatting +- Rector for code modernization and refactoring +- Comprehensive documentation for all public APIs + +### Contributing + +When contributing to the stdlib, follow the established patterns and maintain consistency with existing implementations. + +--- + +*This documentation provides comprehensive coverage of all object classes in the EncoreDigitalGroup/StdLib package. For specific implementation details, refer to the +individual class documentation files.* \ No newline at end of file diff --git a/docs/calendar.md b/docs/calendar.md new file mode 100644 index 0000000..1f42d4e --- /dev/null +++ b/docs/calendar.md @@ -0,0 +1,209 @@ +# Calendar Classes + +The Calendar namespace provides date and time utilities with focus on days of the week and month operations, offering type-safe alternatives to numeric date handling. + +## DayOfWeek Enum + +The `DayOfWeek` enum provides a type-safe representation of days of the week with conversion utilities. + +### Purpose + +Eliminates magic numbers in date calculations and provides consistent day-of-week handling with flexible integer conversion options. + +### Available Days + +- `Sunday` through `Saturday` - Complete week coverage with string-backed enum values + +### Key Methods + +#### Integer Conversion + +- `toInt(bool $zero = true)` - Converts day to integer representation + - When `$zero = true` (default): Sunday = 0, Monday = 1, ... Saturday = 6 + - When `$zero = false`: Sunday = 1, Monday = 2, ... Saturday = 7 + +### Usage Scenarios + +- Calendar application development +- Date calculation and manipulation +- Scheduling system implementation +- Business hour calculations +- Weekly recurring event handling +- Date validation and formatting + +### Conversion Flexibility + +The dual conversion system accommodates different standards: + +#### Zero-Based (Default) + +- Compatible with PHP's `date('w')` function +- Common in programming contexts +- JavaScript Date.getDay() compatible + +#### One-Based + +- Compatible with ISO 8601 standard (where Monday = 1) +- Database systems that use 1-7 for days +- Some international date standards + +### Integration Benefits + +- Type-safe day comparisons +- IDE autocompletion for days +- Prevention of invalid day values +- Clear code intention + +## Month Enum + +The `Month` enum provides comprehensive month handling with navigation capabilities and integer conversion. + +### Purpose + +Type-safe month operations with built-in navigation methods, eliminating the complexity of month calculations and wraparound handling. + +### Available Months + +- `January` through `December` - Complete year coverage with string-backed enum values + +### Key Methods + +#### Integer Conversion + +- `toInt()` - Returns the month number (1-12) following standard calendar numbering + +#### Month Navigation + +- `next()` - Returns the next month with automatic year wraparound (December → January) +- `previous()` - Returns the previous month with automatic year wraparound (January → December) + +### Usage Scenarios + +- Calendar navigation interfaces +- Date range calculations +- Monthly report generation +- Billing cycle management +- Seasonal calculation systems +- Financial period handling + +### Navigation Features + +#### Automatic Wraparound + +The navigation methods handle year boundaries automatically: + +- `December.next()` returns `January` +- `January.previous()` returns `December` +- No need for manual boundary checking +- Consistent behavior across all months + +#### Chain Operations + +Navigation methods can be chained for complex calculations: + +- Multiple month advancement/retreat +- Seasonal calculations +- Quarter navigation +- Period-based operations + +### Calendar Integration + +The month enum integrates seamlessly with: + +- PHP's built-in date functions +- Calendar libraries +- Date calculation utilities +- Database date operations + +### Type Safety Benefits + +- Eliminates magic numbers (1-12) +- Prevents invalid month values +- Clear method intentions +- Compile-time validation + +## Common Patterns + +### Enum-Based Date Handling + +Both calendar enums follow consistent patterns: + +#### String-Backed Design + +- Human-readable enum values +- Easy debugging and logging +- Clear code intention +- Database storage friendly + +#### Integer Conversion + +- Consistent `toInt()` methods +- Standard calendar numbering +- Database compatibility +- Calculation support + +### Navigation Consistency + +Calendar enums provide consistent navigation patterns: + +- Automatic boundary handling +- Predictable wraparound behavior +- Method chaining support +- No special case handling required + +### Integration Strategy + +#### PHP Date Functions + +Calendar enums work seamlessly with PHP's date functions: + +- Compatible with `mktime()` parameters +- Works with `DateTime` objects +- Integrates with `date()` formatting +- Supports `strtotime()` operations + +#### Database Integration + +- Integer conversion for database storage +- String values for human-readable storage +- Compatible with date column types +- Supports date range queries + +### Performance Considerations + +#### Memory Efficiency + +- Enum instances are singleton-like +- Minimal memory overhead +- Efficient comparison operations +- Fast navigation methods + +#### Calculation Speed + +- Simple arithmetic operations +- No complex date library dependencies +- Efficient modular arithmetic for wraparound +- Optimized for frequent operations + +### Usage Best Practices + +#### Type Safety + +- Use enum values instead of integers where possible +- Leverage IDE autocompletion +- Validate enum inputs at boundaries +- Use type hints in method signatures + +#### Navigation + +- Prefer enum navigation methods over manual calculation +- Use method chaining for complex navigation +- Let the enum handle boundary conditions +- Trust automatic wraparound behavior + +#### Integration + +- Convert to integers only when interfacing with external systems +- Use string values for logging and debugging +- Leverage enum equality for comparisons +- Combine with other date utilities as needed \ No newline at end of file diff --git a/docs/core-objects.md b/docs/core-objects.md new file mode 100644 index 0000000..8520e00 --- /dev/null +++ b/docs/core-objects.md @@ -0,0 +1,217 @@ +# Core Objects and Utilities + +This documentation covers the core utility classes and support components that provide foundational functionality across the stdlib package. + +## Enum Class + +The `Enum` class provides utilities for working with PHP 8.1+ BackedEnum types safely. + +### Purpose + +Type-safe enum value extraction with validation, preventing runtime errors from incorrect enum type assumptions. + +### Key Methods + +#### Safe Value Extraction + +- `string(BackedEnum $enum)` - Safely extracts string value from string-backed enums +- `int(BackedEnum $enum)` - Safely extracts integer value from integer-backed enums + +### Usage Scenarios + +- API response formatting where enum values need conversion +- Database storage of enum values +- Form handling with enum-backed fields +- Configuration processing with enum options +- Type-safe enum value access + +### Type Safety Features + +- Validates enum backing type before extraction +- Throws `InvalidArgumentException` for type mismatches +- Prevents runtime errors from assuming wrong backing type +- Clear error messages for debugging + +### Integration Benefits + +- Works with any PHP 8.1+ backed enum +- Compatible with custom enum classes +- Provides consistent interface across different enum types +- Enables safe enum handling in generic code + +## StaticCache Class + +The `StaticCache` class provides a sophisticated static caching system with partitioning and enable/disable capabilities. + +### Purpose + +High-performance static caching with advanced features like partitioning, conditional enabling, and flexible cache management. + +### Key Methods + +#### Basic Cache Operations + +- `add(string $key, mixed $value, ?string $partition)` - Adds value to cache with optional partitioning +- `get(string $key, ?string $partition)` - Retrieves value from cache +- `remove(string $key, ?string $partition)` - Removes specific key from cache +- `contains(string $key, ?string $partition)` - Checks if key exists in cache + +#### Advanced Operations + +- `flush(?string $partition)` - Clears entire cache or specific partition +- `remember(string $key, callable $callback, ?string $partition)` - Cache-or-execute pattern +- `enable()` / `disable()` - Control cache functionality +- `enabled()` / `disabled()` - Check cache state + +### Usage Scenarios + +- Application-level caching for expensive operations +- Configuration caching across request boundaries +- Computed value storage for repeated calculations +- Temporary data storage during complex operations +- Performance optimization for frequently accessed data + +### Advanced Features + +#### Partitioning + +- Organize cache entries into logical groups +- Selective cache clearing by partition +- Namespace isolation between different cache uses +- Better cache management and organization + +#### Enable/Disable Control + +- Runtime cache control for testing scenarios +- Conditional caching based on environment +- Performance debugging capabilities +- Development vs production behavior differences + +#### Enum Key Support + +- Support for enum-based cache keys +- Type-safe key generation +- Better code organization with meaningful key names + +### Performance Considerations + +- Static storage provides fastest access times +- Memory-based caching eliminates I/O overhead +- Partitioning prevents cache pollution +- Selective flushing maintains cache efficiency + +## Php Class + +The `Php` class provides utilities for PHP version checking and compatibility management. + +### Purpose + +Reliable PHP version detection and comparison for feature detection and compatibility checking. + +### Key Methods + +#### Version Comparison + +- `greaterThanOrEqual(string $version)` - Checks if current PHP version is greater than or equal to specified version +- `lessThanOrEqual(string $version)` - Checks if current PHP version is less than or equal to specified version +- `greaterThan(string $version)` - Strict greater than comparison +- `lessThan(string $version)` - Strict less than comparison +- `equalTo(string $version)` - Exact version matching + +### Usage Scenarios + +- Feature detection based on PHP version +- Compatibility checking before using language features +- Conditional code execution based on PHP capabilities +- Library compatibility validation +- Deployment environment verification + +### Version-Dependent Development + +- Enable modern PHP features conditionally +- Maintain backward compatibility +- Provide fallbacks for older PHP versions +- Validate runtime environment capabilities + +## Support Traits + +The stdlib provides several traits that enhance class functionality across the system. + +### HasEnumValue Trait + +Enhances PHP enums with additional functionality for UI generation and data handling. + +#### Key Methods + +- `values()` - Extract all enum values as array +- `titleCasedValues()` - Get formatted title-case values for display +- `from()` - Safe enum creation that returns null instead of throwing exceptions +- `options(array $include = [], array $exclude = [])` - Generate filtered select options +- `name()` - Get formatted display name + +#### Usage Scenarios + +- Form select option generation +- Enum value validation and conversion +- UI component data preparation +- API response formatting +- Display name generation + +### StaticCacheEnabled Trait + +Provides enable/disable functionality for static cache implementations. + +#### Key Methods + +- `enable()` / `disable()` - Control cache state +- `enabled()` / `disabled()` - Check current state + +### Macroable Trait + +Enables dynamic method addition to classes, marked as experimental. + +#### Key Features + +- Dynamic method registration +- Static and instance method support +- Eloquent model integration +- Closure binding capabilities +- Method existence checking + +## Common Patterns + +### Wrapper Strategy + +Many core classes follow a wrapper pattern: + +- Provide enhanced interfaces over Laravel functionality +- Add version checking and validation +- Maintain compatibility while adding features +- Enable consistent error handling + +### Version Safety + +Core classes emphasize version safety: + +- Automatic dependency version checking +- Clear error messages for version mismatches +- Graceful degradation where possible +- Consistent version requirement handling + +### Performance Focus + +Core utilities are designed for performance: + +- Static caching for frequently accessed data +- Minimal overhead wrapper implementations +- Efficient version checking strategies +- Memory-conscious data structures + +### Type Safety + +All core classes prioritize type safety: + +- Strong typing in method signatures +- Runtime type validation where needed +- Clear exception handling for type errors +- IDE-friendly interfaces for autocompletion \ No newline at end of file diff --git a/docs/filesystem.md b/docs/filesystem.md new file mode 100644 index 0000000..65b2763 --- /dev/null +++ b/docs/filesystem.md @@ -0,0 +1,190 @@ +# Filesystem Classes + +The Filesystem namespace provides utilities for safe file and directory operations, along with standardized exit codes for CLI applications. + +## File Class + +The `File` class provides safe file system operations with comprehensive error handling and validation. + +### Purpose + +Safe file operations that handle common edge cases, provide proper error handling, and throw meaningful exceptions when operations fail. + +### Key Methods + +#### File Reading + +- `content(string $path)` - Reads file content with proper error handling and validation + +#### File Management + +- `delete(string $path)` - Deletes a file with existence checking before removal +- `copy(string $source, string $destination)` - Copies files with source validation and proper error handling + +### Usage Scenarios + +- Configuration file reading +- Template file processing +- Asset file management +- Backup file operations +- File cleanup operations + +### Error Handling + +The class uses custom exceptions to provide clear error messages: + +- Throws `FileNotFoundException` when attempting to read or copy non-existent files +- Provides meaningful error context for debugging +- Handles file system permission issues gracefully + +### Safety Features + +- Validates file existence before operations +- Prevents operations on non-existent source files +- Provides proper error messages for failed operations +- Ensures data integrity during copy operations + +## Directory Class + +The `Directory` class provides comprehensive directory operations including analysis, scanning, and content hashing functionality. + +### Purpose + +Advanced directory operations that go beyond basic file system functions, with focus on directory analysis, recursive operations, and content integrity checking. + +### Key Methods + +#### Directory Information + +- `current()` - Retrieves the current working directory + +#### Content Analysis + +- `hash(string $dir)` - Generates an MD5 hash of all directory contents, useful for detecting changes +- `scan(string $dir)` - Manually scans directory contents recursively +- `scanRecursive(string $path)` - Uses SPL iterators for efficient recursive directory scanning + +### Usage Scenarios + +- Directory change detection +- Content integrity verification +- File system monitoring +- Backup validation +- Directory comparison operations +- File listing for processing + +### Scanning Strategies + +The class provides two different scanning approaches: + +#### Manual Scanning (`scan()`) + +- Custom implementation for specific use cases +- Provides fine-grained control over scanning behavior +- Suitable for specialized filtering requirements + +#### SPL Iterator Scanning (`scanRecursive()`) + +- Uses PHP's built-in SPL iterators for efficiency +- Better performance on large directory structures +- Standard PHP approach for recursive operations + +### Hash Functionality + +The `hash()` method provides: + +- MD5 hash generation of directory contents +- Useful for detecting directory changes +- Content integrity verification +- Backup validation workflows + +### Dependencies + +- Utilizes `Arr` utility class for array operations +- Uses custom `DirectoryNotFoundException` for proper error handling +- Integrates with other filesystem utilities + +## ExitCode Class + +The `ExitCode` class provides standardized exit codes for CLI applications and system operations. + +### Purpose + +Consistent exit code standards that follow Unix conventions while also providing HTTP-status-based codes for web-related CLI tools. + +### Exit Code Categories + +#### Success Codes + +- `SUCCESS` (0) - Operation completed successfully + +#### General Error Codes + +- `GENERAL_ERROR` (1) - General catchall error +- `MISUSE_OF_SHELL_BUILTINS` (2) - Incorrect shell builtin usage +- `COMMAND_NOT_FOUND` (127) - Command not found +- `INVALID_ARGUMENT` (128) - Invalid argument to exit + +#### HTTP-Status-Based Codes + +The class also provides exit codes that correspond to HTTP status codes for web-related CLI applications: + +- Maps to `HttpStatusCode` constants for consistency +- Enables unified error handling across web and CLI contexts +- Provides semantic meaning for different failure types + +### Usage Scenarios + +- CLI application error reporting +- Script exit status standardization +- Process monitoring and alerting +- Automated deployment scripts +- System administration tools + +### Integration Benefits + +- Follows Unix exit code conventions +- Provides HTTP status integration for web tools +- Enables consistent error reporting across applications +- Supports automated monitoring systems + +### Best Practices + +- Use `SUCCESS` for successful operations +- Choose specific error codes over `GENERAL_ERROR` when possible +- Document expected exit codes in CLI application help +- Use HTTP-based codes for web-related CLI tools + +## Common Patterns + +### Error Handling Strategy + +All filesystem classes follow consistent error handling patterns: + +- Custom exceptions for specific error types +- Meaningful error messages with context +- Validation before operations +- Safe defaults and fallback behavior + +### Safety First Approach + +The filesystem classes prioritize safety by: + +- Validating inputs before operations +- Checking file/directory existence +- Providing proper error contexts +- Using exception handling for error conditions + +### Performance Considerations + +- Multiple scanning strategies for different use cases +- Efficient use of PHP built-in functions +- Proper memory management for large directories +- Optimized hash generation algorithms + +### Integration Features + +- Works seamlessly with other stdlib classes +- Uses consistent exception hierarchy +- Integrates with HTTP status codes where appropriate +- Follows Laravel filesystem patterns where applicable \ No newline at end of file diff --git a/docs/geography.md b/docs/geography.md new file mode 100644 index 0000000..3c94adc --- /dev/null +++ b/docs/geography.md @@ -0,0 +1,217 @@ +# Geography Classes + +The Geography namespace provides comprehensive geographic data structures and utilities for handling countries, political divisions, and regional information in +applications. + +## Country Enum + +The `Country` enum provides a comprehensive list of world countries as a string-backed enum with enhanced functionality. + +### Purpose + +Type-safe country selection and validation with comprehensive coverage of all recognized world countries, providing consistent country data across applications. + +### Key Features + +#### Comprehensive Coverage + +- Contains 196+ countries with standardized naming +- Uses underscore-separated values for consistency +- Covers all major world countries and territories + +#### Enhanced Functionality + +The enum uses the `HasEnumValue` trait, providing: + +- `values()` - Extract all country values as an array +- `titleCasedValues()` - Get formatted display names +- `from()` - Safe enum creation with null returns instead of exceptions +- `options()` - Generate select options with filtering capabilities +- `name()` - Get formatted display names + +### Usage Scenarios + +- Country selection dropdowns in forms +- Address validation systems +- Geographic data validation +- Internationalization support +- User profile country selection +- Shipping and billing address forms + +### Data Format + +Countries are stored with underscore-separated values that can be easily converted to display format: + +- Enum values use consistent formatting +- Display names automatically generated from values +- Support for title case conversion +- Proper handling of multi-word country names + +## DivisionType Enum + +The `DivisionType` enum defines the types of political divisions used by different countries, providing context-aware division terminology. + +### Purpose + +Determines the appropriate political subdivision terminology (state, province, region) based on the country context, ensuring correct usage in forms and displays. + +### Available Types + +- `State` - Used primarily by the United States +- `Province` - Used by countries like Canada +- `Region` - Used by various other countries + +### Key Methods + +#### Context-Aware Division Selection + +- `country(Country $country)` - Returns the appropriate division type for a given country using match expressions + +### Usage Scenarios + +- Dynamic form field labeling +- Address form customization based on country selection +- Proper terminology in shipping forms +- Internationalized address validation +- Geographic data entry interfaces + +### Smart Country Mapping + +The class provides intelligent mapping based on country: + +- United States → State +- Canada → Province +- Other countries → Region (as default) +- Extensible for additional country-specific mappings + +## Canada Enum + +The `Canada` enum provides comprehensive coverage of Canadian provinces and territories with official abbreviations. + +### Purpose + +Type-safe Canadian province and territory selection with official abbreviation support for address validation and form processing. + +### Coverage + +#### Provinces (10) + +All Canadian provinces with their standard names and abbreviations + +#### Territories (3) + +All Canadian territories including northern territories + +### Key Methods + +#### Official Abbreviations + +- `abbreviated()` - Returns official province/territory abbreviations as used by Canada Post and government systems + +### Usage Scenarios + +- Canadian address forms +- Shipping calculation systems +- Tax calculation based on province +- Canadian user registration +- Geographic filtering for Canadian users +- Postal code validation + +### Data Accuracy + +- Uses official provincial/territorial names +- Provides Canada Post approved abbreviations +- Consistent formatting across all entries +- Proper handling of bilingual names where applicable + +## UnitedStates Enum + +The `UnitedStates` enum provides comprehensive coverage of all US states with official abbreviations. + +### Purpose + +Type-safe US state selection with official USPS abbreviation support for address validation and form processing. + +### Coverage + +#### Complete State Coverage + +All 50 US states with standardized naming and official abbreviations + +### Key Methods + +#### Official Abbreviations + +- `abbreviated()` - Returns official USPS state abbreviations + +### Usage Scenarios + +- US address forms +- State tax calculations +- Shipping rate determination +- Geographic filtering for US users +- ZIP code validation +- State-specific feature toggling + +### Data Standards + +- Follows USPS official state names +- Uses standard USPS abbreviations +- Consistent formatting across all states +- Proper alphabetical ordering + +## Common Patterns + +### Enum Enhancement Strategy + +All geography enums utilize the `HasEnumValue` trait, providing: + +#### Consistent API + +- Standardized methods across all geographic enums +- Uniform display formatting capabilities +- Consistent null-safe creation methods +- Shared filtering and option generation + +#### UI Integration + +- Easy dropdown/select option generation +- Filtering capabilities for subset selection +- Display name formatting +- Type-safe value handling + +### Type Safety Benefits + +Geographic enums provide: + +- Compile-time validation of country/division values +- IDE autocompletion support +- Prevention of typos in geographic data +- Consistent data formats across applications + +### Internationalization Support + +The geography classes support internationalization by: + +- Providing machine-readable identifiers +- Supporting display name customization +- Enabling easy integration with translation systems +- Maintaining data consistency across locales + +### Address Form Integration + +These classes are designed specifically for address form scenarios: + +- Dynamic form field adjustment based on country +- Proper terminology usage (state vs province) +- Official abbreviation support for data storage +- Validation support for geographic data + +### Extensibility + +The geographic system is designed for extension: + +- Easy addition of new countries or divisions +- Consistent patterns for new geographic entities +- Trait-based enhancement system +- Integration with custom validation rules \ No newline at end of file diff --git a/docs/http.md b/docs/http.md new file mode 100644 index 0000000..13efe5c --- /dev/null +++ b/docs/http.md @@ -0,0 +1,182 @@ +# HTTP Classes + +The Http namespace provides utilities and constants for HTTP-related operations, ensuring type safety and consistency across web applications. + +## Url Class + +The `Url` class provides safe URL encoding and decoding operations with proper error handling. + +### Purpose + +Reliable URL manipulation utilities that handle edge cases and provide null-safe operations for web applications. + +### Key Methods + +#### URL Encoding/Decoding + +- `encode(mixed $data)` - URL encodes data with proper type handling +- `decode(mixed $data)` - URL decodes data with null-safe operations + +### Usage Scenarios + +- Query parameter encoding for API requests +- URL-safe string conversion +- Form data preparation +- Search parameter handling +- Safe URL construction + +### Features + +- Handles mixed data types appropriately +- Null-safe operations prevent runtime errors +- Consistent encoding behavior across different input types + +## HttpMethod Class + +The `HttpMethod` class provides constants for standard HTTP methods, ensuring consistency and preventing typos in HTTP operations. + +### Purpose + +Type-safe HTTP method references that eliminate magic strings and provide IDE autocompletion support. + +### Available Constants + +- `GET` - HTTP GET method +- `POST` - HTTP POST method +- `PUT` - HTTP PUT method +- `PATCH` - HTTP PATCH method +- `DELETE` - HTTP DELETE method +- `HEAD` - HTTP HEAD method +- `OPTIONS` - HTTP OPTIONS method +- `TRACE` - HTTP TRACE method +- `CONNECT` - HTTP CONNECT method + +### Usage Scenarios + +- HTTP client configuration +- Route definition +- API endpoint documentation +- Request validation +- Method comparison operations + +### Benefits + +- IDE autocompletion support +- Prevents typos in HTTP method strings +- Centralized method definitions +- Type safety in method comparisons + +## HttpStatusCode Class + +The `HttpStatusCode` class provides constants for standard HTTP status codes with comprehensive coverage of common and specialized codes. + +### Purpose + +Type-safe HTTP status code references that eliminate magic numbers and provide consistent status code usage across applications. + +### Key Status Code Categories + +#### Success Codes (2xx) + +- `OK` (200) - Standard success response +- `CREATED` (201) - Resource creation success +- `ACCEPTED` (202) - Request accepted for processing +- `NO_CONTENT` (204) - Success with no response body + +#### Redirection Codes (3xx) + +- `MOVED_PERMANENTLY` (301) - Permanent redirect +- `FOUND` (302) - Temporary redirect +- `NOT_MODIFIED` (304) - Resource not modified +- `PERMANENT_REDIRECT` (301) - Alias for moved permanently +- `TEMPORARY_REDIRECT` (302) - Alias for found + +#### Client Error Codes (4xx) + +- `BAD_REQUEST` (400) - Malformed request +- `UNAUTHORIZED` (401) - Authentication required +- `FORBIDDEN` (403) - Access denied +- `NOT_FOUND` (404) - Resource not found +- `METHOD_NOT_ALLOWED` (405) - HTTP method not supported +- `UNPROCESSABLE_ENTITY` (422) - Validation errors + +#### Server Error Codes (5xx) + +- `INTERNAL_SERVER_ERROR` (500) - General server error +- `NOT_IMPLEMENTED` (501) - Method not implemented +- `BAD_GATEWAY` (502) - Gateway error +- `SERVICE_UNAVAILABLE` (503) - Service temporarily unavailable + +### Usage Scenarios + +- API response status setting +- HTTP client response handling +- Error handling and logging +- Status code comparison operations +- API documentation and testing + +### Features + +- Comprehensive status code coverage +- Some constants provide aliases for different naming conventions +- Consistent numeric values following HTTP standards + +## HttpStatusName Class + +The `HttpStatusName` class provides human-readable string constants that correspond to HTTP status codes, designed to work alongside `HttpStatusCode`. + +### Purpose + +Display-friendly HTTP status descriptions for user interfaces, logging, and error messages. + +### Key Features + +- String constants matching `HttpStatusCode` values +- Human-readable status descriptions +- Consistent naming convention with status code class +- Suitable for user-facing messages + +### Usage Scenarios + +- Error message display +- API response documentation +- Logging and debugging +- User interface status indicators +- Error reporting systems + +### Relationship with HttpStatusCode + +The `HttpStatusName` class is designed as a companion to `HttpStatusCode`, providing descriptive names that correspond to the numeric codes. This allows for consistent +status handling across both programmatic operations and user-facing displays. + +## Common Patterns + +### Type Safety + +All HTTP classes emphasize type safety by: + +- Using constants instead of magic strings/numbers +- Providing consistent interfaces +- Enabling IDE autocompletion +- Preventing runtime errors from typos + +### Standards Compliance + +- HTTP methods follow RFC specifications +- Status codes adhere to HTTP/1.1 and HTTP/2 standards +- URL encoding follows web standards +- Consistent behavior across different environments + +### Integration Benefits + +- Seamless integration with HTTP clients (Guzzle, Laravel HTTP) +- Compatible with PSR-7 HTTP message interfaces +- Works with popular PHP frameworks +- Suitable for both client and server-side applications + +### Error Prevention + +- Eliminates magic strings and numbers +- Provides compile-time checking through constants +- Reduces debugging time from HTTP-related issues +- Enables static analysis tools to catch errors early \ No newline at end of file diff --git a/docs/serializers.md b/docs/serializers.md new file mode 100644 index 0000000..b85d6fd --- /dev/null +++ b/docs/serializers.md @@ -0,0 +1,256 @@ +# Serializers Classes + +The Serializers namespace provides a comprehensive object serialization system built on Symfony's Serializer component, with support for JSON and XML formats plus custom normalizers for common data types. + +## AbstractSerializer Class + +The `AbstractSerializer` class serves as the foundation for all serializer implementations, providing a consistent interface and shared functionality. + +### Purpose + +Base class that implements the template method pattern for serialization, handling normalizer management and providing a consistent API for concrete serializer implementations. + +### Key Methods + +#### Normalizer Management + +- `setNormalizers(array $normalizers)` - Configure the complete set of normalizers +- `addNormalizer(NormalizerInterface $normalizer)` - Add a normalizer to the end of the chain +- `prependNormalizer(NormalizerInterface $normalizer)` - Add a normalizer to the beginning of the chain + +#### Serialization Operations + +- `serialize(object $object)` - Convert an object to its serialized string representation +- `deserialize(string $class, string $data)` - Convert serialized data back to an object instance + +#### Template Methods + +- `format()` - Abstract method that concrete classes implement to specify format (json, xml, etc.) +- `encoders()` - Abstract method that concrete classes implement to provide format-specific encoders + +### Usage Scenarios + +- Building custom serialization formats +- Creating standardized serialization workflows +- Implementing consistent object transformation +- API response formatting + +### Architecture Benefits + +- Consistent interface across different formats +- Extensible normalizer system +- Template method pattern ensures consistent behavior +- Built on Symfony's robust serialization framework + +## JsonSerializer Class + +The `JsonSerializer` class provides JSON serialization capabilities with configurable normalizers. + +### Purpose + +Complete JSON serialization solution for converting PHP objects to JSON and back, with support for custom data type handling through normalizers. + +### Implementation Details + +- Extends `AbstractSerializer` +- Uses Symfony's `JsonEncoder` +- Supports all JSON-compatible data types +- Configurable normalizer chain + +### Usage Scenarios + +- API response serialization +- Data persistence to JSON format +- Configuration object serialization +- Inter-service communication +- Frontend data exchange + +### Features + +- Pretty printing support (via Symfony encoder options) +- Custom normalizer support for complex types +- Proper handling of nested objects +- Laravel Collection serialization (with appropriate normalizer) +- Carbon date serialization (with appropriate normalizer) + +## XmlSerializer Class + +The `XmlSerializer` class provides XML serialization capabilities for applications requiring XML data exchange. + +### Purpose + +XML serialization solution for converting PHP objects to XML format, useful for legacy system integration and specific protocol requirements. + +### Implementation Details + +- Extends `AbstractSerializer` +- Uses Symfony's `XmlEncoder` +- Currently marked as experimental +- Supports configurable normalizers + +### Usage Scenarios + +- Legacy system integration +- SOAP web service communication +- XML-based configuration files +- Enterprise system data exchange +- XML API implementations + +### Experimental Status + +The XML serializer is marked as experimental, meaning: + +- API may change in future versions +- Should be tested thoroughly before production use +- Feedback and bug reports are particularly valuable +- Additional features may be added based on usage patterns + +## CarbonNormalizer Class + +The `CarbonNormalizer` class provides specialized handling for Carbon date objects during serialization. + +### Purpose + +Ensures consistent date serialization/deserialization for both Carbon and Laravel Carbon instances, using W3C standard format for interoperability. + +### Key Methods + +#### Normalization + +- `normalize()` - Converts Carbon objects to W3C standard string format +- `supportsNormalization()` - Checks if the data is a Carbon instance + +#### Denormalization + +- `denormalize()` - Creates Carbon instances from W3C formatted strings +- `supportsDenormalization()` - Validates target type is Carbon-compatible + +### Usage Scenarios + +- API date/time consistency +- Database date serialization +- Cross-system date exchange +- Frontend date handling +- Time zone aware serialization + +### Date Format + +Uses W3C standard format for maximum compatibility: + +- ISO 8601 compliant +- Timezone information preserved +- Parseable by most date libraries +- Human-readable format + +### Carbon Support + +Handles both Carbon types: + +- Original Carbon library instances +- Laravel's Illuminate Carbon instances +- Consistent behavior across both types + +## LaravelCollectionNormalizer Class + +The `LaravelCollectionNormalizer` class provides specialized handling for Laravel Collection objects. + +### Purpose + +Enables Laravel Collections to be properly serialized and reconstructed, maintaining collection functionality after deserialization. + +### Key Methods + +#### Normalization + +- `normalize()` - Converts Laravel Collections to arrays for serialization +- `supportsNormalization()` - Identifies Laravel Collection instances + +#### Denormalization + +- `denormalize()` - Reconstructs Laravel Collections from array data +- `supportsDenormalization()` - Validates target type is Collection-compatible + +### Usage Scenarios + +- API responses containing collections +- Caching collection data +- Inter-service data transfer +- Database serialization +- Configuration object serialization + +### Collection Preservation + +- Maintains collection methods after deserialization +- Preserves nested collection structures +- Handles both typed and untyped collections +- Compatible with all Laravel Collection types + +## Common Patterns + +### Normalizer Chain Strategy + +The serializer system uses a normalizer chain approach: + +#### Order Matters + +- Normalizers are checked in order +- First matching normalizer handles the data +- More specific normalizers should come first +- Generic normalizers come last + +#### Custom Normalizers + +- Easy to add domain-specific normalizers +- Can handle complex object relationships +- Support for conditional normalization +- Extensible for new data types + +### Type Safety + +All serializers provide type safety through: + +- Interface-based contracts +- Type checking in normalizers +- Exception handling for invalid data +- Consistent error reporting + +### Performance Considerations + +#### Normalizer Efficiency + +- Normalizers checked in order until match found +- Specific type checking minimizes overhead +- Caching of normalizer results where appropriate +- Efficient handling of nested structures + +#### Memory Management + +- Stream-based processing for large objects +- Lazy loading of normalizers +- Proper cleanup of temporary data +- Efficient handling of large collections + +### Integration Benefits + +#### Symfony Ecosystem + +- Built on proven Symfony Serializer component +- Compatible with Symfony normalizers +- Access to Symfony's extensive serialization features +- Professional-grade serialization handling + +#### Laravel Integration + +- Seamless handling of Laravel Collections +- Carbon date object support +- Compatible with Laravel's data structures +- Works with Eloquent models (with appropriate normalizers) + +### Error Handling + +The serializer system provides robust error handling: + +- Clear exception messages for serialization failures +- Type validation during deserialization +- Graceful handling of missing normalizers +- Detailed error context for debugging \ No newline at end of file diff --git a/docs/support-types.md b/docs/support-types.md new file mode 100644 index 0000000..a1ae34f --- /dev/null +++ b/docs/support-types.md @@ -0,0 +1,110 @@ +# Support/Types Classes + +The Support/Types namespace provides enhanced type utility classes that extend Laravel's base functionality with additional methods tailored for common development +scenarios. + +## Str Class + +The `Str` class extends Laravel's `Illuminate\Support\Str` class, providing all base Laravel string functionality plus additional utility methods. + +### Purpose + +Enhanced string manipulation operations beyond Laravel's base functionality, with a focus on formatting, validation, and type-safe conversions. + +### Key Methods + +#### Basic Utilities + +- `guid()` - Generates a UUID as a string +- `empty()` - Returns an empty string constant +- `space()` - Returns a single space character +- `toString(mixed $value)` - Performs type-safe string conversion + +#### Text Formatting + +- `maxLength(string $value, ?int $length = null)` - Truncates strings to maximum length (default: 100 characters) +- `conjunctions(string $value)` - Formats conjunctions by converting "And" → "and", "Or" → "or", "Of" → "of" +- `formattedTitleCase(string $value)` - Applies title case while removing underscores and formatting conjunctions + +### Usage Scenarios + +- String truncation with consistent length limits +- Text formatting for display purposes +- Title case formatting with proper conjunction handling +- UUID generation for unique identifiers +- Type-safe string conversions + +## Arr Class + +The `Arr` class extends Laravel's `Illuminate\Support\Arr` class, providing all base Laravel array functionality plus advanced manipulation methods. + +### Purpose + +Advanced array operations that maintain array structure integrity while providing powerful manipulation capabilities. + +### Key Methods + +#### Basic Utilities + +- `empty()` - Returns an empty array constant + +#### Array Manipulation + +- `renameKey(array $array, string $oldKey, string $newKey)` - Renames an array key while preserving the original order of elements +- `addAfter(array $array, string $afterKey, string $newKey, mixed $newValue)` - Inserts a new key-value pair after a specified existing key + +### Usage Scenarios + +- Maintaining array order during key modifications +- Dynamic array structure manipulation +- Form field reordering and insertion +- Configuration array modifications + +## Number Class + +The `Number` class extends Laravel's `Illuminate\Support\Number` class, providing all base Laravel number functionality plus type-safe validation and conversion methods. + +### Purpose + +Safe number operations with built-in validation to prevent type conversion errors and ensure data integrity. + +### Key Methods + +#### Type Conversion + +- `toInt(mixed $value)` - Performs type-safe integer conversion +- `validate(mixed $value)` - Validates whether a value can be safely converted to an integer + +### Usage Scenarios + +- Safe type conversion in user input processing +- Data validation before mathematical operations +- Form input sanitization +- API data type validation + +## Common Patterns + +### Inheritance Strategy + +All Support/Types classes extend their Laravel counterparts, meaning you get: + +- All existing Laravel functionality +- Additional stdlib-specific methods +- Seamless integration with existing Laravel code +- Drop-in replacement capability + +### Type Safety + +These classes emphasize type safety by: + +- Providing validation methods before conversions +- Using nullable return types where appropriate +- Throwing appropriate exceptions for invalid operations +- Maintaining consistent behavior across different input types + +### Performance Considerations + +- Built on top of Laravel's optimized implementations +- Additional methods maintain Laravel's performance characteristics +- String operations use efficient PHP built-in functions +- Array operations preserve memory efficiency where possible \ No newline at end of file