1
|
|
|
<?php |
2
|
|
|
|
|
|
|
|
3
|
|
|
namespace BristolSU\ControlDB\Export\Handler; |
4
|
|
|
|
5
|
|
|
use BristolSU\ControlDB\Export\FormattedItem; |
6
|
|
|
use BristolSU\ControlDB\Export\Formatter\Formatter; |
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
|
9
|
|
|
abstract class Handler |
|
|
|
|
10
|
|
|
{ |
11
|
|
|
/** |
|
|
|
|
12
|
|
|
* @var array |
13
|
|
|
*/ |
14
|
|
|
private $config; |
|
|
|
|
15
|
|
|
|
16
|
13 |
|
public function __construct(array $config) |
|
|
|
|
17
|
|
|
{ |
18
|
13 |
|
$this->config = $config; |
19
|
13 |
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Prepare items by transforming them to formattable items |
23
|
|
|
* |
24
|
|
|
* @param $items |
|
|
|
|
25
|
|
|
* @return FormattedItem[] |
|
|
|
|
26
|
|
|
*/ |
27
|
6 |
|
protected function prepareItems($items) |
28
|
|
|
{ |
29
|
6 |
|
$formattedItems = []; |
30
|
6 |
|
foreach($items as $item) { |
|
|
|
|
31
|
6 |
|
$formattedItems[] = FormattedItem::create($item); |
32
|
|
|
} |
33
|
6 |
|
return $formattedItems; |
34
|
|
|
} |
35
|
|
|
|
36
|
6 |
|
public function export($items = []) |
|
|
|
|
37
|
|
|
{ |
38
|
6 |
|
if($items instanceof Collection) { |
|
|
|
|
39
|
1 |
|
$items = $items->all(); |
40
|
|
|
} |
41
|
6 |
|
$formattedItems = $this->prepareItems($items); |
42
|
6 |
|
foreach($this->getFormatters() as $formatter) { |
|
|
|
|
43
|
5 |
|
$formattedItems = $formatter->format($formattedItems); |
44
|
|
|
} |
45
|
5 |
|
$this->save($formattedItems); |
46
|
5 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
|
|
|
|
49
|
|
|
* @return Formatter[] |
50
|
|
|
*/ |
51
|
6 |
|
protected function getFormatters() |
52
|
|
|
{ |
53
|
|
|
return array_map(function($className) { |
|
|
|
|
54
|
6 |
|
if(class_exists($className)) { |
|
|
|
|
55
|
5 |
|
return new $className($this->config('formatters')[$className]); |
56
|
|
|
} |
57
|
1 |
|
throw new \Exception(sprintf('Formatter %s does not exist', $className)); |
58
|
6 |
|
}, array_keys($this->config('formatters', []))); |
|
|
|
|
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
|
|
|
|
62
|
|
|
* @param FormattedItem[] $items |
|
|
|
|
63
|
|
|
* @return mixed |
|
|
|
|
64
|
|
|
*/ |
65
|
|
|
abstract protected function save(array $items); |
66
|
|
|
|
67
|
|
|
/** |
|
|
|
|
68
|
|
|
* @param string $key |
|
|
|
|
69
|
|
|
* @param null $default |
|
|
|
|
70
|
|
|
* |
71
|
|
|
* @return mixed|null |
72
|
|
|
*/ |
73
|
11 |
|
protected function config(string $key, $default = null) |
74
|
|
|
{ |
75
|
11 |
|
if(array_key_exists($key, $this->config)) { |
|
|
|
|
76
|
11 |
|
return $this->config[$key]; |
77
|
|
|
} |
78
|
3 |
|
return $default; |
79
|
|
|
} |
80
|
|
|
} |