1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yajra\CMS\Http; |
4
|
|
|
|
5
|
|
|
use Illuminate\Http\JsonResponse; |
6
|
|
|
use Illuminate\Http\Response; |
7
|
|
|
|
8
|
|
|
trait NotificationResponse |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var string |
12
|
|
|
*/ |
13
|
|
|
protected $notificationType = 'success'; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param mixed $response |
17
|
|
|
* @param null $title |
18
|
|
|
* @return \Illuminate\Http\JsonResponse |
19
|
|
|
*/ |
20
|
|
View Code Duplication |
public function notifyError($response, $title = null) |
|
|
|
|
21
|
|
|
{ |
22
|
|
|
if (is_string($response)) { |
23
|
|
|
$response = ['text' => $response]; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
$default = [ |
27
|
|
|
'status' => false, |
28
|
|
|
'title' => $title ?: 'Error', |
29
|
|
|
'text' => 'Oops! An error occurred and we were not able to process your request!', |
30
|
|
|
]; |
31
|
|
|
|
32
|
|
|
$data = array_diff_key($default, $response) + $response; |
33
|
|
|
|
34
|
|
|
return $this->setNotificationType('error')->notify($data); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param array $data |
39
|
|
|
* @param int $code |
40
|
|
|
* @return \Illuminate\Http\JsonResponse |
41
|
|
|
*/ |
42
|
|
|
public function notify(array $data, $code = 200) |
43
|
|
|
{ |
44
|
|
|
$data['type'] = $this->getNotificationType(); |
45
|
|
|
|
46
|
|
|
return new JsonResponse($data, $code); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @return string |
51
|
|
|
*/ |
52
|
|
|
public function getNotificationType() |
53
|
|
|
{ |
54
|
|
|
return $this->notificationType; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param string $responseType |
59
|
|
|
* @return $this |
60
|
|
|
*/ |
61
|
|
|
public function setNotificationType($responseType) |
62
|
|
|
{ |
63
|
|
|
$this->notificationType = $responseType; |
64
|
|
|
|
65
|
|
|
return $this; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param mixed $response |
70
|
|
|
* @param null|string $title |
71
|
|
|
* @return \Illuminate\Http\JsonResponse |
72
|
|
|
*/ |
73
|
|
View Code Duplication |
public function notifySuccess($response, $title = null) |
|
|
|
|
74
|
|
|
{ |
75
|
|
|
if (is_string($response)) { |
76
|
|
|
$response = ['text' => $response]; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
$default = [ |
80
|
|
|
'status' => true, |
81
|
|
|
'title' => $title ?: 'Success', |
82
|
|
|
'text' => 'Requested process successfully completed!', |
83
|
|
|
]; |
84
|
|
|
|
85
|
|
|
$data = array_diff_key($default, $response) + $response; |
86
|
|
|
|
87
|
|
|
return $this->setNotificationType('success')->notify($data, Response::HTTP_OK); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.