CampaignVariablesController.php
3.38 KB
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
<?php
namespace App\Http\Controllers;
use App\Models\Tokens;
use App\Models\Variable;
use Inertia\Inertia;
class CampaignVariablesController extends Controller
{
protected $rule_variable = 'required|exists:variables,id';
protected $rule_variable_name = 'required|alpha|regex:/[a-zA-z]/';
protected $rule_value = 'required';
function __invoke(Tokens $token, $campaign_id)
{
if ($token->isMain()) {
return back();
}
$campaign = Tokens::where('type', Tokens::MAIN)->get()->first()->campaignsForEnabled()->with('variables')->find($campaign_id);
if (!$campaign) {
return back();
};
switch (request()->method()) {
case 'GET':
return Inertia::render('CampaignVariables/Edit', [
'variables' => Variable::defaultOrderBy()->get(),
'token' => $token,
'campaign' => $campaign,
]);
break;
case 'POST':
if (request('variable') === 'add') {
request()->validate([
'name' => $this->rule_variable_name,
'value' => $this->rule_value,
]);
$variable_new = Variable::create([
'name' => request('name'),
]);
$variable_id = $variable_new->getKey();
$value = request('value');
} else {
request()->validate([
'variable' => $this->rule_variable,
'value' => $this->rule_value,
]);
$variable_id = request('variable');
$value = request('value');
}
$campaign->variables()->syncWithoutDetaching([
$variable_id => [
'value' => $value,
],
]);
return back()->with('success', 'Campaign variable added.');
break;
case 'PUT':
$campaign_variable = $campaign->variables()->find(request('id'));
if (!$campaign_variable) {
return back();
}
if (request()->validate(['name' => $this->rule_variable_name])) {
$campaign_variable->update(request()->only('name'));
}
return back()->with('success', 'Variable name updated.');
break;
case 'PATCH':
$campaign_variable = $campaign->variables()->find(request('id'));
if (!$campaign_variable) {
return back();
}
if (request()->validate(['value' => $this->rule_value])) {
$campaign_variable->update(request()->only('value'));
}
return back()->with('success', 'Campaign variable updated.');
break;
case 'DELETE':
$campaign_variable = $campaign->vars()->find(request('id'));
if (!$campaign_variable) {
return back();
}
$campaign_variable->delete();
return back()->with('success', 'Campaign variable deleted.');
break;
}
return back();
}
}