1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ntb\RestAPI; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Factory for different kind of rest serializers. |
7
|
|
|
* @author Christian Blank <[email protected]> |
8
|
|
|
*/ |
9
|
|
|
class SerializerFactory { |
10
|
|
|
private static $lookup = [ |
11
|
|
|
'json' => 'application/json', |
12
|
|
|
'html' => 'text/html', |
13
|
|
|
'xml' => 'application/xml', |
14
|
|
|
'yaml' => 'application/yaml' |
15
|
|
|
]; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Returns a new instance of a serializer depending on the given type. |
19
|
|
|
* |
20
|
|
|
* @param string $mimeType the serializer type; Default: application/json |
21
|
|
|
* @return IRestSerializer an instance of a serializer |
22
|
|
|
* @throws RestUserException |
23
|
|
|
*/ |
24
|
|
|
public static function create($mimeType='application/json') { |
25
|
|
|
$availableSerializers = \ClassInfo::implementorsOf('Ntb\RestAPI\IRestSerializer'); |
26
|
|
|
foreach($availableSerializers as $serializer) { |
27
|
|
|
/** @var IRestSerializer $instance */ |
28
|
|
|
$instance = new $serializer(); |
29
|
|
|
if($instance->active() && $instance->contentType() === $mimeType) { |
30
|
|
|
return $instance; |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
throw new RestUserException("Requested Accept '$mimeType' not supported", 404); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Determines the correct serializer from an incoming request. |
38
|
|
|
* |
39
|
|
|
* @param \SS_HTTPRequest $request the request object |
40
|
|
|
* @return IRestSerializer a new instance of a serializer which fits the request best |
41
|
|
|
* @throws RestUserException |
42
|
|
|
*/ |
43
|
|
|
public static function create_from_request($request) { |
44
|
|
|
if($type = $request->getVar('accept')) { |
45
|
|
|
try { |
46
|
|
|
if(array_key_exists($type, self::$lookup)) { |
47
|
|
|
return self::create(self::$lookup[$type]); |
48
|
|
|
} |
49
|
|
|
} catch(\Exception $e) {} |
|
|
|
|
50
|
|
|
} |
51
|
|
|
$types = $request->getAcceptMimetypes(); |
52
|
|
|
foreach($types as $type) { |
53
|
|
|
try { |
54
|
|
|
return self::create($type); |
55
|
|
|
} catch(RestUserException $e) {} |
|
|
|
|
56
|
|
|
} |
57
|
|
|
return self::create(); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|