1 | <?php |
||
8 | class CustomPassthroughFunctionTest extends PHPUnit_Framework_TestCase |
||
9 | { |
||
10 | /** |
||
11 | * Example of implementing a transpose function and how to apply it over a collection. |
||
12 | * |
||
13 | * For more on how this can be useful: http://adamwathan.me/2016/04/06/cleaning-up-form-input-with-transpose/ |
||
14 | */ |
||
15 | public function testIt() |
||
16 | { |
||
17 | $formData = [ |
||
18 | 'names' => [ |
||
19 | 'Jane', |
||
20 | 'Bob', |
||
21 | 'Mary', |
||
22 | ], |
||
23 | 'emails' => [ |
||
24 | '[email protected]', |
||
25 | '[email protected]', |
||
26 | '[email protected]', |
||
27 | ], |
||
28 | 'occupations' => [ |
||
29 | 'Doctor', |
||
30 | 'Plumber', |
||
31 | 'Dentist', |
||
32 | ], |
||
33 | ]; |
||
34 | |||
35 | //Must take and return a Collection |
||
36 | $transpose = function (Collection $collections) { |
||
37 | $transposed = array_map( |
||
38 | function (...$items) { |
||
39 | return $items; |
||
40 | }, |
||
41 | ...$collections->values()->toArray() |
||
42 | ); |
||
43 | |||
44 | return Collection::from($transposed); |
||
45 | }; |
||
46 | |||
47 | $result = Collection::from($formData) |
||
48 | ->transform($transpose) |
||
49 | ->toArray(); |
||
50 | |||
51 | $expected = [ |
||
52 | [ |
||
53 | 'Jane', |
||
54 | '[email protected]', |
||
55 | 'Doctor' |
||
56 | ], |
||
57 | [ |
||
58 | 'Bob', |
||
59 | '[email protected]', |
||
60 | 'Plumber' |
||
61 | ], |
||
62 | [ |
||
63 | 'Mary', |
||
64 | '[email protected]', |
||
65 | 'Dentist' |
||
66 | ] |
||
67 | ]; |
||
68 | |||
69 | $this->assertEquals($expected, $result); |
||
70 | } |
||
71 | } |
||
72 |