-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blueprint.php
138 lines (117 loc) · 3.11 KB
/
Blueprint.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<?php namespace Orchestra\Transporter;
use Exception;
use Illuminate\Support\Fluent;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
class Blueprint extends Fluent
{
/**
* Get query builder.
*
* @return \Illuminate\Database\Query\Builder
*/
public function getQueryBuilder()
{
$filter = $this->get('filter');
$query = DB::connection($this->get('connection'))->table($this->get('table'));
if (is_callable($filter)) {
call_user_func($filter, $query, $this);
}
$query->orderBy($this->get('key'));
return $query;
}
/**
* Get last migrated.
*
* @return object|null
*/
public function getLastMigrated()
{
$result = DB::table('orchestra_transporter')
->where('name', '=', $this->get('table'))
->orderBy('source_id', 'desc')
->first();
return $result;
}
/**
* Get migrated table key.
*
* @param string $table
* @param int $id
*
* @return int
*/
public function getMigratedKey($table, $id)
{
$result = DB::table('orchestra_transporter')
->where('name', '=', $table)
->where('source_id', '=', $id)
->first();
return data_get($result, 'destination_id', $id);
}
/**
* Migrate data.
*
* @param mixed $data
*
* @return void
*/
public function migrate($data)
{
$transport = $this->get('transport');
$source = data_get($data, $this->get('key', 'id'));
$result = call_user_func($transport, $data, $this);
$destination = $this->prepareTransformationAndGetKey($result);
if (is_null($destination)) {
throw new Exception('[transport] need to return the inserted ID');
}
$this->runCreateHook($source, $destination);
}
/**
* Is Blueprint valid.
*
* @return bool
*/
public function isValid()
{
return is_callable($this->get('transport'));
}
/**
* Prepare if result from tranform callback is an Eloquent object, if sp
* return the key.
*
* @param mixed $model
*
* @return mixed
*/
protected function prepareTransformationAndGetKey($model)
{
if (! $model instanceof Model) {
return $model;
}
if ($model->exists == false) {
$model->save();
}
return $model->getKey();
}
/**
* Run post create hook.
*
* @param mixed $source
* @param mixed $destination
*
* @return void
*/
protected function runCreateHook($source, $destination)
{
DB::table('orchestra_transporter')->insert([
'name' => $this->get('table'),
'source_id' => $source,
'destination_id' => $destination,
]);
$listen = $this->get('listen');
if (is_callable($listen)) {
call_user_func($listen, $this, $source, $destination);
}
}
}