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: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172:
<?php
namespace Baidu\Duer\Botsdk;
class Response{
private $request;
private $session;
private $nlu;
private $sourceType;
private $shouldEndSession = true;
public function __construct($request, $session, $nlu){
$this->request = $request;
$this->session = $session;
$this->nlu = $nlu;
$this->sourceType = $this->request->getBotId();
}
public function setShouldEndSession($val){
if($val === false) {
$this->shouldEndSession = false;
}else if($val === true){
$this->shouldEndSession = true;
}
}
public function defaultResult(){
return json_encode(['status'=>0, 'msg'=>null]);
}
public function build($data){
if($this->nlu && $this->nlu->hasAsked()){
$this->shouldEndSession = false;
}
$directives = $data['directives'] ? $data['directives'] : [];
$directives = array_values(array_filter(array_map(function($directive){
if($directive instanceof Directive\BaseDirective) {
return $directive->getData();
}
}, $directives)));
if($this->nlu){
$arr = $this->nlu->toDirective();
if($arr) {
$directives[] = $arr;
}
}
if(!$data['outputSpeech'] && $data['card'] && $data['card'] instanceof Card\TextCard) {
$data['outputSpeech'] = $data['card']->getData('content');
}
$ret = [
'version' => '2.0',
'context' => ($this->nlu ? $this->nlu->toUpdateIntent() : null)?($this->nlu ? $this->nlu->toUpdateIntent() : null) :(object)[],
'session' => $this->session->toResponse(),
'response' => [
'directives' => $directives,
'shouldEndSession' => $this->shouldEndSession,
'card' => $data['card']?$data['card']->getData():null,
'resource' => $data['resource'],
'outputSpeech' => $data['outputSpeech']?$this->formatSpeech($data['outputSpeech']):null,
'reprompt' => $data['reprompt']?[
'outputSpeech' => $this->formatSpeech($data['reprompt']),
]:null
]
];
$str=json_encode($ret, JSON_UNESCAPED_UNICODE);
return $str;
}
public function formatSpeech($mix){
if(is_array($mix)) {
return $mix;
}
if(preg_match('/<speak>/', $mix)) {
return [
'type' => 'SSML',
'ssml' => $mix,
];
}else{
return [
'type' => 'PlainText',
'text' => $mix,
];
}
}
public function illegalRequest() {
return json_encode(['status'=>1, 'msg'=>'非法请求']);
}
}