1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
4
|
|
|
use Symfony\Component\HttpFoundation\ParameterBag; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* A controller with the capability of responding with JSON data |
8
|
|
|
* @package BZiON\Controllers |
9
|
|
|
*/ |
10
|
|
|
abstract class JSONController extends HTMLController |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Values to be included in the JSON response |
14
|
|
|
*/ |
15
|
|
|
protected $attributes; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* {@inheritdoc} |
19
|
|
|
*/ |
20
|
1 |
|
public function __construct($parameters) |
21
|
|
|
{ |
22
|
1 |
|
$this->attributes = new ParameterBag(); |
23
|
|
|
|
24
|
1 |
|
parent::__construct($parameters); |
25
|
1 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Finds whether the client has requested a JSON document |
29
|
|
|
* |
30
|
|
|
* @return bool |
31
|
|
|
**/ |
32
|
1 |
|
protected function isJson() |
33
|
|
|
{ |
34
|
1 |
|
$request = $this->getRequest(); |
35
|
1 |
|
foreach (array($request->request, $request->query) as $params) { |
36
|
1 |
|
if (strtolower($params->get('format')) == 'json') { |
37
|
|
|
return true; |
38
|
|
|
} |
39
|
1 |
|
} |
40
|
|
|
|
41
|
1 |
|
return false; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* {@inheritdoc} |
46
|
|
|
*/ |
47
|
1 |
|
protected function handleReturnValue($return, $action) |
48
|
|
|
{ |
49
|
|
|
// Format strings nicely with JSON, if the client wants that |
50
|
1 |
|
if ($this->isJson()) { |
51
|
|
|
if (!$return instanceof JsonResponse) { |
52
|
|
|
$response = array('success' => true); |
53
|
|
|
|
54
|
|
|
$flashbag = $this->getFlashBag(); |
55
|
|
|
if ($flashbag->has('success')) { |
56
|
|
|
$messages = $flashbag->get('success'); |
57
|
|
|
$response['message'] = $messages[0]; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$response['content'] = (is_array($return)) |
61
|
|
|
? $this->renderDefault($return, $action) |
62
|
|
|
: $return; |
63
|
|
|
|
64
|
|
|
$response = array_replace($response, $this->attributes->all()); |
65
|
|
|
|
66
|
|
|
$return = new JsonResponse($response); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
1 |
|
return parent::handleReturnValue($return, $action); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|