forked from paysera/lib-rest-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiManager.php
602 lines (547 loc) · 18.6 KB
/
ApiManager.php
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
<?php
namespace Paysera\Bundle\RestBundle;
use Paysera\Bundle\RestBundle\Resolver\AttributeResolverInterface;
use Paysera\Bundle\RestBundle\Service\PropertyPathConverter\PathConverter;
use Paysera\Component\Serializer\Exception\InvalidDataException;
use Paysera\Component\Serializer\Normalizer\NormalizerInterface;
use Paysera\Component\Serializer\Validation\PropertiesAwareValidator;
use Paysera\Component\Serializer\Validation\PropertyPathConverterInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Paysera\Bundle\RestBundle\Entity\ErrorConfig;
use Paysera\Bundle\RestBundle\Exception\ConfigurationException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Paysera\Component\Serializer\Encoding\DecoderInterface;
use Paysera\Bundle\RestBundle\Service\FormatDetector;
use Paysera\Bundle\RestBundle\Entity\Error;
use Paysera\Component\Serializer\Encoding\EncoderInterface;
use Paysera\Bundle\RestBundle\Exception\ApiException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class ApiManager
{
/**
* @var RestApi[]
*/
private $apiByUriPattern;
/**
* @var RestApi[]
*/
private $apiByKey;
/**
* @var EncoderInterface[]
*/
private $encoders;
/**
* @var DecoderInterface[]
*/
private $decoders;
private $errorConfig;
private $validator;
private $errorNormalizer;
private $logger;
/**
* @var string
*/
private $routingAttribute;
/**
* @var PropertyPathConverterInterface|null
*/
private $propertyPathConverter;
private $formatDetector;
/**
* @param FormatDetector $formatDetector
* @param LoggerInterface $logger
* @param ValidatorInterface $validator
* @param NormalizerInterface $errorNormalizer
* @param string $routingAttribute
*/
public function __construct(
FormatDetector $formatDetector,
LoggerInterface $logger,
ValidatorInterface $validator,
NormalizerInterface $errorNormalizer,
$routingAttribute = 'api_key'
) {
$this->logger = $logger;
$this->formatDetector = $formatDetector;
$this->validator = $validator;
$this->errorNormalizer = $errorNormalizer;
$this->routingAttribute = $routingAttribute;
$this->errorConfig = new ErrorConfig();
$this->apiByUriPattern = [];
$this->apiByKey = [];
$this->encoders = [];
$this->decoders = [];
}
/**
* Adds API to manager. Should be called from configuration or dependency injection compiler
*
* @param RestApi $restApi
* @param string $uriPattern
*/
public function addApiByUriPattern(RestApi $restApi, $uriPattern)
{
$this->apiByUriPattern[$uriPattern] = $restApi;
}
/**
* Adds API to manager. Should be called from configuration or dependency injection compiler
*
* @param RestApi $restApi
* @param string $apiKey
*/
public function addApiByKey(RestApi $restApi, $apiKey)
{
$this->apiByKey[$apiKey] = $restApi;
}
/**
* Adds encoder
*
* @param EncoderInterface $encoder
* @param string $format
*/
public function addEncoder(EncoderInterface $encoder, $format)
{
$this->encoders[$format] = $encoder;
}
/**
* Adds decoder
*
* @param DecoderInterface $decoder
* @param string $format
*/
public function addDecoder(DecoderInterface $decoder, $format)
{
$this->decoders[$format] = $decoder;
}
/**
* Sets errorConfig
*
* @param \Paysera\Bundle\RestBundle\Entity\ErrorConfig $errorConfig
*/
public function setErrorConfig($errorConfig)
{
$this->errorConfig = $errorConfig;
}
/**
* Creates response for exception if some API is answering to this request.
* If not, null is returned
*
* @param Request $request
* @param \Exception $exception
*
* @throws Exception\ApiException
* @throws \Exception
* @return \Symfony\Component\HttpFoundation\Response|null
*/
public function getResponseForException(Request $request, \Exception $exception)
{
try {
$api = $this->getApiForRequest($request);
} catch (\RuntimeException $e) {
return new Response('', 500);
}
if ($api) {
$error = $this->createErrorFromException($exception);
$this->fillErrorDefaults($error, $api);
try {
$encoder = $this->getEncoderForApi($request, $api);
$result = $encoder->encode($this->errorNormalizer->mapFromEntity($error));
$headers = array('Content-Type' => $encoder->getContentType());
} catch (ApiException $exception) {
if ($exception->getErrorCode() === $exception::NOT_ACCEPTABLE) {
$result = $error->getMessage();
$headers = array('Content-Type' => 'text/plain');
} else {
throw $exception;
}
}
return new Response($result, $error->getStatusCode(), $headers);
}
return null;
}
/**
* Returns request mapper for this request
*
* @param Request $request
*
* @return \Paysera\Bundle\RestBundle\Normalizer\NameAwareDenormalizerInterface|null
*/
public function getRequestMapper(Request $request)
{
$api = $this->getApiForRequest($request);
if ($api) {
return $api->getRequestMapper($request->attributes->get('_controller'));
}
return null;
}
/**
* Returns request query mapper for this request
*
* @param Request $request
*
* @return \Paysera\Bundle\RestBundle\Normalizer\NameAwareDenormalizerInterface|null
*/
public function getRequestQueryMapper(Request $request)
{
$api = $this->getApiForRequest($request);
if ($api) {
return $api->getRequestQueryMapper($request->attributes->get('_controller'));
}
return null;
}
/**
* Returns validation group for this request
*
* @param Request $request
*
* @return array
*/
public function getValidationGroups(Request $request)
{
$api = $this->getApiForRequest($request);
if ($api) {
return $api->getValidationGroups($request->attributes->get('_controller'));
}
return null;
}
/**
* @param Request $request
*
* @return PropertiesAwareValidator|null
*/
public function createPropertiesValidator(Request $request)
{
$api = $this->getApiForRequest($request);
if ($api) {
$pathConverters = $api->getPropertyPathConverters($request->attributes->get('_controller'));
if ($this->propertyPathConverter !== null) {
$pathConverters[] = $this->propertyPathConverter;
}
$propertyPathConverter = count($pathConverters) > 0
? new PathConverter($pathConverters)
: null
;
return new PropertiesAwareValidator($this->validator, $propertyPathConverter);
}
return null;
}
/**
* returns if controlers request body should be logged or not
*
* @param Request $request
*
* @return array|null
*/
public function getRequestLoggingParts(Request $request)
{
$api = $this->getApiForRequest($request);
if ($api) {
return $api->getRequestLoggingParts($request->attributes->get('_controller'));
}
return null;
}
/**
* Returns request query mapper for this request
*
* @param Request $request
*
* @return AttributeResolverInterface[]
*/
public function getRequestAttributeResolvers(Request $request)
{
$requestAttrResolvers = array();
$api = $this->getApiForRequest($request);
if ($api) {
$requestAttrResolvers = $api->getRequestAttributeResolvers($request->attributes->get('_controller'));
}
return $requestAttrResolvers;
}
/**
* Returns response mapper for this request
*
* @param Request $request
* @param array $options
*
* @return NormalizerInterface|null
*/
public function getResponseMapper(Request $request, array $options = array())
{
$api = $this->getApiForRequest($request);
if ($api) {
return $api->getResponseMapper($request->attributes->get('_controller'), $options);
}
return null;
}
/**
* Returns cache strategy for this request
*
* @param Request $request
* @param array $options
*
* @return \Paysera\Bundle\RestBundle\Cache\CacheStrategyInterface|null
*/
public function getCacheStrategy(Request $request, array $options = array())
{
$api = $this->getApiForRequest($request);
if ($api) {
return $api->getCacheStrategy($request->attributes->get('_controller'), $options);
}
return null;
}
/**
* Returns encoder for this request
*
* @param Request $request
* @param array $options
*
* @return \Paysera\Component\Serializer\Encoding\EncoderInterface|null
*/
public function getEncoder(Request $request, array $options = array())
{
$api = $this->getApiForRequest($request);
if ($api) {
return $this->getEncoderForApi($request, $api, $options);
}
return null;
}
/**
* Returns decoder for this request
*
* @param Request $request
*
* @return \Paysera\Component\Serializer\Encoding\DecoderInterface|null
*/
public function getDecoder(Request $request)
{
$api = $this->getApiForRequest($request);
if ($api) {
return $this->getDecoderForApi($request, $api);
}
return null;
}
/**
* Returns security strategy for this request
*
* @param Request $request
*
* @return \Paysera\Bundle\RestBundle\Security\SecurityStrategyInterface|null
*/
public function getSecurityStrategy(Request $request)
{
$api = $this->getApiForRequest($request);
if ($api) {
return $api->getSecurityStrategy();
}
return null;
}
/**
* @param PropertyPathConverterInterface|null $propertyPathConverter
*
* @return $this
*/
public function setPropertyPathConverter($propertyPathConverter)
{
$this->propertyPathConverter = $propertyPathConverter;
return $this;
}
public function getLogger(Request $request)
{
$api = $this->getApiForRequest($request);
if ($api) {
return $api->getLogger();
}
return null;
}
public function getApiKeyForRequest(Request $request)
{
return $request->attributes->get($this->routingAttribute);
}
/**
* Finds API for this request. Returns null if none found
*
* @param Request $request
*
* @throws \RuntimeException
* @return RestApi|null
*/
protected function getApiForRequest(Request $request)
{
$apiKey = $this->getApiKeyForRequest($request);
if ($apiKey !== null) {
if (!isset($this->apiByKey[$apiKey])) {
throw new \RuntimeException('Api not registered with such key: ' . $apiKey);
}
return $this->apiByKey[$apiKey];
}
foreach ($this->apiByUriPattern as $uriPattern => $api) {
if (preg_match($uriPattern, $request->getPathInfo())) {
return $api;
}
}
return null;
}
/**
* Creates Error entity from given exception
*
* @param \Exception $exception
*
* @return Error
*/
protected function createErrorFromException(\Exception $exception)
{
if ($exception instanceof ApiException) {
return Error::create()
->setCode($exception->getErrorCode())
->setMessage($exception->getMessage())
->setStatusCode($exception->getStatusCode())
->setProperties($exception->getProperties())
->setData($exception->getData())
->setViolations($exception->getViolations())
;
} elseif ($exception instanceof InvalidDataException) {
return Error::create()
->setCode(ApiException::INVALID_PARAMETERS)
->setMessage($exception->getMessage())
->setStatusCode(400)
->setProperties($exception->getProperties())
->setViolations($exception->getViolations())
;
} elseif ($exception instanceof AuthenticationCredentialsNotFoundException) {
return Error::create()->setCode(ApiException::UNAUTHORIZED)->setMessage('No authorization data found');
} elseif ($exception instanceof AuthenticationException) {
$error = Error::create()->setCode(ApiException::UNAUTHORIZED);
if ($exception->getCode() === 999) {
$error->setMessage($exception->getMessage());
}
return $error;
} elseif ($exception instanceof AccessDeniedException) {
return Error::create()->setCode(ApiException::FORBIDDEN)->setMessage($exception->getMessage());
} elseif ($exception instanceof AccessDeniedHttpException) {
return Error::create()->setCode(ApiException::FORBIDDEN)->setMessage($exception->getMessage());
} elseif ($exception instanceof ResourceNotFoundException || $exception instanceof NotFoundHttpException) {
return Error::create()->setCode(ApiException::NOT_FOUND)->setMessage('Provided url not found')->setStatusCode(404);
} elseif ($exception instanceof MethodNotAllowedException) {
return Error::create()
->setCode(ApiException::NOT_FOUND)
->setMessage('Provided method not allowed for this url')
->setStatusCode(404)
;
} elseif ($exception instanceof HttpExceptionInterface && $exception->getStatusCode() < 500) {
if ($exception->getStatusCode() === 405 || $exception->getStatusCode() === 404) {
return Error::create()
->setCode(ApiException::NOT_FOUND)
->setStatusCode($exception->getStatusCode())
->setMessage('Used method is not allowed for this url')
;
} elseif ($exception->getStatusCode() === 401) {
return Error::create()->setCode(ApiException::UNAUTHORIZED);
} elseif ($exception->getStatusCode() === 403) {
return Error::create()->setCode(ApiException::FORBIDDEN);
}
}
return Error::create()->setCode(ApiException::INTERNAL_SERVER_ERROR)->setStatusCode(500);
}
/**
* Fills error fields with defaults from configuration. Returns the same error object
*
* @param Error $error
* @param RestApi $api
*
* @return Error
*/
protected function fillErrorDefaults(Error $error, RestApi $api)
{
$config = $this->getErrorConfig($api, $error->getCode());
if (!$error->getMessage() && isset($config['message'])) {
$error->setMessage($config['message']);
}
if (!$error->getUri() && isset($config['uri'])) {
$error->setUri($config['uri']);
}
if (!$error->getStatusCode() && isset($config['statusCode'])) {
$error->setStatusCode($config['statusCode']);
}
return $error;
}
/**
* Returns encoder for this request and API
*
* @param Request $request
* @param RestApi $api
* @param array $options
*
* @throws Exception\ConfigurationException
* @return \Paysera\Component\Serializer\Encoding\EncoderInterface
*/
protected function getEncoderForApi(Request $request, RestApi $api, array $options = array())
{
$format = $this->formatDetector->getResponseFormat($request, $api->getAvailableResponseFormats());
$encoder = $api->getEncoder($format, $options);
if ($encoder === null) {
if (!isset($this->encoders[$format])) {
throw new ConfigurationException('Format is not supported: ' . $format);
}
$encoder = $this->encoders[$format];
}
return $encoder;
}
/**
* Returns decoder for this request and API
*
* @param Request $request
* @param RestApi $api
*
* @throws Exception\ConfigurationException
* @return \Paysera\Component\Serializer\Encoding\DecoderInterface
*/
protected function getDecoderForApi(Request $request, RestApi $api)
{
$format = $this->formatDetector->getRequestFormat($request, $api->getAvailableRequestFormats());
$decoder = $api->getDecoder($format);
if ($decoder === null) {
if (!isset($this->decoders[$format])) {
throw new ConfigurationException('Format is not supported: ' . $format);
}
$decoder = $this->decoders[$format];
}
return $decoder;
}
/**
* Returns merged configuration for error code
*
* @param RestApi $api
* @param string $errorCode
*
* @return array available keys: statusCode, message, uri; value can be null
*/
protected function getErrorConfig(RestApi $api, $errorCode)
{
$config = $api->getErrorConfig($errorCode);
if ($config === null) {
$config = array();
}
$globalConfig = $this->errorConfig->getConfig($errorCode) ?: array('statusCode' => 400);
foreach ($globalConfig as $key => $value) {
if (!isset($config[$key])) {
$config[$key] = $value;
}
}
return $config;
}
/**
* @param Request $request
* @return bool
*/
public function isRestRequest(Request $request)
{
return $this->getApiForRequest($request) !== null;
}
}