1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Utils\Recruitments; |
4
|
|
|
|
5
|
|
|
use App\Models\Recruitment; |
6
|
|
|
use App\Utils\SourceCreator; |
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
|
9
|
|
|
class RecruitmentReplicator |
10
|
|
|
{ |
11
|
|
|
protected static $relationships = [ |
12
|
|
|
'formFields', |
13
|
|
|
'sources', |
14
|
|
|
'predefinedMessages', |
15
|
|
|
]; |
16
|
|
|
|
17
|
|
|
public static function duplicate($recruitmentId) |
18
|
|
|
{ |
19
|
|
|
$recruitment = Recruitment::with(static::$relationships)->findOrFail($recruitmentId); |
20
|
|
|
|
21
|
|
|
$newRecruitment = $recruitment->replicate()->setRelations([]); |
22
|
|
|
$newRecruitment->name = $newRecruitment->name.' '.date('d.m.Y'); |
23
|
|
|
$newRecruitment->is_draft = true; |
24
|
|
|
$newRecruitment->push(); |
25
|
|
|
|
26
|
|
|
$replicatedOrder = static::replicateRelations($recruitment, $newRecruitment); |
27
|
|
|
|
28
|
|
|
return $replicatedOrder->loadMissing(static::$relationships); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
protected static function replicateRelations(Model $oldModel, Model &$newModel) |
32
|
|
|
{ |
33
|
|
|
foreach ($oldModel->getRelations() as $relation => $modelCollection) { |
34
|
|
|
|
35
|
|
|
// if (!in_array($relation, static::$relationships)) { |
36
|
|
|
// continue; |
37
|
|
|
// } |
38
|
|
|
|
39
|
|
|
foreach ($modelCollection as $model) { |
40
|
|
|
if ($relation === 'sources') { |
41
|
|
|
SourceCreator::create(['name' => $model->name, 'recruitment_id' => $newModel->id]); |
42
|
|
|
} else { |
43
|
|
|
$childModel = $model->replicate(); |
44
|
|
|
$childModel->recruitment_id = $newModel->id; |
45
|
|
|
$childModel->push(); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
//$childModel->setRelations([]); |
49
|
|
|
//$newModel->{$relation}()->save($childModel); // saving whatever columns $childModel has except foreign keys relative to it's parent model. If there were any other foreign keys other than the parent model, in this case, those scenarios are not handled. |
50
|
|
|
//static::replicateRelations($model,$childModel); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $newModel; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|