Download the PHP package somnambulist/collection without Composer
On this page you can find all versions of the php package somnambulist/collection. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download somnambulist/collection
More information about somnambulist/collection
Files in somnambulist/collection
Package collection
Short Description Collection implementation with no dependencies.
License MIT
Informations about the package collection
Somnambulist Collection Library
Somnambulist Collection provides a framework for making collections and pseudo sets of your own. It has been completely re-worked from the previous versions into a set of behaviours (traits) and some common interfaces grouped around function.
The basic "Collection" is an interface that extends ArrayAccess, IteratorAggregate and Countable; and adds Arrayable and Jsonable as common requirements. Then the basic methods are:
From this, additional functionality is added by interface and traits - or implement your own. The goal is to allow for a set of small, re-usable, well tested functions that can be combined to provide the functionality you need, instead of a single monolithic collection class that does everything and more.
Of course out of the box, several standard implementations are included.
This is heavily inspired by Doctrine ArrayCollection and of course Laravel Collection along with ideas from Lithium framework, ez Components, CakePHP and more.
If you see something missing or have suggestions for other methods, submit a PR or ticket! Adding functions is easy with the trait system and if you think that the groupings need work, suggest a better name!
Change History
- V3 Deprecations, API changes
- V4 Deprecations, API changes
- V5 Deprecations, API changes
Requirements
- PHP 8.0+
- ext-json for JSON export
Installation
Install using composer, or checkout / pull the files from github.com.
- composer require somnambulist/collection
Contributing
Contributions are more than welcome! Whether doc improvements, new methods or bug fixes. In all cases, fork the repository, make a branch then submit a PR - the usual GitHub flow.
Please consider the following:
- the minimum version of PHP is 8.0
- traits should not specify a return type but must include a docblock return type
- return types for the Collection must be
static
to allow runtime resolution - all trait methods must have docblocks - these are converted to docs
- if a trait uses code from elsewhere, it should be attributed whenever possible
- consider the type of operation and if it will work in a Set or a Frozen collection
- tests should be included
Remember that the Collection could be a Set or Frozen, so often it is necessary to operate on the values and then create a new collection after processing. See the current implementations for examples.
Built-in Collections
There are several types of collection that all implement the Collection interface with varying levels of functionality:
- SimpleCollection - a very basic, Doctrine ArrayCollection like style collection
- MutableCollection - more like Laravel Collection, supports dot notation accessing
- FrozenCollection - more like a Symfony Frozen ParameterBag, but more, with dot notation
- MutableSet - a pseudo set that does not allow duplicate values, but does allow string keys.
There's no frozen set, but if you freeze a MutableSet; you have yourself a FrozenSet.
Usage
Instantiate with an array or other collection of items:
Freeze changes to a collection:
Use a custom Immutable collection class:
Dot Access
Dot access is available on:
- has*
- get
- extract
- aggregate functions
For example: users.*.name
would fetch the name from all elements in the users key space. Dot access
can call into:
- arrays
- Collections
- public object properties
- object return methods e.g.:
name
would be translated toname()
- object
get
methods e.g:name
would be translated togetName()
If the key name uses snake casing e.g.: user_address, this will be converted to UserAddress for method access checks.
A default can be supplied with get()
that if the specified key does not exist, it will be used instead.
The default can be a closure. Note: that this will be called for all elements e.g: users.*.age
with a
default that returned 0
, would return 0 for all matching users without an age present.
Key walking is implemented in a standalone class allowing it to be re-used in other classes. This functionality
is based on Laravel's data_get()
and Arr::pluck()
, modified to support getter methods and default handling
when extracting from objects.
Proxy Helpers
New in v4 is an expansion of the run/map proxies used to make operations across the set. Now additional proxies can be bound to virtual properties that can be accessed at runtime. This allows for additional custom behaviour or the creation of mini Domain Specific Languages within the collection.
It is recommended when adding additional proxy options, that this is done in a child class of the collection
so that the options can be documented using @property-read
declarations in the class docblock. By default
run
and map
are pre-bound in the built-in collections, however these can be overridden if necessary.
Proxies are lazy instantiated when accessed so should have a minimal impact on performance. For most cases the proxy is mapped by the full qualified class name to an alias, but for more complex construction a closure can be used.
The proxy can be called by:
$collection->proxy(<alias>)->someMethod()
$collection-><alias>->someMethod()
For example: to run the method setDateTo()
on a collection of objects that have this method:
$collection->run->setDateTo(new DateTime())
or$collection->proxy('run')->setDateTo(new DateTime())
Method Index
The collection behaviour docs are generated from the source code and are available in the docs
folder.
Factory Methods
On the collection class
collect()
create a new Collection staticallycreate()
create a new Collection statically
As helpers in the FactoryUtils
createFromIniString()
create a Collection from an ini style stringcreateFromString()
split an encoded string into a CollectioncreateFromUrl()
given a URL returns a Collection after usingparse_url()
createFromUrlQuery()
converts a URL query string to a Collection usingparse_str()
createWithNestedArrayFromKey
converts a key likeuser.addresses.home
to a nested collectionexplode()
explode a string into a Collection
Methods by Group
Aggregates | Assertable | Comparable | Exportable | Filterable | Mappable |
---|---|---|---|---|---|
average | assert | diff | jsonSerialize | filter | collapse |
max | diffUsing | toArray | matching | flatMap | |
median | diffAssoc | toJson | notMatching | flatten | |
min | diffAssocUsing | toQueryString | reject | map | |
modal | diffKeys | toString | except | mapInto | |
sum | diffKeysUsing | serialize | has | reduce | |
countBy | intersect | unserialize | hasAllOf | ||
intersectByKeys | hasAnyOf | ||||
hasNoneOf | |||||
keys | |||||
keysMatching | |||||
only | |||||
with | |||||
without | |||||
matchingRule |
Mutable | Partitionable | Queryable | Runnable | String Helpers |
---|---|---|---|---|
add | groupBy | all | each | capitalize |
append | partition | contains | pipe | lower |
concat | slice | doesNotContain | pipeline | trim |
combine | splice | extract | run | upper |
clear | find | |||
combine | findLast | |||
fill | first | |||
fillKeysWith | get | |||
flip | last | |||
merge | has | |||
pad | random | |||
pop | removeEmpty | |||
prepend | removeNulls | |||
push | sort | |||
remapKeys | sortBy | |||
remove | value | |||
replace | values | |||
replaceRecursively | ||||
reverse | ||||
set | ||||
shift | ||||
shuffle | ||||
union | ||||
unset | ||||
when |
Magic Methods & PHP Interface Methods
- getIterator
- offsetGet
- offsetExists
- offsetSet
- offsetUnset
- __get
- __isset
- __set
- __set_state
- __unset
All versions of collection with dependencies
ext-json Version *