An open API service indexing awesome lists of open source software.

https://github.com/phpfn/pipe

[READONLY] Library for implementing function call chains
https://github.com/phpfn/pipe

chain functional php pipe

Last synced: 9 months ago
JSON representation

[READONLY] Library for implementing function call chains

Awesome Lists containing this project

README

          

# Pipe

Object-oriented pipe operator implementation based
on [RFC Pipe Operator](https://wiki.php.net/rfc/pipe-operator).

## Installation

Library can be installed into any PHP application:
- Using [`Composer`](https://getcomposer.org/) dependency manager
- [The Force](https://www.youtube.com/watch?v=o2we_B6hDrY) for the Jedi Developers

```sh
$ composer require phpfn/pipe
```

In order to access library make sure to include `vendor/autoload.php`
in your file.

```php
ucwords(_)
->preg_replace('/\s+/u', '', _)
->preg_replace('/(.)(?=[A-Z])/u', '$1_', _)
->strtolower(_)
->var_dump;
//
// string(11) "hello_world"
//
```

### Another Example

See: [https://wiki.php.net/rfc/pipe-operator#file_collection_example](https://wiki.php.net/rfc/pipe-operator#file_collection_example)

```php
scanDir($arg)
->array_filter(_, fn($x): bool => $x !== '.' && $x !== '..')
->array_map(fn($x): string => $arg . '/' . $x, _)
->use('namespaced\func')->get_file_arg
->array_merge($result, _);
```

## Working With Value

To pass a value as an argument to a function, use the
underscore (`_`) character:

```php
str_replace('o', '', _)
->var_dump; // "hell"
```

You can omit parentheses if only one argument is used:

```php
is_array
->var_dump; // bool(false)
```

To get the value, use one of the options:

```php
strtoupper;

var_dump($context);
// object(Fun\Pipe\Pipe)#8 (1) { ... }

var_dump($context());
// string(5) "HELLO"
```

## Working With Namespace

Let's take a simple example of such code:

```php
namespace {
function foo() { return __FUNCTION__; }
}

namespace Example {
function foo() { return __FUNCTION__; }
}
```

Let's try to manage the namespace:

```php
$context = pipe()->use('Example')->foo;

echo $context(); // 'Example\\foo'

$context = $context->foo;

echo $context(); // 'foo'
```

Please note that the `use` function applies only to the subsequent function,
all further operations performed in the current context:

```php
pipe()
->use('Some\\Namespace')->foo // Call "\Some\Namespace\foo()"
->foo // Call "\foo()"
;
```

In order to perform several operations in another namespace, use an anonymous
function as the second `use` argument.

```php
pipe()
->use('Some\\Namespace', fn($pipe) =>
$pipe
->a // Call "\Some\Namespace\a()"
->b // Call "\Some\Namespace\b()"
)
->a // Call "a()"
;
```

> Note that the behavior of the `->use()` method differs depending on whether
> the second argument is passed.