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) |
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
|
2 |
|
$rowParsed['{.}'] = $field; |
49
|
2 |
|
$rowParsed['{}'] = $row->get($field); |
50
|
|
|
|
51
|
2 |
|
return strtr($pattern, $rowParsed); |
52
|
|
|
} |
53
|
|
|
|
54
|
2 |
|
protected function formatCustom($row, $field, $closure) |
55
|
|
|
{ |
56
|
2 |
|
return $closure($row, $field, $row->get($field)); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param string $field |
61
|
|
|
* @param string $pattern |
62
|
|
|
* @return RowOutput |
63
|
|
|
*/ |
64
|
2 |
|
public function addFormat($field, $pattern) |
65
|
|
|
{ |
66
|
2 |
|
$this->fieldList[$field] = [ self::FORMAT, $pattern ]; |
67
|
2 |
|
return $this; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Undocumented function |
72
|
|
|
* |
73
|
|
|
* @param string $field |
74
|
|
|
* @param Closure $closure |
75
|
|
|
* @return RowOutput |
76
|
|
|
*/ |
77
|
2 |
|
public function addCustomFormat($field, Closure $closure) |
78
|
|
|
{ |
79
|
2 |
|
$this->fieldList[$field] = [ self::CUSTOM, $closure ]; |
80
|
2 |
|
return $this; |
81
|
|
|
} |
82
|
|
|
} |