Passed
Push — 6.0 ( 3dc798...7ca19f )
by liu
02:48
created

Jsonp::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
12
namespace think\response;
13
14
use think\Request;
15
use think\Response;
16
17
class Jsonp extends Response
1 ignored issue
show
Coding Style introduced by
Missing doc comment for class Jsonp
Loading history...
18
{
19
    // 输出参数
20
    protected $options = [
21
        'var_jsonp_handler'     => 'callback',
22
        'default_jsonp_handler' => 'jsonpReturn',
23
        'json_encode_param'     => JSON_UNESCAPED_UNICODE,
24
    ];
25
26
    protected $contentType = 'application/javascript';
27
28
    protected $request;
29
30
    public function __construct(Request $request, $data = '', int $code = 200)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
31
    {
32
        parent::__construct($data, $code);
33
34
        $this->request = $request;
35
    }
36
37
    /**
38
     * 处理数据
39
     * @access protected
40
     * @param  mixed $data 要处理的数据
41
     * @return string
42
     * @throws \Exception
43
     */
44
    protected function output($data): string
45
    {
46
        try {
47
            // 返回JSON数据格式到客户端 包含状态信息 [当url_common_param为false时是无法获取到$_GET的数据的,故使用Request来获取<[email protected]>]
48
            $var_jsonp_handler = $this->request->param($this->options['var_jsonp_handler'], "");
49
            $handler           = !empty($var_jsonp_handler) ? $var_jsonp_handler : $this->options['default_jsonp_handler'];
50
51
            $data = json_encode($data, $this->options['json_encode_param']);
52
53
            if (false === $data) {
54
                throw new \InvalidArgumentException(json_last_error_msg());
55
            }
56
57
            $data = $handler . '(' . $data . ');';
58
59
            return $data;
60
        } catch (\Exception $e) {
61
            if ($e->getPrevious()) {
62
                throw $e->getPrevious();
63
            }
64
            throw $e;
65
        }
66
    }
67
68
}
69