krugozor / cover
PHP Array Object (PHP collection)
Installs: 4
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/krugozor/cover
Requires
- php: >=8.0
- ext-ctype: *
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2026-02-06 05:13:00 UTC
README
Other languages:
- Русская документация
- Documentation française
- Deutsche Dokumentation
- Documentazione italiana
- 日本語ドキュメント
- Documentación en español
- 한국어 문서
- 简体中文文档
- 繁體中文文件
- Dokumentasi Bahasa Indonesia
- Documentação em Português (BR)
- हिंदी दस्तावेज़
- التوثيق بالعربية
- Türkçe Dokümantasyon
- Tài liệu tiếng Việt
State
Test Status
| PHP Version | Status |
|---|---|
| 8.0 | |
| 8.1 | |
| 8.2 | |
| 8.3 | |
| 8.4 | |
| 8.5 |
Code Coverage
Requirements
PHP >= 8.0
Installation
composer require krugozor/cover
CoverArray: Object-Oriented Array Wrapper for PHP (PHP Collection)
Created by human, verified and tested by artificial intelligence. Release 2026
Why CoverArray Was Created
In modern PHP development, we often work with arrays as the primary data structure. However, PHP's native array functions have several limitations that CoverArray solves.
The Problem with Native PHP Arrays
- Inconsistent function naming: Some functions use underscores (
array_map), others don't (usort) - Mixed parameter orders: Functions like
array_map($callback, $array)vsarray_filter($array, $callback) - No method chaining: Native functions return new arrays, requiring intermediate variables
- Limited type safety: No IDE autocompletion or static analysis support
- Verbose syntax: Complex operations require nested function calls
What CoverArray Solves
CoverArray provides a clean, object-oriented interface that wraps PHP arrays while maintaining full compatibility with native functions:
// Data: users with age and status // Task: get names of active users over 18, sorted by descending score $users = [ ['name' => 'Alice', 'age' => 25, 'active' => true, 'score' => 85], ['name' => 'Bob', 'age' => 17, 'active' => false, 'score' => 45], ['name' => 'Charlie', 'age' => 32, 'active' => true, 'score' => 92], ['name' => 'Diana', 'age' => 19, 'active' => true, 'score' => 78], ['name' => 'Eve', 'age' => 22, 'active' => false, 'score' => 61], ];
Before (Native PHP):
$filtered = array_filter($users, fn($u) => $u['active'] && $u['age'] >= 18); $sorted = usort($filtered, fn($a, $b) => $b['score'] <=> $a['score']) ? $filtered : []; $names = array_column($sorted, 'name'); $result = implode(', ', $names); // Charlie, Alice, Diana
After (CoverArray):
// EVERYTHING IN ONE LINE! $result = CoverArray::fromArray($users) ->filter(fn($u) => $u->active && $u->age >= 18) ->usort(fn($a, $b) => $b->score <=> $a->score) ->values() ->column('name') ->implode(', '); // Charlie, Alice, Diana
Key Benefits
- No External Dependencies: Pure PHP implementation, no additional packages required
- Consistent API: All methods follow
$array->method($arguments)pattern - Method Chaining: Chain multiple operations in a readable way
- IDE Support: Full autocompletion and type hints
- Modern Syntax: Designed for PHP 8.0+ with strict typing
- Dot Notation: Easy nested data access with
$array->get('user.profile.name') - JSON Support: Built-in serialization/deserialization
- Immutable Operations: Most methods return new instances, preserving original data
- Full Compatibility: Works seamlessly with existing array-based code
Real-World Use Cases
Example 1: Configuration Management with Dot Notation
// Load and access nested configuration safely $config = CoverArray::fromJson(file_get_contents('config.json')); // Direct nested access with default fallbacks $dbHost = $config->get('database.connections.mysql.host', fn($value) => $value ?? 'localhost'); $dbPort = $config->get('database.connections.mysql.port', fn($value) => $value ?? 3306); // Access with callback for complex defaults $apiKeys = $config->get('services.payment.keys', function($keys) { return $keys ?? CoverArray::fromArray([ 'public' => 'default_public_key', 'secret' => 'default_secret_key' ]); });
Example 2: API Response Processing Pipeline
// Real-world API processing: filter, transform, and extract data $apiResponse = CoverArray::fromJson($httpResponse) ->get('data.users', function (mixed $users): CoverArray { if ($users === null) { return new CoverArray(); } /** @var CoverArray $users */ return $users ->filter(fn($u) => $u['active'] == '1' && $u['email_verified']) ->map(fn($u) => [ 'id' => $u['id'], 'name' => $u['first_name'] . ' ' . $u['last_name'], 'email' => strtolower($u['email']), 'role' => $u['role'] ?? 'user' ]) ->usort(fn($a, $b) => $a['name'] <=> $b['name']); }); // Extract specific columns for dropdown $userOptions = $apiResponse->column('name', 'id')->getDataAsArray();
Example 3: Log Analysis and Error Reporting
// Parse application logs and extract error patterns $logLines = CoverArray::fromExplode("\n", file_get_contents('app.log')) ->filter(fn($line) => !empty(trim($line))); // Extract and categorize errors $errors = $logLines ->filter(fn($line) => str_contains($line, 'ERROR')) ->map(function($line) { preg_match('/\[(.*?)\].*ERROR:\s*(\w+)\s*-\s*(.*)/', $line, $matches); return [ 'timestamp' => $matches[1] ?? 'Unknown', 'type' => $matches[2] ?? 'General', 'message' => $matches[3] ?? $line ]; }); // Group by error type and count occurrences $errorStats = $errors ->column('type') ->countValues() ->arsort(); // Sort by frequency // Generate error report $report = "Error Report:\n"; foreach ($errorStats as $type => $count) { $report .= "- {$type}: {$count} occurrences\n"; } // Find most recent critical error $lastCritical = $errors ->filter(fn($e) => $e['type'] === 'Critical') ->last();
CoverArray bridges the gap between PHP's powerful array functions and modern object-oriented practices, making array manipulation more expressive, maintainable, and enjoyable.
Comparison Table: CoverArray Methods vs PHP Array Functions
| # | PHP Function | CoverArray Method | Status | Notes |
|---|---|---|---|---|
| 1 | array_all | all() | ✅ | Implemented with polyfill for older PHP versions |
| 2 | array_any | any() | ✅ | Implemented with polyfill for older PHP versions |
| 3 | array_change_key_case | changeKeyCase() | ✅ | Full implementation |
| 4 | array_chunk | chunk() | ✅ | Full implementation |
| 5 | array_column | column() | ✅ | Full implementation |
| 6 | array_combine | combine() | ✅ | Full implementation (static method) |
| 7 | array_count_values | countValues() | ✅ | Full implementation |
| 8 | array_diff | diff() | ✅ | Full implementation |
| 9 | array_diff_assoc | diffAssoc() | ✅ | Full implementation |
| 10 | array_diff_key | diffKey() | ✅ | Full implementation |
| 11 | array_diff_uassoc | diffUassoc() | ✅ | Full implementation |
| 12 | array_diff_ukey | diffUkey() | ✅ | Full implementation |
| 13 | array_fill | fill() | ✅ | Full implementation (static method) |
| 14 | array_fill_keys | fillKeys() | ✅ | Full implementation (static method) |
| 15 | array_filter | filter() | ✅ | Full implementation |
| 16 | array_find | find() | ✅ | Implemented with polyfill for older PHP versions |
| 17 | array_find_key | findKey() | ✅ | Implemented with polyfill for older PHP versions |
| 18 | array_first | first() | ✅ | Implemented with polyfill for older PHP versions |
| 19 | array_flip | flip() | ✅ | Full implementation |
| 20 | array_intersect | intersect() | ✅ | Full implementation |
| 21 | array_intersect_assoc | intersectAssoc() | ✅ | Full implementation |
| 22 | array_intersect_key | intersectKey() | ✅ | Full implementation |
| 23 | array_intersect_uassoc | intersectUassoc() | ✅ | Full implementation |
| 24 | array_intersect_ukey | intersectUkey() | ✅ | Full implementation |
| 25 | array_is_list | isList() | ✅ | Implemented with polyfill for older PHP versions |
| 26 | array_key_exists | keyExists() | ✅ | Full implementation |
| 27 | array_key_first | keyFirst() | ✅ | Uses built-in function |
| 28 | array_key_last | keyLast() | ✅ | Uses built-in function |
| 29 | array_keys | keys() | ✅ | Full implementation |
| 30 | array_last | last() | ✅ | Implemented with polyfill for older PHP versions |
| 31 | array_map | map() | ✅ | Full implementation |
| 32 | array_merge | merge() | ✅ | Full implementation |
| 33 | array_merge_recursive | mergeRecursive() | ✅ | Full implementation |
| 34 | array_multisort | multisort() | ✅ | Full implementation (mutating) |
| 35 | array_pad | pad() | ✅ | Full implementation |
| 36 | array_pop | pop() | ✅ | Full implementation (mutating) |
| 37 | array_product | product() | ✅ | Full implementation |
| 38 | array_push | push() / append() | ✅ | Full implementation (mutating) |
| 39 | array_rand | rand() | ✅ | Full implementation |
| 40 | array_reduce | reduce() | ✅ | Full implementation |
| 41 | array_replace | replace() | ✅ | Full implementation |
| 42 | array_replace_recursive | replaceRecursive() | ✅ | Full implementation |
| 43 | array_reverse | reverse() | ✅ | Full implementation |
| 44 | array_search | search() | ✅ | Full implementation |
| 45 | array_shift | shift() | ✅ | Full implementation (mutating) |
| 46 | array_slice | slice() | ✅ | Full implementation |
| 47 | array_splice | splice() | ✅ | Full implementation (mutating) |
| 48 | array_sum | sum() | ✅ | Full implementation |
| 49 | array_udiff | udiff() | ✅ | Full implementation |
| 50 | array_udiff_assoc | udiffAssoc() | ✅ | Full implementation |
| 51 | array_udiff_uassoc | udiffUassoc() | ✅ | Full implementation |
| 52 | array_uintersect | uintersect() | ✅ | Full implementation |
| 53 | array_uintersect_assoc | uintersectAssoc() | ✅ | Full implementation |
| 54 | array_uintersect_uassoc | uintersectUassoc() | ✅ | Full implementation |
| 55 | array_unique | unique() | ✅ | Full implementation |
| 56 | array_unshift | unshift() / prepend() | ✅ | Full implementation (mutating) |
| 57 | array_values | values() | ✅ | Full implementation |
| 58 | array_walk | walk() | ✅ | Full implementation (mutating) |
| 59 | array_walk_recursive | walkRecursive() | ✅ | Full implementation (mutating) |
| 60 | arsort | arsort() | ✅ | Full implementation (mutating) |
| 61 | asort | asort() | ✅ | Full implementation (mutating) |
| 62 | compact | compact() | ⚠️ | Not implementable (PHP scope limitations). Use: CoverArray::fromArray(compact(...)) |
| 63 | count | count() | ✅ | Implementation of Countable interface |
| 64 | current | current() | ✅ | Full implementation |
| 65 | end | end() | ✅ | Full implementation (mutating) |
| 66 | extract | extract() | ✅ | Full implementation |
| 67 | in_array | in() | ✅ | Full implementation |
| 68 | key | key() | ✅ | Full implementation |
| 69 | key_exists | keyExists() | ✅ | Full implementation (same as array_key_exists) |
| 70 | krsort | krsort() | ✅ | Full implementation (mutating) |
| 71 | ksort | ksort() | ✅ | Full implementation (mutating) |
| 72 | list | list() | ⚠️ | Not implementable (language construct). Use: list($a, $b) = $cover->getDataAsArray() |
| 73 | natcasesort | natcasesort() | ✅ | Full implementation (mutating) |
| 74 | natsort | natsort() | ✅ | Full implementation (mutating) |
| 75 | next | next() | ✅ | Full implementation (mutating) |
| 76 | pos | pos() | ✅ | Alias of current() |
| 77 | prev | prev() | ✅ | Full implementation (mutating) |
| 78 | range | range() | ✅ | Full implementation (static method) |
| 79 | reset | reset() | ✅ | Full implementation (mutating) |
| 80 | rsort | rsort() | ✅ | Full implementation (mutating) |
| 81 | shuffle | shuffle() | ✅ | Full implementation (mutating) |
| 82 | sort | sort() | ✅ | Full implementation (mutating) |
| 83 | uasort | uasort() | ✅ | Full implementation (mutating) |
| 84 | uksort | uksort() | ✅ | Full implementation (mutating) |
| 85 | usort | usort() | ✅ | Full implementation (mutating) |
Additional CoverArray Methods
| Method | Purpose | Access |
|---|---|---|
__clone() | Creates a shallow copy with deep cloning of immediate object properties | Magic |
__get() | Gets a property value using object property syntax | Magic |
__isset() | Checks if a property is set | Magic |
__serialize() | Serializes the object for serialization | Magic |
__set() | Sets a property value using object property syntax | Magic |
__toString() | Returns a string representation of the object | Magic |
__unserialize() | Unserializes the object from serialized data | Magic |
__unset() | Unsets a property | Magic |
clear() | Clears all data | Public |
copy() | Creates and returns a copy of the current object instance | Public |
each() | Applies a callback to each element and returns a new instance with preserved keys (immutable, non-recursive) | Public |
eachRecursive() | Recursively applies a callback to each element and returns a new instance (immutable, recursive) | Public |
fromArray() | Creates a CoverArray from a native PHP array | Public Static |
fromExplode() | Creates a CoverArray from a string using explode() | Public Static |
fromJson() | Creates a CoverArray instance from a JSON string | Public Static |
get() | Returns data by keys of the current object using dot notation | Public |
getData() | Returns the internal data array as-is without any conversion | Public |
getDataAsArray() | Returns the current object's data as a native PHP array | Public |
getIterator() | Returns an iterator for the array (IteratorAggregate interface) | Public |
implode() | Joins array elements with a string | Public |
isEmpty() | Checks if the array is empty | Public |
item() | Returns the collection element with the given index as the result | Public |
jsonSerialize() | Specifies data which should be serialized to JSON (JsonSerializable interface) | Public |
offsetExists() | Checks whether the specified offset exists in the array (ArrayAccess interface) | Public |
offsetGet() | Returns the value at the specified offset (ArrayAccess interface) | Public |
offsetSet() | Sets the value at the specified offset (ArrayAccess interface) | Public |
offsetUnset() | Unsets the value at the specified offset (ArrayAccess interface) | Public |
setData() | Sets the internal data for the CoverArray | Public |
toJson() | Converts the CoverArray to a JSON string | Public |
