Small library providing some functional programming tools for PHP, based on Rambda

Overview

Build Status Version Coverage Status Mutation testing badge Latest Stable Version Latest Unstable Version Total Downloads License PHP Version Require

Functional library for PHP.

Features:

  • set of useful functions helpful in functional programming
  • all functions are automatically curried
  • every array can be wrapped with special class which allows for method chaining
  • first param is always function and the data to be operated will be last param

Table of contents

Installation

To install run:

composer require wojciech.nawalaniec/phlambda

Usage

All functions and constants are in one namespace, so it won't create any conflict with existing ones in your project or other libraries. You can simply import namespaces with alias (for simplification), like this:

use Wojciech\Phlambda as f;

f\all(f\above(2), [1, 2, 3, 4]);

You can import one or few functions using import like this:

use function Wojciech\Phlambda\{all, above};

all(above(2), [1, 2, 3, 4]);

There are also constants which can be used in places accepting callbacks, because PHP will resolve them as functions:

use function Wojciech\Phlambda\map;
use const Wojciech\Phlambda\toString;

map(toString, [1, 2, 3]);

If you have some array and wish to perform multiple, chained operations on it. You can wrapp it with special object with _() function:

use function Wojciech\Phlambda\{_, below, concat};
use const Wojciech\Phlambda\toString;

_($someArray)
    ->filter(below(30))
    ->map(toString) // you can use constant which will be resolved as callable by PHP
    ->reduce(concat(), ''); // or you can call function without params because all functions all curried

If you wish to have more readable code you can use a static method from that class instead: Wrapper::wrap($array).

If you don't want to use objects you can use just functions. Wrapper's methods are just delegates to those functions, and exists only for chaining purposes.

Docs

Here you can find documentation.

Currying

In this library all function are automatically curried. If you don't know what curry functions let me try to change it. According to Wikipedia:

In mathematics and computer science, currying is the technique of converting a function that takes multiple arguments into a sequence of functions that each takes a single argument.

Let's see an example:

// we can use reduce function normally like this:
$array = ['a', 'b', 'c'];
$result = reduce(\Wojciech\Phlambda\concat, '', $array); // $result = 'abc'

// and we can use it like cirrying function:
$concat = reduce(\Wojciech\Phlambda\concat, ''); // now it will return callback accepting last param from reduce - an array
$result = $concat($array); // $result = 'abc'

TODO

  • implement more methods
  • add placeholders for curry functions - it seems as interesting thing to do

Development Guides

  • all functions must be tested
  • all functions must be automatically curring
  • all functions must be implemented in Wrapper (it's testd)
    • if function shouldn't be e.g. it's predicate or some math operation attribute ShouldNotBeImplementedInWrapper must be added
  • all function must be documented
    • because ...$v is used for curring, @param should be used to document order and type of params
    • type declarations (both return and arguments) must be used
    • similar functions should be linked with @see
    • at least one example must be given
      • examples should be inside
         tags
  • there must be constant with a function name (with whole namespace) like e.g. const map = 'Wojciech\Phlambda\map'
  • if function name is PHP reserved key-word it must be prefixed with _

Backstory

PHP was not designed as functional programming language, that's one thing I'm sure. We can create and use anonymous functions, and in 7.4 we even got arrow functions fn () =>. Language itself is providing us with some functions like array_map() etc. where we can pass an array and some callable to perform some operations on the input. But its... so cumbersome.

One day at the company my friend joked about PHP and said that it's sad we can't do something like this in PHP:

someArray.every(below(30));

I thought for a while, and respond with something like this:

function below(int $val): callable
{
    return fn(int $v) => $v < $val;
}

function every(array $a, callable $fn): array
{
    return array_filter($a, $fn);
}

$arr = [1, 2, 3, 4];
every($arr, below(3));

Both examples are similar, but we can see that with PHP solution we have no way of chaining methods together, also we must write most of that method our selves. After while another idea came up to my mind. We could leverage OOP and create class which implements \ArrayAccess so it can be considered array like, and have all that nice methods we can chain together. I thought about something like this:

$arrayObject
    ->filter(below(30))
    ->sum();

It seemed as a great weekend project so here it is.

There are some great functional libraries for JS, but one (pointed by earlier mentioned friend) seemed interesting. It's Ramda. It's interesting because it has all function automatically curried, and it adds some complexity to that project.

Comments
  • Spoko to wygląda, propozycja paru usprawnień

    Spoko to wygląda, propozycja paru usprawnień

    1. Nie potrzebujesz composer.lock.
    2. W pliku .travis.yml możesz testować wobec PHP 8.0 i 8.1 żeby upewnić się, że działa tu i tu. Tak samo na niskich i wysokich zależnościach.
    3. Możesz dodać .gitattributes i wyciąć rzeczy niepotrzebne zaciągającym paczkę (np. testy), coś jak https://github.com/symfony/framework-bundle/blob/5.4/.gitattributes
    4. Pomyśl nad licencją MIT, bo GPL uniemożliwi zaciąganie paczki w komercyjnych projektach ze względu na "wirusowość" licencji GPL.
    opened by spiechu 1
  • Make Wrapper Traversable

    Make Wrapper Traversable

    Wrapper is now only implementing ArrayAccess. This doesn't allow to use it in foreach which is a bummer. Also implementing Countable could be a good idea.

    enhancement good first issue 
    opened by wnnawalaniec 0
  • 🍛  `curryN` function

    🍛 `curryN` function

    I've added already curry, curry2 and curry3 functions because they were needed to write other functions. I think it would be cool to add curryN like function.

    enhancement good first issue 
    opened by wnnawalaniec 0
  • Curry placeholders

    Curry placeholders

    Ramda has those cool feature that you can use placeholders in currying functions. I wish to add same functionality so you can write:

    $concater = reduce(concat, __, ''); // assign currying function with first and third argument given, and expect only second
    $concater(['a', 'b', 'c']); // will return 'abc'
    ...
    $concater(['x', 'y', 'z']); // will return 'xyz'
    
    enhancement 
    opened by wnnawalaniec 0
  • Constants generation tool

    Constants generation tool

    Because adding constants with functions names can be easily automated and is dull task I added tool for generating those, which can be used with simple command: make generate-constants This will add file ./src/constants.php or replace it if exists with all functions in namespace.

    opened by wnnawalaniec 0
Releases(v0.1.0)
  • v0.1.0(Dec 2, 2022)

    Features:

    • added curyring functions
    • added placeholder object to omit some arguments in currying function

    Full Changelog: https://github.com/wnnawalaniec/phlambda/compare/v0.0.7...v0.0.9

    Source code(tar.gz)
    Source code(zip)
  • v0.0.9(Jan 14, 2022)

    Features:

    • made Wrapper both Traversable and Countable
    • added clamp(), dropLastWhile(), endsWith()
    • moved all constants to single file
    • added changelog
    • added tool for generating that file

    Fixes:

    • license in composer file

    Full Changelog: https://github.com/wnnawalaniec/phlambda/compare/v0.0.7...v0.0.9

    Source code(tar.gz)
    Source code(zip)
  • v0.0.7(Jan 11, 2022)

    Features:

    • changed license to MIT
    • moved all functions to namespace
    • added logical functions: _and, _or, not, either, neither, both
    • added array functions: map, flatMap, diff, filter, flat
    • added string functions: startsWith, matches
    • added test cases checking some project postulates
    • added constants with functions names so it can be used in places expecting callable without need of writing string with whole namespace:
    use function Wojciech\Phlambda\map;
    use const Wojciech\Phlambda\toString;
    
    map(toString, [1, 2, 3]);
    

    Fixes:

    • added missing docs
    • added missing test cases

    Full Changelog: https://github.com/wnnawalaniec/phlambda/compare/v0.0.1...v0.0.7

    Source code(tar.gz)
    Source code(zip)
Owner
Wojciech Nawalaniec
I'm senior PHP developer working at polish company making software for education. I've been programming since I was 13, starting with C++ and Java.
Wojciech Nawalaniec
A story about SQLinject and a demonstration of some vulnerabilities and tools

Предысловие Если не умру,буду дальше развивать эту тему Идея которая пришла мне в голову,<<А почему бы не рассказать об уязвимостях SQL?>>.Поэтому я б

null 0 Jun 11, 2022
Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics (functional) API that doesn't cause vendor lock-in.

Metrics Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics API that doesn't cau

Benjamin Eberlei 311 Nov 20, 2022
A Finite State Machine System based on Chapter 3.1 of Game Programming Gems 1 by Eric Dybsand

A Finite State Machine System based on Chapter 3.1 of Game Programming Gems 1 by Eric Dybsand,Written by Roberto Cezar Bianchini, July 2010 ported to php by MrFerrys.

null 4 Apr 18, 2022
This example shows how to use Anychart library with the PHP programming language, Laravel framework and MySQL database.

PHP basic template This example shows how to use Anychart library with the PHP programming language, Laravel framework and MySQL database. Running To

AnyChart Integrations and Templates 23 Jul 17, 2022
Small convention based CQRS library for PHP

LiteCQRS for PHP Small naming-convention based CQRS library for PHP (loosely based on LiteCQRS for C#) that relies on the MessageBus, Command, EventSo

Benjamin Eberlei 560 Nov 20, 2022
A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

Jan Schädlich 69 Dec 18, 2022
Skosmos is a web-based tool providing services for accessing controlled vocabularies, which are used by indexers describing documents and searchers looking for suitable keywords.

Skosmos is a web-based tool providing services for accessing controlled vocabularies, which are used by indexers describing documents and searchers looking for suitable keywords.

National Library of Finland 195 Dec 24, 2022
A collection of type-safe functional data structures

lamphpda A collection of type-safe functional data structures Aim The aim of this library is to provide a collection of functional data structures in

Marco Perone 99 Nov 11, 2022
N2Web turns your Notion HTML export into a fully functional static website

Notion2Web N2Web turns your Notion HTML export into a fully functional static website. What is Notion? Notion is an online tool. But I can't tell you

Lars Lehmann 15 Nov 23, 2022
Simple libary for functional programing paradigm with arrays.

rodrigodornelles/php-array-lib simple libary for functional programing paradigm with arrays Features Test driven development style (TDD) PHP version c

null 10 Nov 28, 2022
WARNING! This software is currently non-functional. - A system which makes installing Jexactyl far, far easier.

Jexactyl Assistant A system which makes installing Jexactyl far, far easier. WARNING ?? This software is currently in heavy alpha testing and WILL NOT

Jexactyl 7 Nov 14, 2022
Sitepackage for TYPO3 CMS that adheres to the recommended standards, maps all conceivable functional areas and contains examples for common use cases.

TYPO3 CMS Sitepackage This sitepackage sticks as closely as possible to the recommended standard and maps all conceivable functional areas. There are

Eric Bode 3 Dec 18, 2022
PHP library providing retry functionality with multiple backoff strategies and jitter support

PHP Backoff Easily wrap your code with retry functionality. This library provides: 4 backoff strategies (plus the ability to use your own) Optional ji

Signature Tech Studio 145 Dec 21, 2022
MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query and get result in a fastest way

Mysql Optimizer mysql optimizer also known as MOP is a php query handling and manipulation library providing easy and reliable way to manipulate query

null 2 Nov 20, 2021
A PHP library providing ISO 3166-1 data

league/iso3166 A PHP library providing ISO 3166-1 data. What is ISO 3166-1 ISO 3166-1 is part of the ISO 3166 standard published by the International

The League of Extraordinary Packages 555 Dec 21, 2022
Tiny PHP library providing retry functionality with multiple backoff strategies and jitter support

JBZoo / Retry 4 retry strategies (plus the ability to use your own) Optional jitter / randomness to spread out retries and minimize collisions Wait ti

JBZoo Toolbox 6 Dec 19, 2022
Simple game server with php without socket programming. Uses the Api request post(json).

QMA server Simple game server with php without socket programming. Uses the Api request post(json). What does this code do? Register the user as a gue

reza malekpour 3 Sep 4, 2021
This is a plugin written in PHP programming language and running on the PocketMine platform that works stably on the API 3.25.0 platform

This is a plugin written in PHP programming language and running on the PocketMine platform that works stably on the API 3.25.0 platform. It allows you to hear the sound

Thành Nhân 10 Sep 27, 2022
A repository for showcasing my knowledge of the PHP programming language, and continuing to learn the language.

Learning PHP (programming language) I know very little about PHP. This document will list all my knowledge of the PHP programming language. Basic synt

Sean P. Myrick V19.1.7.2 2 Oct 29, 2022