Passed
Pull Request — master (#12)
by Joao
01:34
created

RowOutput::formatCustom()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 3
crap 1
1
<?php
2
3
namespace ByJG\AnyDataset\Core;
4
use Closure;
5
6
class RowOutput
7
{
8
    const FORMAT = 'format';
9
    const CUSTOM = 'custom';
10
11
    protected $fieldList = [];
12
13 3
    public static function getInstance()
14
    {
15 3
        return new RowOutput();
16
    }
17
18 3
    public function print($row, $field)
19
    {
20 3
        if (!isset($this->fieldList[$field])) {
21 2
            return $row->get($field);
22
        }
23
24 3
        $data = $this->fieldList[$field];
25
26 3
        switch ($data[0]) {
27 3
            case self::FORMAT:
28 2
                return $this->formatPattern($row, $field, $data[1]);
29 2
            case self::CUSTOM:
30 2
                return $this->formatCustom($row, $field, $data[1]);
31
        }
32
    }
33
34 1
    public function apply($row)
35
    {
36 1
        foreach ($this->fieldList as $key => $value) {
37 1
            $row->set($key, $this->print($row, $key));
38
        }
39
    }
40
41 2
    protected function formatPattern($row, $field, $pattern)
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

41
    protected function formatPattern($row, /** @scrutinizer ignore-unused */ $field, $pattern)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
42
    {
43 2
        $rowParsed = $row->toArray();
44 2
        foreach ($rowParsed as $key => $value) {
45 2
            $rowParsed['{' . $key . '}'] = $value;
46 2
            unset($rowParsed[$key]);
47
        }
48
49 2
        return strtr($pattern, $rowParsed);
50
    }
51
52 2
    protected function formatCustom($row, $field, $closure)
53
    {
54 2
        return $closure($row, $field, $row->get($field));
55
    }
56
57
    /**
58
     * @param string $field
59
     * @param string $pattern
60
     * @return RowOutput
61
     */
62 2
    public function addFormat($field, $pattern)
63
    {
64 2
        $this->fieldList[$field] = [ self::FORMAT,  $pattern ];
65 2
        return $this;
66
    }
67
68
    /**
69
     * Undocumented function
70
     *
71
     * @param string $field
72
     * @param Closure $closure
73
     * @return RowOutput
74
     */
75 2
    public function addCustomFormat($field, Closure $closure)
76
    {
77 2
        $this->fieldList[$field] = [ self::CUSTOM, $closure ];
78 2
        return $this;
79
    }
80
}