-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAjaxResponse.php
executable file
·91 lines (79 loc) · 2.87 KB
/
AjaxResponse.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
<?php
namespace TestPlugin {
/**
* A class that represents a response from an AJAX call.
* */
class AjaxResponse implements \JsonSerializable {
public $success;
public $result;
public $message;
public $newNonce;
public function __construct(bool $success = false, $result = [], string $message = "", string $newNonce = ""){
$this->success = $success;
$this->result = $result;
$this->message = $message;
$this->newNonce = $newNonce;
}
public function jsonSerialize():array {
if(!empty($this->newNonce)){
return [
"result" => $this->result,
"message" => $this->message,
"success" => $this->success,
"newNonce" => $this->newNonce
];
} else {
return [
"result" => $this->result,
"message" => $this->message,
"success" => $this->success
];
}
}
public function addMessage(string $msg) {
if(!empty($msg)){
if(!empty($this->message)){
if(!is_array($this->message)){
$this->message = [$this->message];
}
$this->message[] = $msg;
} else {
$this->message = $msg;
}
}
}
public function addToResult($result) {
if(!empty($this->result)){
if(!is_array($this->result)){
$this->result = [$this->result];
}
$this->result[] = $result;
} else {
$this->result = $result;
}
}
public function getMessages(bool $mergeMessages = true):string {
$resultMessages = $this->message;
if($mergeMessages && is_array($resultMessages)) {
$resultMessages = implode('',$resultMessages);
}
return $resultMessages;
}
public function combine(AjaxResponse $other){
$this->success = $this->success && $other->success;
$thisMessages = $this->message;
$otherMessages = $other->message;
if(!is_array($thisMessages)) {
$thisMessages = [$thisMessages];
}
if(!is_array($otherMessages)) {
$otherMessages = [$otherMessages];
}
$this->message = array_merge($thisMessages, $otherMessages);
$this->message = array_filter($this->message);
if(!empty($other->result)) {
$this->addToResult($other->result);
}
}
}
}