Download the PHP package pinkcrab/function-constructors without Composer
On this page you can find all versions of the php package pinkcrab/function-constructors. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download pinkcrab/function-constructors
More information about pinkcrab/function-constructors
Files in pinkcrab/function-constructors
Package function-constructors
Short Description A collection of functions to make working with the standard php library a little easier for function composition. Allows the creation of partially applied library functions, to work as close to pure fucntions as possible.
License GPL-2.0-or-later
Homepage https://pinkcrab.co.uk
Informations about the package function-constructors
The PinkCrab FunctionConstructors library.
This library provides a small selection of functions for making functional programming a little cleaner and easier in php.
Setup
Can be included into your project using either composer or added manually to your codebase.
Via Composer
$ composer require pinkcrab/function-constructors
Via Manual Loader
If you wish to use this library within WordPress or other PHP codebase where you do not or cannot use composer, you can use the FunctionsLoader class. Just clone the repo into your codebase and do the following.
All of our functions are namespaced as PinkCrab\FunctionConstructors\{lib}. So the easiest way to use them is to use with an alias. Throughout all the docs on the wiki we use the following aliases.
Usage
At its core, the Function Constructors library is designed to make using PHP easier to use in a functional manor. With the use of functions compose() and pipe() its possible to construct complex functions, from simpler ones.
Function Composition and Piping
pipe()
PLEASE NOTE THIS HAS CHANGED IN VERSION 2.0.0, using
compose()is now the preferred method.
Using pipe(mixed $value, callable ...$callables) and pipeR() *, allows you to pass a value through a chain of callables. The result of the 1st function, is passed as the input the 2nd and so on, until the end when the final result is returned.
The rest of this library makes it easier to use standard php functions as callables, by defining some of the parameters up front.
compose()
Piping is ideal when you are working with a single value, but when it comes to working with Arrays or writing callbacks, compose() is much more useful.
compose(callable ...$callables) , composeR(callable ...$callables) , composeSafe(callable ...$callables) and composeTypeSafe(callable $validator, callable ...$callables) all allow you to create custom Closures.
You can use
composeTypeSafe()if you want to pass the return of each callable through a validator before being passed to the next. If the validator fails, the rest of the chain will be skipped and null will be returned.
Working with Records
It is possible to work with the properties of Records (arrays and objects). Indexes or Properties can be checked, fetched and set using some of the GeneralFunctions .
Reading Properties
You can check if a property exists, get its value or compare it an defined value.
pluckProperty()can also be used if you need to traverse nested properties/indexes of either arrays or objects also handlesArrayAccessobjects, set with array syntax see example oncompose()
Writing Properties
Its also possible to write properties of objects and set values to indexes in arrays using the setProperty() function. More complex structures can also be created using the Record Encoder
String Functions
Much of the string functions found in this library act as wrappers for common standard (PHP) library functions, but curried to allow them to be easier composed with.
String Manipulation
There is a collection of functions with make for the concatenation of strings.
String Contents
There is a collection of functions that be used to check the contents of a string.
Str\isBlank()can be used when composing a function, thanks to the Functions::isBlank constant.
Sub Strings
There is a series of functions that can be used to work with substrings.
See more of the Strings functions on the wiki
Number Functions
Much of the number functions found in this library act as wrappers for common standard (PHP) library functions, but curried to allow them to be easier composed with.
Basic Arithmetic
You can do some basic arithmetic using composable functions. This allows for the creation of a base value, then work using the passed value.
All these functions allow the use of
INTorFLOATonly, all numerical strings must be cast before being used. Will throwTypeErrorotherwise.
Multiple and Modulus
It is possible to do basic modulus operations and working out if a number has a whole factor of another.
Array Functions
As you can imagine there are a large number of functions relating to arrays and working with them.
Map
This library contains a large number of variations of array_map , these can all be pre composed, using the other functions to be extremely powerful and easy to follow.
There is
flatMap()andmapWith()also included, please see the wiki.
Filter and Take
There is a large number of composible functions based around array_filter() . Combined with a basic set of take*() functions, you can compose functions to work with lists/collections much easier.
Filter is great if you want to just process every result in the collection, the
take()family of functions allow for controlling how much of an array is filtered
Fold and Scan
Folding or reducing an a list is a pretty common operation and unlike the native array_reduce you have a little more flexibility.
You also have access to
foldR()andscanR()which will iterate through the array backwards.
Grouping and Partitioning
Function Constructor has a number of functions which make it easy to group and partition arrays
It is possible to chunk and split arrays, see the wiki for more.
Sorting
The native PHP sort functions are tricky with a functional approach, as they sort via reference, rather than by a return value. The Function Constructor library covers all native sorting as partially applied functions.
Iterable support (v1.0.0+)
From 1.0.0 onwards, every data-transforming function in the Arrays\ namespace accepts any iterable — arrays, Generators, Iterators, and any other Traversable. Two output contracts apply:
- Array in → array out. Existing call sites keep returning arrays with identical shape. No breakage.
- Generator (or other Traversable) in → Generator out for the lazy functions; materialised result (array / int / bool / string / object) for terminal functions.
This lets you feed a compose / pipe chain a lazy source and keep it lazy end-to-end, until a terminal step collapses it:
Which functions are lazy?
| Category | Functions |
|---|---|
| Lazy (yield Generator for iterable input) | append, prepend, tail, head (early-exit), map, mapKey, mapWith, mapWithKey, filter, filterKey, filterAnd, filterOr, filterMap, take, takeUntil, takeWhile, zip, chunk, column, flatMap, flattenByN, scan, scanR |
| Short-circuit terminal (don't fully consume when they can bail early) | filterFirst, filterAll, filterAny, head |
| Full-consume terminal (materialise to produce a result) | last, takeLast, filterLast, filterCount, partition, groupBy, toString, toObject, toJson, sumWhere, pick, replace, replaceRecursive, fold, foldR, foldKeys, all sort variants |
Caveats
- Generators are single-shot. Once exhausted they cannot be rewound. Iterating a pipeline result twice yields empty on the second pass — this is a PHP Generator fact of life, not a library choice.
- Infinite Generators work with early-exit pipelines (
head,take,filterFirst,filterAllon first false,filterAnyon first true). They hang forever with full-consume terminals (sort,fold,groupBy, etc.) — that's your call, not ours. - Key collisions when materialising a Generator to an array (inside terminal fns) follow PHP's native behaviour: duplicate keys overwrite earlier values.
tailon an empty Generator yields an empty Generator rather than returningnull(the array-path behaviour for empty input). The array path is unchanged.
Contributions
If you would like to contribute to this project, please feel to fork the project on github and submit a pull request.
For more details, please read the wiki
Changes
-
1.0.0
- New Functions
Strings\digit()— replacesStrings\decimalNumber().Strings\similar()— replacesStrings\similarAsBase()/Strings\similarAsComparison().Strings\compare().Strings\countChars()now has mode constants (CHAR_COUNT_ARRAY,CHAR_COUNT_ARRAY_UNIQUE,CHAR_COUNT_ARRAY_UNUSED).Arrays\last()— returns the last element of an array.Arrays\append()— replacesArrays\pushTail().Arrays\prepend()— replacesArrays\pushHead().Arrays\pick()— picks a subset of keys from an array.GeneralFunctions\sideEffect()— runs a callable for its side effect and returns the input unchanged; handy for debug/log taps in compose/pipe chains.- Breaking Changes — all deprecated functions removed
- Typo-alias functions removed:
Strings\decimialNumber()→ useStrings\digit()Strings\similarAsComparisson()→ useStrings\similar()Strings\firstPosistion()→ useStrings\firstPosition()Strings\lastPosistion()→ useStrings\lastPosition()- Previously-deprecated functions removed:
Strings\decimalNumber()→ useStrings\digit()Strings\similarAsBase()→ useStrings\similar()Strings\similarAsComparison()→ useStrings\similar()Arrays\pushHead()→ useArrays\prepend()Arrays\pushTail()→ useArrays\append()GeneralFunctions\toArray()→ useObjects\toArray()Arrays\tail()now works as expected, returning the array without the first element.Strings\allowTags()now accepts an array of allowed tags even for pre PHP 7.4.- Iterable support
- Every data-transforming
Arrays\*function now accepts anyiterable— arrays,Generators,Iterators, anyTraversable— not justarray. See the "Iterable support" section above for the full contract, the lazy/terminal classification, and the gotchas (single-shot Generators, infinite streams, key collisions,tailon empty). - Lazy functions (
map,filter,take,chunk,zip,flatMap,scan, …) return aGeneratorforTraversableinput and anarrayforarrayinput — pipelines stay lazy end-to-end when the source is lazy, and fully backward-compatible when the source is an array. - Other Changes
- Made
Arrays\filterFirst()andArrays\filterLast()more efficient. - Bumped dev deps: phpstan
^1.0 || ^2.0, phpunit^7.5 || ^8.5 || ^9.6, phpunit-polyfills^1.0 || ^2.0 || ^4.0. - CI matrix expanded to PHP 7.1 through 8.5; Codecov upload restricted to the PHP 8.5 job.
-
0.2.0 -
- New Functions
Numbers\isMultipleOf()Numbers\isFactorOf()Strings\isBlank()Strings\splitByLength()GeneralFunctions\ifThen()GeneralFunctions\ifElse()GeneralFunctions\composeR()Arrays\fold()Arrays\foldR()Arrays\foldKey()Arrays\scan()Arrays\scanR()Arrays\take()Arrays\takeLast()Arrays\takeUntil()Arrays\takeWhile()Arrays\filterAny()Arrays\filterAll()Arrays\mapWithKey()Objects\isInstanceOf()Objects\implementsInterface()Objects\toArray()Objects\usesTrait()Objects\createWith()- Breaking Changes
GeneralFunctions\pipe()&GeneralFunctions\pipeR()have now changed and are no longer alias forcompose()GeneralFunctions\setProperty()now takes the property argument when creating the Closure.Strings\tagWrap()has been removedStrings\asUrl()has been removedStrings\vSprintf()has has its arguments reversed.Strings\split()is now a wrapper for explode() and the existingStrings\split()has been renamed toStrings\splitByLength()- Other Changes
- Constants added using the
Functionsclass-name,Functions::isBlankcan be used as a string for a callable. GeneralFunctions\toArray()has been moved toObjects\toArray(),Objects\toArray()is now an alias forGeneralFunctions\toArray()
-
0.1.2 - Added
Arrays\zip() - 0.1.3 - Added
Arrays\filterKey()
