|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of Blitz PHP framework. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) 2022 Dimitri Sitchet Tomkeu <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view |
|
9
|
|
|
* the LICENSE file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace BlitzPHP\Formatter; |
|
13
|
|
|
|
|
14
|
|
|
use BlitzPHP\Exceptions\FormatException; |
|
15
|
|
|
|
|
16
|
|
|
class Formatter |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* Lorsque vous effectuez une négociation de contenu avec la requête, il s'agit des |
|
20
|
|
|
* formats disponibles pris en charge par votre application. |
|
21
|
|
|
* Un formateur valide doit exister pour le format spécifié. |
|
22
|
|
|
* |
|
23
|
|
|
* Ces formats ne sont vérifiés que lorsque les données sont transmises à la réponse () |
|
24
|
|
|
* La méthode est un tableau. |
|
25
|
|
|
* |
|
26
|
|
|
* @var string[] |
|
27
|
|
|
*/ |
|
28
|
|
|
protected static $supportedResponseFormats = [ |
|
29
|
|
|
'application/json', |
|
30
|
|
|
'application/xml', // XML lisible par machine |
|
31
|
|
|
'text/xml', // XML lisible par l'homme |
|
32
|
|
|
]; |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Répertorie la classe à utiliser pour formater les réponses avec un type particulier. |
|
36
|
|
|
* Pour chaque type mime, indiquez la classe à utiliser. |
|
37
|
|
|
* |
|
38
|
|
|
* @var array<string, string> |
|
39
|
|
|
*/ |
|
40
|
|
|
protected static $formatters = [ |
|
41
|
|
|
'application/json' => JsonFormatter::class, |
|
42
|
|
|
'json' => JsonFormatter::class, |
|
43
|
|
|
'application/csv' => CsvFormatter::class, |
|
44
|
|
|
'csv' => CsvFormatter::class, |
|
45
|
|
|
'application/xml' => XmlFormatter::class, |
|
46
|
|
|
'text/xml' => XmlFormatter::class, |
|
47
|
|
|
'xml' => XmlFormatter::class, |
|
48
|
|
|
|
|
49
|
|
|
'php/array' => ArrayFormatter::class, |
|
50
|
|
|
'array' => ArrayFormatter::class, |
|
51
|
|
|
]; |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Une méthode Factory pour renvoyer le formateur approprié pour le type mime donné. |
|
55
|
|
|
* |
|
56
|
|
|
* @throws FormatException |
|
57
|
|
|
*/ |
|
58
|
|
|
public static function type(string $mime): FormatterInterface |
|
59
|
|
|
{ |
|
60
|
|
|
if (! array_key_exists($mime, self::$formatters)) { |
|
61
|
2 |
|
throw FormatException::invalidMime($mime); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
2 |
|
$className = self::$formatters[$mime]; |
|
65
|
|
|
|
|
66
|
|
|
if (! class_exists($className)) { |
|
67
|
2 |
|
throw FormatException::invalidFormatter($className); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
2 |
|
$class = new $className(); |
|
71
|
|
|
|
|
72
|
|
|
if (! $class instanceof FormatterInterface) { |
|
73
|
2 |
|
throw FormatException::invalidFormatter($className); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
2 |
|
return $class; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|