Skip to content

Commit 73006eb

Browse files
authored
Merge pull request #105 from ilario-pierbattista/ilario-pierbattista-pipe-function
Introduction of the pipe function inspired by fp-ts
2 parents a1a4edc + 0d05f26 commit 73006eb

File tree

2 files changed

+68
-2
lines changed

2 files changed

+68
-2
lines changed

src/Functional/miscellaneous.php

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,8 @@ function compose(callable $a, callable $b)
8787
* Composition starts from left.
8888
*
8989
* <code>
90-
* compose('strtolower', 'strtoupper')('aBc') ≡ 'ABC'
91-
* strtouppser(strtolower('aBc')) ≡ 'ABC'
90+
* pipeline('strtolower', 'strtoupper')('aBc') ≡ 'ABC'
91+
* strtoupper(strtolower('aBc')) ≡ 'ABC'
9292
* </code>
9393
*
9494
* @param callable $a
@@ -107,6 +107,37 @@ function pipeline(callable $a, callable $b)
107107
};
108108
}
109109

110+
/**
111+
* @var callable
112+
*/
113+
const pipe = 'Widmogrod\Functional\pipe';
114+
115+
/**
116+
* The first argument becomes the input of the composition
117+
* of functions given as arguments following the former.
118+
* Composition stats from left.
119+
*
120+
* <code>
121+
* pipe('aBc', 'strtolower', 'strtoupper') ≡ 'ABC'
122+
* strtoupper(strtolower('aBc')) ≡ 'ABC'
123+
* </code>
124+
*
125+
* @param mixed $in
126+
* @param callable $fab
127+
* @param callable ...$fbc
128+
* @return mixed
129+
*/
130+
function pipe(
131+
$in,
132+
callable $fab,
133+
callable ...$fbc
134+
) {
135+
$callables = count($fbc) > 0
136+
? $fbc
137+
: [identity];
138+
139+
return pipeline($fab, ...$callables)($in);
140+
}
110141

111142
/**
112143
* @var callable

test/Functional/PipeTest.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace test\Functional;
6+
7+
use Widmogrod\Functional as f;
8+
9+
class PipeTest extends \PHPUnit\Framework\TestCase
10+
{
11+
/**
12+
* @dataProvider provideData
13+
*/
14+
public function test_it_should_compose_and_inject_input_correctly(
15+
$functions,
16+
$value,
17+
$expected
18+
) {
19+
$this->assertEquals(
20+
$expected,
21+
f\pipe($value, ...$functions)
22+
);
23+
}
24+
25+
public function provideData()
26+
{
27+
return [
28+
'two function' => [
29+
'$functions' => ['strtolower', 'strtoupper'],
30+
'$value' => 'aBcD',
31+
'$expected' => 'ABCD'
32+
],
33+
];
34+
}
35+
}

0 commit comments

Comments
 (0)