Skip to content

Commit 2d26999

Browse files
committed
Adds string termination
1 parent a4aa34a commit 2d26999

File tree

4 files changed

+61
-2
lines changed

4 files changed

+61
-2
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
namespace Pitchart\Transformer\Reducer\Termination;
4+
5+
use Pitchart\Transformer\Termination;
6+
7+
class ToString implements Termination
8+
{
9+
/**
10+
* @var string
11+
*/
12+
private $glue;
13+
14+
public function __construct($glue = '')
15+
{
16+
$this->glue = $glue;
17+
}
18+
19+
public function init()
20+
{
21+
return '';
22+
}
23+
24+
public function step($result, $current)
25+
{
26+
return $result.$this->glue.$current;
27+
}
28+
29+
public function complete($result)
30+
{
31+
return $result;
32+
}
33+
34+
}

src/Transducer/transducers.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,14 @@ function to_single()
269269
return new Reducer\Termination\SingleResult();
270270
}
271271

272+
/**
273+
* @return Reducer\Termination\ToString
274+
*/
275+
function to_string($glue = '')
276+
{
277+
return new Reducer\Termination\ToString($glue);
278+
}
279+
272280
/**
273281
* @return Reducer\Termination\ToArray
274282
*/

src/Transformer.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,15 +271,25 @@ public function groupBy(callable $callback)
271271
}
272272

273273
/**
274-
* @return mixed
274+
* @param string $glue
275+
*
276+
* @return string
277+
*/
278+
public function toString($glue = '')
279+
{
280+
return $this->terminate(t\to_string($glue));
281+
}
282+
283+
/**
284+
* @return array
275285
*/
276286
public function toArray()
277287
{
278288
return $this->terminate(t\to_array());
279289
}
280290

281291
/**
282-
* @return mixed
292+
* @return \Iterator
283293
*/
284294
public function toIterator()
285295
{

tests/TransformerTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ public function test_can_transduce_into_iterator()
4343
self::assertEquals([1, 2, 3, 4, 5, 6], $values);
4444
}
4545

46+
public function test_can_transduce_into_string()
47+
{
48+
$result = (new Transformer(range(1, 6)))->toString('');
49+
50+
self::assertEquals('123456', $result);
51+
}
52+
4653
public function test_can_map_items_of_iterable()
4754
{
4855
$mapped = (new Transformer(range(1,6)))

0 commit comments

Comments
 (0)