Passed
Push — master ( e6c108...aa88c1 )
by Daniel
01:49
created

Formatter::assertResultString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
crap 2
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 13
    public function __construct(callable $callback)
33
    {
34 13
        $this->callback = $callback;
35 13
    }
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 8
            if (!is_string($element)) {
48 1
                throw new \InvalidArgumentException('All elements of the array must be strings');
49
            }
50 7
            if (!is_string($formattedElement = call_user_func($this->callback, $element))) {
51 1
                throw new FormatterResultException('Formatter must result in an array of strings');
52
            }
53 6
            $formatted[] = $formattedElement;
54
        }
55 6
        return $formatted;
56
    }
57
}
58