Download the PHP package dusank/knapsack without Composer
On this page you can find all versions of the php package dusank/knapsack. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download dusank/knapsack
More information about dusank/knapsack
Files in dusank/knapsack
Package knapsack
Short Description Collection library for PHP
License MIT
Homepage https://github.com/DusanKasan/Knapsack
Informations about the package knapsack
Knapsack
Collection pipeline library for PHP
Knapsack is a collection library for PHP >= 5.6 that implements most of the sequence operations proposed by Clojures sequences plus some additional ones. All its features are available as functions (for functional programming) and as a collection pipeline object methods.
The heart of Knapsack is its Collection class. However its every method calls a simple function with the same name that does the actual heavy lifting. These are located in DusanKasan\Knapsack
namespace and you can find them here. Collection is a Traversable implementor (via IteratorAggregate) that accepts Traversable object, array or even a callable that produces a Traversable object or array as constructor argument. It provides most of Clojures sequence functionality plus some extra features. It is also immutable - operations preformed on the collection will return new collection (or value) instead of modifying the original collection.
Most of the methods of Collection return lazy collections (such as filter/map/etc.). However, some return non-lazy collections (reverse) or simple values (count). For these operations all of the items in the collection must be iterated over (and realized). There are also operations (drop) that iterate over some items of the collection but do not affect/return them in the result. This behaviour as well as laziness is noted for each of the operations.
If you want more example usage beyond what is provided here, check the specs and/or scenarios. There are also performance tests you can run on your machine and see the computation time impact of this library (the output of these is included below).
Feel free to report any issues you find. I will do my best to fix them as soon as possible, but community pull requests to fix them are more than welcome.
Documentation
Check out the documentation (which is prettified version of this readme) at http://dusankasan.github.io/Knapsack
Installation
Require this package using Composer.
Usage
Instantiate via static or dynamic constructor
Work with arrays, Traversable objects or callables that produce Traversables
Basic map/reduce
The same map/reduce using Knapsack's collection functions
Get first 5 items of Fibonacci's sequence
If array or Traversable would be returned from functions that return an item from the collection, it can be converted to Collection using the optional flag. By default it returns the item as is.
Collections are immutable
Keys are not unique by design
It would harm performance. This is only a problem if you need to call toArray(), then you should call values() before.
Collection trait is provided
If you wish to use all the Collection methods in your existing classes directly, no need to proxy their calls, you can just use the provided CollectionTrait. This will work on any Traversable by default. In any other class you will have to override the getItems() method provided by the trait. Keep in mind that after calling filter or any other method that returns collection, the returned type will be actually Collection, not the original Traversable.
Performance tests
PHP 5.6
PHP 7.1.1
Constructors
These are ways how to create the Collection class. There is one default constructor and few named (static) ones.
new(iterable|callable $input)
The default constructor accepts array, Traversable or a callable that takes no arguments and produces Traversable or array. The use case for the callable argument is for example a Generator, which can not be rewound so the Collection must be able to reconstruct it when rewinding itself.
from(iterable|callable $input)
Collection::from is a static alias of the default constructor. This is the preferred way to create a Collection.
iterate(mixed $input, callable $function)
Returns lazy collection of values, where first value is $input and all subsequent values are computed by applying $function to the last value in the collection. By default this produces an infinite collection. However you can end the collection by throwing a NoMoreItems exception.
repeat(mixed $value, int $times = -1)
Returns a lazy collection of $value repeated $times times. If $times is not provided the collection is infinite.
range(int $start = 0, int $end = null, int step = 1)
Returns a lazy collection of numbers starting at $start, incremented by $step until $end is reached.
Operations
These are the operations (methods) provided by Collection class. For each one, there is a function with the same name in Knapsack namespace. The function has the same footprint as the method, except it has one extra argument prepended - the collection (array or Traversable).
Standard Iterator methods
It implements http://php.net/manual/en/class.iterator.php
append(mixed $item, mixed $key = null) : Collection
Returns a lazy collection of items of this collection with $item added as last element. If $key is not provided, its key will be the next integer in the sequence.
average() : int|float
Returns average of values in this collection.
combine(iterable $collection, bool $strict = false) : Collection
Combines the values of this collection as keys, with values of $collection as values. The resulting collection has length equal to the size of smaller collection. If $strict is true, the size of both collections must be equal, otherwise ItemNotFound is thrown. When strict, the collection is realized immediately.
concat(iterable ...$collections) : Collection
Returns a lazy collection with items from this collection followed by items from the collection from first argument, then second and so on.
contains(mixed $needle) : bool
Returns true if $needle is present in the collection.
countBy(callable $function) : Collection
Returns a collection of items whose keys are the return values of $function(value, key) and values are the number of items in this collection for which the $function returned this value.
cycle() : Collection
Returns an infinite lazy collection of items in this collection repeated infinitely.
diff(iterable ...$collections) : Collection
Returns a lazy collection of items that are in $collection but are not in any of the other arguments, indexed by the keys from the first collection. Note that the ...$collections are iterated non-lazily.
distinct() : Collection
Returns a lazy collection of distinct items. The comparison whether the item is in the collection or not is the same as in in_array.
drop(int $numberOfItems) : Collection
A form of slice that returns all but first $numberOfItems items.
dropLast($numberOfItems = 1) : Collection
Returns a lazy collection with last $numberOfItems items skipped. These are still realized, just skipped.
dropWhile(callable $function) : Collection
Returns a lazy collection by removing items from this collection until first item for which $function(value, key) returns false.
dump(int $maxItemsPerCollection = null, $maxDepth = null) : array
Dumps this collection into array (recursively).
- scalars are returned as they are,
- array of class name => properties (name => value and only properties accessible for this class) is returned for objects,
- arrays or Traversables are returned as arrays,
- for anything else result of calling gettype($input) is returned
If specified, $maxItemsPerCollection will only leave specified number of items in collection, appending a new element at end '>>>' if original collection was longer.
If specified, $maxDepth will only leave specified n levels of nesting, replacing elements with '^^^' once the maximum nesting level was reached.
If a collection with duplicate keys is encountered, the duplicate keys (except the first one) will be change into a format originalKey//duplicateCounter where duplicateCounter starts from 1 at the first duplicate. So [0 => 1, 0 => 2] will become [0 => 1, '0//1' => 2]
each(callable $function) : Collection
Returns a lazy collection in which $function(value, key) is executed for each item.
every(callable $function) : bool
Returns true if $function(value, key) returns true for every item in this collection, false otherwise.
except(iterable $keys) : Collection
Returns a lazy collection without the items associated to any of the keys from $keys.
extract(mixed $keyPath) : Collection
Returns a lazy collection of data extracted from $collection items by dot separated key path. Supports the wildcard. If a key contains \ or it must be escaped using \ character.
filter(callable $function = null) : Collection
Returns a lazy collection of items for which $function(value, key) returned true.
If $function
is not provided, \DusanKasan\Knapsack\identity
is used so every falsy value is removed.
find(callable $function, mixed $ifNotFound = null, bool $convertToCollection = false) : mixed|Collection
Returns first value for which $function(value, key) returns true. If no item is matched, returns $ifNotFound. If $convertToCollection is true and the return value is an iterable an instance of Collection will be returned.
first(bool $convertToCollection = false) : mixed|Collection
Returns first value in the collection or throws ItemNotFound if the collection is empty. If $convertToCollection is true and the return value is an iterable an instance of Collection will be returned.
flatten(int $depth = -1) : Collection
Returns a lazy collection with one or multiple levels of nesting flattened. Removes all nesting when no $depth value is passed.
flip() : Collection
Returns a lazy collection where keys and values are flipped.
frequencies() : Collection
Returns a collection where keys are distinct items from this collection and their values are number of occurrences of each value.
get(mixed $key, bool $convertToCollection = false) : mixed|Collection
Returns value at the key $key. If multiple values have this key, return first. If no value has this key, throw ItemNotFound
. If $convertToCollection is true and the return value is an iterable an instance of Collection will be returned.
getOrDefault(mixed $key, mixed $default = null, bool $convertToCollection = false) : mixed|Collection
Returns value at the key $key. If multiple values have this key, return first. If no value has this key, return $default. If $convertToCollection is true and the return value is an iterable an instance of Collection is returned.
groupBy(callable $function) : Collection
Returns collection which items are separated into groups indexed by the return value of $function(value, key).
groupByKey(mixed $key) : Collection
Returns collection where items are separated into groups indexed by the value at given key.
has(mixed $key) : bool
Checks for the existence of $key in this collection.
indexBy(callable $function) : Collection
Returns a lazy collection by changing keys of this collection for each item to the result of $function(value, key) for that key/value.
interleave(iterable ...$collections) : Collection
Returns a lazy collection of first item from first collection, first item from second, second from first and so on. Works with any number of arguments.
interpose(mixed $separator) : Collection
Returns a lazy collection of items of this collection separated by $separator item.
intersect(iterable ...$collections) : Collection
Returns a lazy collection of items that are in $collection and all the other arguments, indexed by the keys from the first collection. Note that the ...$collections are iterated non-lazily.
isEmpty() : bool
Returns true if is collection is empty. False otherwise.
isNotEmpty() : bool
Opposite of isEmpty
keys() : Collection
Returns a lazy collection of the keys of this collection.
last(bool $convertToCollection = false) : mixed|Collection
Returns last value in the collection or throws ItemNotFound if the collection is empty. If $convertToCollection is true and the return value is an iterable an instance of Collection is returned.
map(callable $function) : Collection
Returns collection where each value is changed to the output of executing $function(value, key).
mapcat(callable $mapper) : Collection
Returns a lazy collection which is a result of calling map($mapper(value, key)) and then flatten(1).
max() : mixed
Returns mthe maximal value in this collection.
min() : mixed
Returns mthe minimal value in this collection.
only(iterable $keys) : Collection
Returns a lazy collection of items associated to any of the keys from $keys.
partition(int $numberOfItems, int $step = 0, iterable $padding = []) : Collection
Returns a lazy collection of collections of $numberOfItems items each, at $step step apart. If $step is not supplied, defaults to $numberOfItems, i.e. the partitionsdo not overlap. If a $padding collection is supplied, use its elements asnecessary to complete last partition up to $numberOfItems items. In case there are not enough padding elements, return a partition with less than $numberOfItems items.
partitionBy(callable $function) : Collection
Creates a lazy collection of collections created by partitioning this collection every time $function(value, key) will return different result.
prepend(mixed $item, mixed $key = null) : Collection
Returns a lazy collection of items of this collection with $item added as first element. Its key will be $key. If $key is not provided, its key will be the next numerical index.
printDump(int $maxItemsPerCollection = null, $maxDepth = null) : Collection
Calls dump on $input and then prints it using the var_export. Returns the collection. See dump function for arguments and output documentation.
realize() : Collection
Realizes collection - turns lazy collection into non-lazy one by iterating over it and storing the key/values.
reduce(callable $function, mixed $start, bool $convertToCollection = false) : mixed|Collection
Reduces the collection to single value by iterating over the collection and calling $function(tmp, value, key) while passing $start and current key/item as parameters. The output of callable is used as $start in next iteration. The output of callable on last element is the return value of this function. If $convertToCollection is true and the return value is an iterable an instance of Collection is returned.
reduceRight(callable $function, mixed $start, bool $convertToCollection = false) : mixed|Collection
Like reduce, but walks from last item to the first one. If $convertToCollection is true and the return value is an iterable an instance of Collection is returned.
reductions(callable $reduction, mixed $start) : Collection
Returns a lazy collection of reduction steps.
reject(callable $filter) : Collection
Returns a lazy collection of items for which $filter(value, key) returned false.
replace(iterable $replacementMap) : Collection
Returns a lazy collection with items from this collection equal to any key in $replacementMap replaced for their value.
replaceByKeys(iterable $replacementMap) : Collection
Returns a lazy collection with items from $collection, but items with keys that are found in keys of $replacementMap are replaced by their values.
reverse() : Collection
Returns a non-lazy collection of items in this collection in reverse order.
second(bool $convertToCollection = false) : mixed|Collection
Returns the second item of $collection or throws ItemNotFound if $collection is empty or has 1 item. If $convertToCollection is true and the return value is an iterable it is converted to Collection.
shuffle() : Collection
Returns a collection of shuffled items from this collection
size() : int
Returns the number of items in this collection.
sizeIsBetween(int $fromSize, int $toSize) : bool
Checks whether this collection has between $fromSize to $toSize items. $toSize can be smaller than $fromSize.
sizeIs(int $size) : bool
Checks whether this collection has exactly $size items.
sizeIsGreaterThan(int $size) : bool
Checks whether this collection has more than $size items.
sizeIsLessThan(int $size) : bool
Checks whether this collection has less than $size items.
slice(int $from, int $to) : Collection
Returns a lazy collection of items which are part of the original collection from item number $from to item number $to inclusive. The items before $from are also realized, just not returned.
some(callable $function) : bool
Returns true if $function(value, key) returns true for at least one item in this collection, false otherwise.
sort(callable $function) : Collection
Returns collection sorted using $function(value1, value2, key1, key2). $function should return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
splitAt(int $position) : Collection
Returns a collection of lazy collections: [take($position), drop($position)].
splitWith(callable $function) : Collection
Returns a collection of lazy collections: [takeWhile($function(value, key)), dropWhile($function(value, key))].
sum() : int|float
Returns a sum of all values in this collection.
take(int $numberOfItems) : Collection
A form of slice that returns first $numberOfItems items.
takeNth(int $step) : Collection
Returns a lazy collection of every nth item in this collection
takeWhile(callable $function) : Collection
Returns a lazy collection of items from the start of the collection until the first item for which $function(value, key) returns false.
transform(callable $transformer) : Collection
Uses a $transformer callable on itself that takes a Collection and returns Collection. This allows for creating a separate and reusable algorithms.
toArray() : array
Converts the collection to array recursively. Obviously this is not lazy since all the items must be realized. Calls iterator_to_array internaly.
toString() : string
Returns a string by concatenating this collection's values into a string.
transpose(iterable $collection) : string
Returns a non-lazy collection by interchanging each row and the corresponding column. The input must be a multi-dimensional collection or an InvalidArgumentException is thrown.
zip(iterable ...$collections) : Collection
Returns a lazy collection of non-lazy collections of items from nth position from this collection and each passed collection. Stops when any of the collections don't have an item at the nth position.
Utility functions
These are the functions bundled with Knapsack to make your life easier when transitioning into functional programming.
identity(mixed $value)
Returns $value
compare(mixed $a, mixed $b)
Default comparator function. Returns a negative number, zero, or a positive number when $a is logically 'less than', 'equal to', or 'greater than' $b.
compare(1, 2); //-1
increment(int $value)
Returns value of $value incremented by one.
increment(0) === 1; //true
decrement(int $value)
Returns value of $value decremented by one.
decrement(2) === 1; //true