vectorial1024/alof-lib

PHP array-like object functions library.

0.1.0 2023-11-30 16:49 UTC

This package is auto-updated.

Last update: 2024-04-30 00:46:18 UTC


README

stable phpunit downloads license php readthedocs

(This is a WIP project!)

PHP array-like object functions library ("alof-lib"). Type-hinted functions for array-like objects, just like those for native arrays. Think of this library as a polyfill of those useful functions for array-like objects, so that you may write clean code with array-like objects.

An array-like object ("ALO") is defined to be implements ArrayAccess and implements Traversable. Examples of array-like objects include:

A PHP array is NOT an ALO. It is still an array.

Latest version requires PHP 8.1+.

See the change log in the CHANGELOG.md file.

Notes and Disclaimers

  • ALO functions aim to be faithful user-land reproductions of their array function counterparts, but there might be slight differences between both sides
  • Some ALO functions may not make sense depending on your exact ALO implementation; use judgement before you use the ALO functions

Testing

This library uses PHPUnit for testing, which can be triggered from Composer. To test this library, run:

composer run-script test

Example Usage

Refer to the test cases under /tests for more examples, but for a minimal example:

use Vectorial1024\AlofLib\Alof;

$objKey = new stdClass();
$objKey->name = "foo";

// conveniently get the keys of the WeakMap (WeakMap becomes a "WeakHashSet" for objects)
$map = new WeakMap();
$map[$objKey] = "1";
$map[$objKey] = 2;
$map[$objKey] = "Hello World!";
$keys = Alof::alo_keys($map);
assert($keys === [$objKey]); // passes

// correctly get the keys of the SplObjectStorage (no more nasty foreach surprises!)
$splObjectStore = new SplObjectStorage();
$splObjectStore[$objKey] = "Hello World!";
$keys = Alof::alo_keys($splObjectStore);
assert($keys === [$objKey]); // passes