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

v1.0.1 2026-02-06 05:10 UTC

This package is auto-updated.

Last update: 2026-02-06 05:13:00 UTC


README

Cover Array

Other languages:

State

Test Status

PHP Version Status
8.0 PHP 8.0
8.1 PHP 8.1
8.2 PHP 8.2
8.3 PHP 8.3
8.4 PHP 8.4
8.5 PHP 8.5

Code Coverage

codecov

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) vs array_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 FunctionCoverArray MethodStatusNotes
1array_allall()Implemented with polyfill for older PHP versions
2array_anyany()Implemented with polyfill for older PHP versions
3array_change_key_casechangeKeyCase()Full implementation
4array_chunkchunk()Full implementation
5array_columncolumn()Full implementation
6array_combinecombine()Full implementation (static method)
7array_count_valuescountValues()Full implementation
8array_diffdiff()Full implementation
9array_diff_assocdiffAssoc()Full implementation
10array_diff_keydiffKey()Full implementation
11array_diff_uassocdiffUassoc()Full implementation
12array_diff_ukeydiffUkey()Full implementation
13array_fillfill()Full implementation (static method)
14array_fill_keysfillKeys()Full implementation (static method)
15array_filterfilter()Full implementation
16array_findfind()Implemented with polyfill for older PHP versions
17array_find_keyfindKey()Implemented with polyfill for older PHP versions
18array_firstfirst()Implemented with polyfill for older PHP versions
19array_flipflip()Full implementation
20array_intersectintersect()Full implementation
21array_intersect_associntersectAssoc()Full implementation
22array_intersect_keyintersectKey()Full implementation
23array_intersect_uassocintersectUassoc()Full implementation
24array_intersect_ukeyintersectUkey()Full implementation
25array_is_listisList()Implemented with polyfill for older PHP versions
26array_key_existskeyExists()Full implementation
27array_key_firstkeyFirst()Uses built-in function
28array_key_lastkeyLast()Uses built-in function
29array_keyskeys()Full implementation
30array_lastlast()Implemented with polyfill for older PHP versions
31array_mapmap()Full implementation
32array_mergemerge()Full implementation
33array_merge_recursivemergeRecursive()Full implementation
34array_multisortmultisort()Full implementation (mutating)
35array_padpad()Full implementation
36array_poppop()Full implementation (mutating)
37array_productproduct()Full implementation
38array_pushpush() / append()Full implementation (mutating)
39array_randrand()Full implementation
40array_reducereduce()Full implementation
41array_replacereplace()Full implementation
42array_replace_recursivereplaceRecursive()Full implementation
43array_reversereverse()Full implementation
44array_searchsearch()Full implementation
45array_shiftshift()Full implementation (mutating)
46array_sliceslice()Full implementation
47array_splicesplice()Full implementation (mutating)
48array_sumsum()Full implementation
49array_udiffudiff()Full implementation
50array_udiff_assocudiffAssoc()Full implementation
51array_udiff_uassocudiffUassoc()Full implementation
52array_uintersectuintersect()Full implementation
53array_uintersect_assocuintersectAssoc()Full implementation
54array_uintersect_uassocuintersectUassoc()Full implementation
55array_uniqueunique()Full implementation
56array_unshiftunshift() / prepend()Full implementation (mutating)
57array_valuesvalues()Full implementation
58array_walkwalk()Full implementation (mutating)
59array_walk_recursivewalkRecursive()Full implementation (mutating)
60arsortarsort()Full implementation (mutating)
61asortasort()Full implementation (mutating)
62compactcompact()⚠️Not implementable (PHP scope limitations). Use: CoverArray::fromArray(compact(...))
63countcount()Implementation of Countable interface
64currentcurrent()Full implementation
65endend()Full implementation (mutating)
66extractextract()Full implementation
67in_arrayin()Full implementation
68keykey()Full implementation
69key_existskeyExists()Full implementation (same as array_key_exists)
70krsortkrsort()Full implementation (mutating)
71ksortksort()Full implementation (mutating)
72listlist()⚠️Not implementable (language construct). Use: list($a, $b) = $cover->getDataAsArray()
73natcasesortnatcasesort()Full implementation (mutating)
74natsortnatsort()Full implementation (mutating)
75nextnext()Full implementation (mutating)
76pospos()Alias of current()
77prevprev()Full implementation (mutating)
78rangerange()Full implementation (static method)
79resetreset()Full implementation (mutating)
80rsortrsort()Full implementation (mutating)
81shuffleshuffle()Full implementation (mutating)
82sortsort()Full implementation (mutating)
83uasortuasort()Full implementation (mutating)
84uksortuksort()Full implementation (mutating)
85usortusort()Full implementation (mutating)

Additional CoverArray Methods

MethodPurposeAccess
__clone()Creates a shallow copy with deep cloning of immediate object propertiesMagic
__get()Gets a property value using object property syntaxMagic
__isset()Checks if a property is setMagic
__serialize()Serializes the object for serializationMagic
__set()Sets a property value using object property syntaxMagic
__toString()Returns a string representation of the objectMagic
__unserialize()Unserializes the object from serialized dataMagic
__unset()Unsets a propertyMagic
clear()Clears all dataPublic
copy()Creates and returns a copy of the current object instancePublic
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 arrayPublic Static
fromExplode()Creates a CoverArray from a string using explode()Public Static
fromJson()Creates a CoverArray instance from a JSON stringPublic Static
get()Returns data by keys of the current object using dot notationPublic
getData()Returns the internal data array as-is without any conversionPublic
getDataAsArray()Returns the current object's data as a native PHP arrayPublic
getIterator()Returns an iterator for the array (IteratorAggregate interface)Public
implode()Joins array elements with a stringPublic
isEmpty()Checks if the array is emptyPublic
item()Returns the collection element with the given index as the resultPublic
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 CoverArrayPublic
toJson()Converts the CoverArray to a JSON stringPublic