Utils
in package
Multi-purpose utility class for HTTP responses, data formatting, and file operations
Comprehensive collection of static utility methods for common web application tasks including JSON API responses, CSV data export, configuration parsing, file sequence management, and directory operations. Designed to reduce code duplication and provide consistent interfaces for frequent programming tasks.
Response Utilities
- JSON API Responses: Standardized JSON output with HTTP status codes and headers
- Content-Type Management: Automatic header setting for proper MIME types
- HTTP Status Integration: Works with HttpStatus class for proper status codes
- Script Termination: Controlled exit after response delivery
Data Format Utilities
- CSV Generation: Convert arrays to CSV format with customizable delimiters
- Configuration Parsing: Parse pipe-delimited INI-style configuration strings
- Type Conversion: Automatic type casting for numeric values
- Header Management: Automatic CSV header generation from array keys
File System Utilities
- Sequence Management: Generate next available numbers in file naming patterns
- Directory Creation: Ensure directory structure exists for file operations
- Path Validation: Safe directory and file path handling
- Permission Management: Configurable directory permissions
Design Philosophy
- Static Interface: All methods static for convenience and consistency
- Error Handling: Graceful error handling with exceptions for critical failures
- No Side Effects: Pure functions where possible, clear side effects where necessary
- Framework Integration: Works seamlessly with other Primordyx components
Common Usage Patterns
Utils serves as the "Swiss Army knife" for common operations that don't warrant separate classes but occur frequently across applications. Methods are designed to be called directly without instantiation and handle edge cases gracefully.
Tags
Table of Contents
Methods
- ensureDirectoryForFile() : bool
- Create directory structure for file path to prevent write failures
- getNextFileSequenceNumber() : int
- Calculate next available sequence number for patterned file naming
- parseToAssocArray() : array<int, mixed>
- Parse pipe-delimited INI-style string into associative array with type conversion
- sendJson() : never
- Convenient alias for sendJsonResponse() with identical functionality
- sendJsonResponse() : never
- Send JSON response with HTTP status code and terminate script execution
- toCsv() : string
- Convert two-dimensional array to CSV-formatted string with automatic headers
Methods
ensureDirectoryForFile()
Create directory structure for file path to prevent write failures
public
static ensureDirectoryForFile(string $filePath[, int $permissions = 0755 ]) : bool
Recursively creates parent directories for specified file path if they don't already exist. Essential for dynamic file creation where directory structure may not be pre-established, preventing common "No such file or directory" errors.
Directory Creation Process
- Path Analysis: Extract directory path using dirname()
- Existence Check: Return early if directory already exists
- Recursive Creation: Create parent directories with mkdir(..., true)
- Permission Setting: Apply specified permissions to created directories
- Result Return: Boolean success/failure status
Permission Handling
- Default: 0755 (owner: rwx, group: rx, other: rx)
- Configurable: Custom permissions via parameter
- Recursive: Applied to all created directories in path
- Existing: Does not modify permissions of existing directories
Use Cases
- Log file initialization in dynamic paths
- Cache file storage with date-based directory structure
- Upload handling with user-specific directories
- Report generation in organized folder hierarchies
- Configuration file creation in multi-level paths
Parameters
- $filePath : string
-
Complete file path (including filename) for directory creation
- $permissions : int = 0755
-
Octal permissions for created directories (default: 0755)
Tags
Return values
bool —True if directory exists or was created successfully, false on failure
getNextFileSequenceNumber()
Calculate next available sequence number for patterned file naming
public
static getNextFileSequenceNumber(string $pattern) : int
Analyzes existing files matching a numeric pattern and returns the next available sequence number. Useful for auto-incrementing file names, backup sequences, or any systematic file numbering scheme requiring gap detection and collision avoidance.
Pattern Format
- Placeholder: Use '#' characters to represent numeric digits
- Digit Count: Number of '#' characters determines padding (### = 3 digits)
- Pattern Example:
/var/logs/app_###.log
matchesapp_001.log
,app_002.log
- Directory Support: Full paths supported with automatic directory extraction
Sequence Detection Logic
- Pattern Analysis: Count '#' characters to determine numeric field width
- Glob Search: Create wildcard pattern and scan directory for matches
- Number Extraction: Parse numeric sequences from matching filenames
- Maximum Finding: Identify highest existing sequence number
- Next Calculation: Return max + 1 as next available number
Gap Handling
Returns next number after highest found, not first gap. If files exist as
file_001.txt, file_003.txt, file_005.txt
, returns 6
not 2
or 4
.
Zero Padding Awareness
Respects padding implied by pattern - ###
expects 3-digit numbers, so
generated filenames should use sprintf('%03d', $number) for consistency.
Parameters
- $pattern : string
-
File path pattern with '#' placeholders for digits
Tags
Return values
int —Next available sequence number (always ≥ 1)
parseToAssocArray()
Parse pipe-delimited INI-style string into associative array with type conversion
public
static parseToAssocArray(string|null $raw[, string $separator = '|' ]) : array<int, mixed>
Converts configuration strings in "key=value|key=value" format into PHP associative arrays with automatic type conversion for numeric values. Useful for parsing configuration data, database connection options, or serialized settings.
Parsing Format
- Delimiter: Pipe character (|) separates key-value pairs by default
- Assignment: Equals sign (=) separates keys from values
- Key Conversion: Keys cast to integers for numeric keys
- Value Conversion: Numeric values automatically cast to integers
- Trimming: Automatic whitespace trimming on keys and values
Type Conversion Rules
- Numeric values converted to integers using is_numeric() and (int) casting
- Non-numeric values remain as strings
- Empty values remain as empty strings
Error Handling
- Empty/null input returns empty array
- Malformed pairs (missing =) are silently skipped
- Invalid separators produce empty arrays
- Method never throws exceptions for parsing errors
Parameters
- $raw : string|null
-
Configuration string to parse (null returns empty array)
- $separator : string = '|'
-
Character used to separate key-value pairs (default: '|')
Tags
Return values
array<int, mixed> —Associative array with integer keys and mixed values
sendJson()
Convenient alias for sendJsonResponse() with identical functionality
public
static sendJson(mixed $data[, int $code = 200 ][, array<string, string> $headers = [] ]) : never
Provides shorter method name for frequent JSON response operations while maintaining exact same parameters, behavior, and script termination as sendJsonResponse(). Choose based on coding style preference or team conventions.
Method Equivalence
This method is functionally identical to sendJsonResponse() and simply delegates all parameters without modification. Both methods set identical headers, handle data encoding the same way, and terminate script execution.
Parameters
- $data : mixed
-
Data to encode as JSON (arrays, objects, primitives)
- $code : int = 200
-
HTTP status code to send (default: 200 OK)
- $headers : array<string, string> = []
-
Optional additional HTTP headers to send
Tags
Return values
never —Method terminates script execution and never returns
sendJsonResponse()
Send JSON response with HTTP status code and terminate script execution
public
static sendJsonResponse(mixed $data[, int $code = 200 ][, array<string, string> $headers = [] ]) : never
Comprehensive JSON response handler that sets appropriate HTTP headers, encodes data as JSON with pretty-printing, and terminates script execution. Essential for API endpoints and AJAX handlers requiring standardized JSON responses.
Response Process
- Header Safety: Check if headers already sent to avoid errors
- Status Code: Set HTTP status using HttpStatus class integration
- Content-Type: Set to application/json for proper MIME handling
- Custom Headers: Add any additional headers provided
- JSON Encoding: Encode data with JSON_PRETTY_PRINT for readability
- Script Termination: Exit immediately after response sent
Header Management
- Automatically sets Content-Type: application/json
- Uses HttpStatus::sendHeader() for proper status code handling
- Supports custom headers via associative array parameter
- Gracefully handles cases where headers already sent
JSON Encoding
- Uses JSON_PRETTY_PRINT for human-readable output
- Handles PHP data types automatically (arrays, objects, primitives)
- Does not perform JSON encoding error handling (assumes valid data)
Script Termination
Method never returns - always terminates script with exit after response. This prevents additional output that could corrupt JSON response format.
Parameters
- $data : mixed
-
Data to encode as JSON (any JSON-serializable type)
- $code : int = 200
-
HTTP status code (default: 200, common: 201, 400, 404, 500)
- $headers : array<string, string> = []
-
Additional headers as key-value pairs
Tags
Return values
never —Method always terminates script execution
toCsv()
Convert two-dimensional array to CSV-formatted string with automatic headers
public
static toCsv(array<string|int, array<string, mixed>> $rows[, string $delimiter = ',' ][, string $enclosure = '"' ]) : string
Transforms array of associative arrays into properly formatted CSV string with configurable delimiters and enclosures. Automatically generates header row from first record's keys and handles CSV escaping through PHP's built-in fputcsv().
CSV Format Features
- Automatic Headers: Uses first row keys as column headers
- Proper Escaping: Handles commas, quotes, newlines in data via fputcsv()
- Configurable Delimiters: Custom field separators (comma, tab, pipe, etc.)
- Configurable Enclosures: Custom quote characters for field wrapping
- Empty Array Handling: Returns empty string for empty input arrays
Data Structure Requirements
- Input must be array of associative arrays (rows)
- All rows should have consistent key structure for proper columns
- Keys become column headers, values become cell data
- Mixed data types automatically converted to strings
Memory Efficiency
Uses php://temp stream for memory-efficient processing of large datasets without loading entire CSV string into memory during generation.
Parameters
- $rows : array<string|int, array<string, mixed>>
-
Array of associative arrays representing CSV rows
- $delimiter : string = ','
-
Field separator character (default: comma)
- $enclosure : string = '"'
-
Quote character for fields (default: double-quote)
Tags
Return values
string —Complete CSV-formatted string including headers