-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathRestApi.php
659 lines (584 loc) · 19.5 KB
/
RestApi.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
<?php
namespace Paysera\Bundle\RestBundle;
use Closure;
use Paysera\Bundle\RestBundle\Cache\CacheStrategyInterface;
use Paysera\Bundle\RestBundle\Normalizer\NameAwareDenormalizerInterface;
use Paysera\Bundle\RestBundle\Resolver\EntityResolverInterface;
use Paysera\Bundle\RestBundle\Resolver\ServiceAwareAttributeResolver;
use Paysera\Component\Serializer\Encoding\DecoderInterface;
use Paysera\Component\Serializer\Encoding\EncoderInterface;
use Paysera\Component\Serializer\Factory\EncoderFactoryInterface;
use Paysera\Component\Serializer\Factory\ResponseMapperFactoryInterface;
use Paysera\Bundle\RestBundle\Normalizer\NameAwareDenormalizer;
use Paysera\Component\Serializer\Normalizer\DenormalizerInterface;
use Paysera\Component\Serializer\Validation\PropertyPathConverterInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Paysera\Bundle\RestBundle\Entity\ErrorConfig;
use Paysera\Bundle\RestBundle\Security\SecurityStrategyInterface;
use Paysera\Component\Serializer\Normalizer\NormalizerInterface;
class RestApi
{
const DEFAULT_VALIDATION_GROUP = 'Default';
/**
* @var Closure[]
*/
protected $requestMappers;
/**
* @var Closure[]
*/
protected $requestQueryMappers;
/**
* @var Closure[]
*/
protected $requestAttributeResolvers;
/**
* @var array[]
*/
protected $requestLoggingParts = array();
/**
* @var string[]
*/
protected $responseMappers;
/**
* @var ResponseMapperFactoryInterface[]
*/
protected $responseMapperFactories;
/**
* @var EncoderFactoryInterface[]
*/
protected $encoderFactories;
/**
* @var string[]
*/
protected $requestFormats = array();
/**
* @var string[]
*/
protected $responseFormats = array();
/**
* @var CacheStrategyInterface[]
*/
protected $cacheStrategies = array();
/**
* @var ErrorConfig
*/
protected $errorConfig;
/**
* @var SecurityStrategyInterface
*/
protected $securityStrategy;
/**
* @var ContainerInterface
*/
protected $serviceContainer;
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var array
*/
private $globalValidationGroups = [self::DEFAULT_VALIDATION_GROUP];
/**
* @var array
*/
private $validationGroups = [];
/**
* @var PropertyPathConverterInterface[]
*/
protected $controllerPropertyPathConverters = [];
/**
* @var PropertyPathConverterInterface
*/
private $propertyPathConverter;
/**
* Constructs object
*
* @param ContainerInterface $serviceContainer
* @param LoggerInterface $logger
*/
public function __construct(
ContainerInterface $serviceContainer,
LoggerInterface $logger
) {
$this->serviceContainer = $serviceContainer;
$this->logger = $logger;
$this->errorConfig = new ErrorConfig();
$this->propertyPathConverter = $serviceContainer
->get('paysera_rest.service.property_path_converter.camel_case_to_snake_case')
;
}
/**
* Adds request mapper for some controller
*
* @param string $mapperKey service key, service must implement DenormalizerInterface
* @param string $controllerKey
* @param string $argumentName
* @param array $validationGroups Validation groups
* @param PropertyPathConverterInterface|null $propertyPathConverter
*/
public function addRequestMapper(
$mapperKey,
$controllerKey,
$argumentName,
array $validationGroups = [self::DEFAULT_VALIDATION_GROUP],
$propertyPathConverter = null
) {
$controllerKey = $this->normalizeControllerKey($controllerKey);
$this->requestMappers[$controllerKey] = $this->getDenormalizerClosure($mapperKey, $argumentName);
$this->addValidationGroups($controllerKey, $validationGroups);
$this->addControllerPropertyPathConverter($controllerKey, $propertyPathConverter);
}
/**
* Adds request query mapper for some controller
*
* @param string $mapperKey service key, service must implement DenormalizerInterface
* @param string $controllerKey
* @param string $argumentName
* @param array $validationGroups Validation groups
* @param PropertyPathConverterInterface|null $propertyPathConverter
*/
public function addRequestQueryMapper(
$mapperKey,
$controllerKey,
$argumentName,
array $validationGroups = [self::DEFAULT_VALIDATION_GROUP],
$propertyPathConverter = null
) {
$controllerKey = $this->normalizeControllerKey($controllerKey);
$this->requestQueryMappers[$controllerKey] = $this->getDenormalizerClosure($mapperKey, $argumentName);
$this->addValidationGroups($controllerKey, $validationGroups);
$this->addControllerPropertyPathConverter($controllerKey, $propertyPathConverter);
}
/**
* Returns denormalizer closure
*
* @param string $mapperKey Denormalizer mapper key
* @param string $argumentName Denormalizer name
*
* @return Closure
*/
protected function getDenormalizerClosure($mapperKey, $argumentName)
{
$serviceContainer = $this->serviceContainer;
return function() use ($mapperKey, $serviceContainer, $argumentName) {
$denormalizer = $serviceContainer->get($mapperKey);
if (!$denormalizer instanceof DenormalizerInterface) {
throw new RuntimeException(
'Configured service does not implement DenormalizerInterface ' . $mapperKey
);
}
return new NameAwareDenormalizer($denormalizer, $argumentName);
};
}
/**
* Sets validation group for given controller key, or uses default validation group if given group is empty
*
* @param string $controllerKey Controller key
* @param array $validationGroups Validation group array
*/
protected function addValidationGroups($controllerKey, array $validationGroups)
{
$this->validationGroups[$controllerKey] = $validationGroups;
}
/**
* @param string $controllerKey
* @param PropertyPathConverterInterface|null $propertyPathConverter
*/
public function addControllerPropertyPathConverter($controllerKey, $propertyPathConverter)
{
if ($propertyPathConverter !== null) {
$this->controllerPropertyPathConverters[$controllerKey] = $propertyPathConverter;
}
}
/**
* @param string $controllerKey
* @param string|null $part
*/
public function dontLogRequest($controllerKey, $part = null)
{
$controllerKey = $this->normalizeControllerKey($controllerKey);
if (!$part) {
$this->requestLoggingParts[$controllerKey] = array(
'url' => false,
'header' => false,
'content' => false
);
} else {
if (!isset($this->requestLoggingParts[$controllerKey])) {
$this->requestLoggingParts[$controllerKey] = array(
'url' => true,
'header' => true,
'content' => true
);
}
$this->requestLoggingParts[$controllerKey][$part] = false;
}
}
/**
* Adds an attribute (_controller, _method etc) mapper for a specific controller
*
* @param string $serviceKey
* @param string $controllerKey
* @param string $attributeName
* @param string $parameterName
*/
public function addRequestAttributeResolver($serviceKey, $controllerKey, $attributeName, $parameterName)
{
$controllerKey = $this->normalizeControllerKey($controllerKey);
$serviceContainer = $this->serviceContainer;
if (empty($this->requestAttributeResolvers[$controllerKey])) {
$this->requestAttributeResolvers[$controllerKey] = array();
}
$this->requestAttributeResolvers[$controllerKey][] = function () use (
$serviceKey,
$serviceContainer,
$attributeName,
$parameterName
) {
$entityResolverService = $serviceContainer->get($serviceKey);
/** @var EntityResolverInterface $entityResolverService */
$implementsResolverInterface = $entityResolverService instanceof EntityResolverInterface;
if (!$implementsResolverInterface) {
throw new RuntimeException(
'The entity resolver service needs to implement EntityResolverInterface'
);
}
return new ServiceAwareAttributeResolver($entityResolverService, $attributeName, $parameterName);
};
}
/**
* Adds response mapper for some controller
*
* @param string $mapperKey service key, service must implement NormalizerInterface
* @param string $controllerKey
*/
public function addResponseMapper($mapperKey, $controllerKey)
{
$controllerKey = $this->normalizeControllerKey($controllerKey);
$this->responseMappers[$controllerKey] = $mapperKey;
}
/**
* Adds response mapper for some controller
*
* @param ResponseMapperFactoryInterface $mapperFactory
* @param string $controllerKey
*/
public function addResponseMapperFactory(ResponseMapperFactoryInterface $mapperFactory, $controllerKey)
{
$controllerKey = $this->normalizeControllerKey($controllerKey);
$this->responseMapperFactories[$controllerKey] = $mapperFactory;
}
public function addCacheStrategy(CacheStrategyInterface $cacheStrategy, $controllerKey)
{
$controllerKey = $this->normalizeControllerKey($controllerKey);
$this->cacheStrategies[$controllerKey] = $cacheStrategy;
}
/**
* Adds supported response format
*
* @param string $format
*/
public function addResponseFormat($format)
{
$this->responseFormats[] = $format;
}
/**
* Adds supported response format
*
* @param string $format
* @param EncoderFactoryInterface $encoderFactory
*/
public function addResponseEncoderFactory($format, EncoderFactoryInterface $encoderFactory)
{
$this->responseFormats[] = $format;
$this->encoderFactories[$format] = $encoderFactory;
}
/**
* Adds supported request format
*
* @param string $format
*/
public function addRequestFormat($format)
{
$this->requestFormats[] = $format;
}
/**
* @param array $validationGroups
*/
public function setValidationGroups(array $validationGroups)
{
$this->globalValidationGroups = $validationGroups;
}
/**
* Sets errorConfig
*
* @param ErrorConfig $errorConfig
*/
public function setErrorConfig($errorConfig)
{
$this->errorConfig = $errorConfig;
}
/**
* Sets securityStrategy
*
* @param SecurityStrategyInterface|null $securityStrategy
*/
public function setSecurityStrategy($securityStrategy)
{
$this->securityStrategy = $securityStrategy;
}
public function setPropertyPathConverter(PropertyPathConverterInterface $propertyPathConverter)
{
$this->propertyPathConverter = $propertyPathConverter;
}
/**
* Returns validation group array
*
* @param string $controllerKey
*
* @return array|null
*/
public function getValidationGroups($controllerKey)
{
$this->logger->debug('Getting validation group for ' . $controllerKey);
$controllerKey = $this->normalizeControllerKey($controllerKey);
if (
!array_key_exists($controllerKey, $this->validationGroups)
|| count($this->validationGroups[$controllerKey]) === 0
) {
return null;
}
return array_unique(array_merge(
$this->globalValidationGroups,
$this->validationGroups[$controllerKey]
));
}
/**
* Returns property path converters
*
* @param string $controllerKey
*
* @return PropertyPathConverterInterface[]
*/
public function getPropertyPathConverters($controllerKey)
{
$this->logger->debug('Getting property path converters for ' . $controllerKey);
$controllerKey = $this->normalizeControllerKey($controllerKey);
$propertyPathConverters = [$this->propertyPathConverter];
if (isset($this->controllerPropertyPathConverters[$controllerKey])) {
$propertyPathConverters[] = $this->controllerPropertyPathConverters[$controllerKey];
}
return $propertyPathConverters;
}
/**
* Should return request mapper for this controller. If none is set, returns null
*
* @param string $controllerKey
*
* @return NameAwareDenormalizerInterface|null
*/
public function getRequestMapper($controllerKey)
{
$this->logger->debug('Getting request mapper for ' . $controllerKey);
$controllerKey = $this->normalizeControllerKey($controllerKey);
if (isset($this->requestMappers[$controllerKey])) {
$closure = $this->requestMappers[$controllerKey];
return $closure();
}
return null;
}
/**
* Should return request query mapper for this controller. If none is set, returns null
*
* @param string $controllerKey
*
* @return NameAwareDenormalizerInterface|null
*/
public function getRequestQueryMapper($controllerKey)
{
$this->logger->debug('Getting request query mapper for ' . $controllerKey);
$controllerKey = $this->normalizeControllerKey($controllerKey);
if (isset($this->requestQueryMappers[$controllerKey])) {
$closure = $this->requestQueryMappers[$controllerKey];
return $closure();
}
return null;
}
/**
* returns if controlers request body should be logged or not
*
* @param string $controllerKey
*
* @return array
*/
public function getRequestLoggingParts($controllerKey)
{
$controllerKey = $this->normalizeControllerKey($controllerKey);
if (isset($this->requestLoggingParts[$controllerKey])) {
return $this->requestLoggingParts[$controllerKey];
}
return array(
'url' => true,
'header' => true,
'content' => false
);
}
/**
* Should return a request parameter (_controller, _method etc) mapper. If none is set, returns null
*
* @param string $controllerKey
*
* @return NameAwareDenormalizerInterface|null|array
*/
public function getRequestAttributeResolvers($controllerKey)
{
$this->logger->debug('Getting request attribute mapper for ' . $controllerKey);
$controllerKey = $this->normalizeControllerKey($controllerKey);
if (isset($this->requestAttributeResolvers[$controllerKey])) {
/** @var Closure[] $closures */
$closures = $this->requestAttributeResolvers[$controllerKey];
return array_map(
function ($closure) {
return $closure();
},
$closures
);
}
return array();
}
/**
* Should return response mapper for this controller. If none is set, returns null
*
* @param string $controllerKey
* @param array $options
*
* @return NormalizerInterface|null
*/
public function getResponseMapper($controllerKey, array $options = array())
{
$this->logger->debug('Getting response mapper for ' . $controllerKey);
$controllerKey = $this->normalizeControllerKey($controllerKey);
if (isset($this->responseMapperFactories[$controllerKey])) {
return $this->responseMapperFactories[$controllerKey]->createResponseMapper($options);
}
return isset($this->responseMappers[$controllerKey])
? $this->serviceContainer->get($this->responseMappers[$controllerKey])
: null
;
}
/**
* @param string $controllerKey
* @param array $options
*
* @return CacheStrategyInterface|null
*/
public function getCacheStrategy($controllerKey, array $options = array())
{
if (isset($options[CacheStrategyInterface::NO_CACHE]) && $options[CacheStrategyInterface::NO_CACHE]) {
return null;
}
$controllerKey = $this->normalizeControllerKey($controllerKey);
return isset($this->cacheStrategies[$controllerKey])
? $this->cacheStrategies[$controllerKey]
: null
;
}
/**
* Returns formats that are available to format response
*
* @return string[]
*/
public function getAvailableResponseFormats()
{
return empty($this->responseFormats) ? array('json') : $this->responseFormats;
}
/**
* Returns formats that are available to parse request content
*
* @return string[]
*/
public function getAvailableRequestFormats()
{
return empty($this->requestFormats) ? array('json') : $this->requestFormats;
}
/**
* Returns decoder for specified format. Returns null if default decoder is to be used
*
* @param string $format
*
* @return DecoderInterface
*/
public function getDecoder($format)
{
return null;
}
/**
* Returns encoder for specified format. Returns null if default encoder is to be used
*
* @param string $format
* @param array $options
*
* @return EncoderInterface
*/
public function getEncoder($format, array $options = array())
{
return isset($this->encoderFactories[$format])
? $this->encoderFactories[$format]->createEncoder($options)
: null
;
}
/**
* @return SecurityStrategyInterface|null
*/
public function getSecurityStrategy()
{
return $this->securityStrategy;
}
/**
* Returns configuration for error code. Can return null to use default configuration or leave some information
* empty
*
* @param string $errorCode
*
* @return array|null available keys: statusCode, message, uri; value can be null
*/
public function getErrorConfig($errorCode)
{
return $this->errorConfig->getConfig($errorCode);
}
/**
* @return LoggerInterface
*/
public function getLogger()
{
return $this->logger;
}
/**
* Returns controller key without namespace prefix. Ie ApiController::getPaymentAction
*
* @param string $controllerKey
*
* @return string
*/
protected function normalizeControllerKey($controllerKey)
{
if ($controllerKey === null) {
return null;
}
$i = strpos($controllerKey, '\\Controller\\');
if ($i !== false) {
$controllerKey = substr($controllerKey, $i + 12);
}
$controllerKey = str_replace('::', ':', $controllerKey);
$parts = explode(':', $controllerKey);
if (count($parts) !== 2) {
return null;
}
$controller = preg_replace('/Controller$/', '', $parts[0]);
$action = preg_replace('/Action$/', '', $parts[1]);
return $controller . ':' . $action;
}
}