1
|
|
|
<?php |
2
|
|
|
|
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace BristolSU\ControlDB\Export\Handler\Airtable; |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
use BristolSU\ControlDB\Export\FormattedItem; |
8
|
|
|
use BristolSU\ControlDB\Export\Handler\Handler; |
9
|
|
|
use Carbon\Carbon; |
10
|
|
|
use Illuminate\Support\Collection; |
11
|
|
|
|
12
|
|
|
class AirtableHandler extends Handler |
|
|
|
|
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Save each item to AirTable |
17
|
|
|
* |
18
|
|
|
* @param FormattedItem[] $items |
|
|
|
|
19
|
|
|
* @return mixed|void |
|
|
|
|
20
|
|
|
*/ |
21
|
2 |
|
protected function save(array $items) |
22
|
|
|
{ |
23
|
2 |
|
$creating = []; |
24
|
|
|
|
25
|
2 |
|
foreach($items as $item) { |
|
|
|
|
26
|
1 |
|
$creating[] = [ |
27
|
1 |
|
'fields' => $item->toArray() |
28
|
|
|
]; |
29
|
|
|
} |
30
|
|
|
|
31
|
2 |
|
$time = Carbon::now(); |
32
|
2 |
|
$time = $this->clearTable($time); |
33
|
2 |
|
$this->createRows($creating, $time); |
34
|
2 |
|
} |
35
|
|
|
|
36
|
2 |
|
protected function createRows($creating, $time) |
|
|
|
|
37
|
|
|
{ |
38
|
2 |
|
foreach (collect($creating)->chunk(10) as $fields) { |
39
|
1 |
|
dispatch( |
40
|
1 |
|
new CreateRows(['records' => $fields->values()->toArray(), 'typecast' => true], $this->config('apiKey'), |
|
|
|
|
41
|
1 |
|
$this->config('baseId'), $this->config('tableName')) |
|
|
|
|
42
|
1 |
|
)->delay($time); |
43
|
1 |
|
$time->addSeconds(2); |
44
|
|
|
} |
45
|
2 |
|
} |
46
|
|
|
|
47
|
2 |
|
protected function clearTable($time) |
|
|
|
|
48
|
|
|
{ |
49
|
2 |
|
$idRetriever = app(IdRetriever::class, [ |
|
|
|
|
50
|
2 |
|
'baseId' => $this->config('baseId'), |
51
|
2 |
|
'tableName' => $this->config('tableName') |
52
|
|
|
]); |
|
|
|
|
53
|
2 |
|
$ids = $idRetriever->ids(); |
54
|
|
|
|
55
|
2 |
|
foreach ($ids->chunk(10) as $idsToRemove) { |
56
|
1 |
|
dispatch( |
57
|
1 |
|
new DeleteRows(['records' => $idsToRemove->values()->toArray()], |
|
|
|
|
58
|
1 |
|
$this->config('apiKey'), $this->config('baseId'), |
|
|
|
|
59
|
1 |
|
$this->config('tableName')) |
|
|
|
|
60
|
1 |
|
)->delay($time); |
61
|
1 |
|
$time->addSeconds(2); |
62
|
|
|
} |
63
|
2 |
|
$idRetriever->saveIds([]); |
64
|
2 |
|
return $time; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
|
68
|
|
|
} |