|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of the Csv-Machine package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Dan McAdams <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace RoadBunch\Csv\Formatter; |
|
13
|
|
|
use RoadBunch\Csv\Exception\FormatterResultException; |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Class Formatter |
|
18
|
|
|
* |
|
19
|
|
|
* @author Dan McAdams |
|
20
|
|
|
* @package RoadBunch\Csv\Formatter |
|
21
|
|
|
*/ |
|
22
|
|
|
class Formatter implements FormatterInterface |
|
23
|
|
|
{ |
|
24
|
|
|
/** @var callable */ |
|
25
|
|
|
protected $callback; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Formatter constructor. |
|
29
|
|
|
* |
|
30
|
|
|
* @param callable $callback |
|
31
|
|
|
*/ |
|
32
|
11 |
|
public function __construct(callable $callback) |
|
33
|
|
|
{ |
|
34
|
11 |
|
$this->callback = $callback; |
|
35
|
11 |
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param array $data an array of strings to be formatted |
|
39
|
|
|
* |
|
40
|
|
|
* @return array |
|
41
|
|
|
* @throws \InvalidArgumentException|FormatterResultException |
|
42
|
|
|
*/ |
|
43
|
8 |
|
public function format(array $data): array |
|
44
|
|
|
{ |
|
45
|
8 |
|
$formatted = []; |
|
46
|
8 |
|
foreach ($data as $element) { |
|
47
|
|
|
// assert element to format is string |
|
48
|
8 |
|
$this->assertString($element); |
|
49
|
|
|
// assert resulting element is string |
|
50
|
7 |
|
$this->assertResultString($formattedElement = call_user_func($this->callback, $element)); |
|
51
|
|
|
|
|
52
|
6 |
|
$formatted[] = $formattedElement; |
|
53
|
|
|
} |
|
54
|
6 |
|
return $formatted; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* @param $value |
|
59
|
|
|
* @throws \InvalidArgumentException |
|
60
|
|
|
*/ |
|
61
|
8 |
|
protected function assertString($value) |
|
62
|
|
|
{ |
|
63
|
8 |
|
if (!is_string($value)) { |
|
64
|
1 |
|
throw new \InvalidArgumentException('All elements of the array must be strings'); |
|
65
|
|
|
} |
|
66
|
7 |
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @param $result |
|
70
|
|
|
* @throws FormatterResultException |
|
71
|
|
|
*/ |
|
72
|
7 |
|
protected function assertResultString($result) |
|
73
|
|
|
{ |
|
74
|
7 |
|
if (!is_string($result)) { |
|
75
|
1 |
|
throw new FormatterResultException('Formatter must result in an array of strings'); |
|
76
|
|
|
} |
|
77
|
6 |
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|