|
23 | 23 | */
|
24 | 24 | final class RequestAttributesExtractor
|
25 | 25 | {
|
| 26 | + const API_ATTRIBUTES = ['resource_class', 'format', 'mime_type']; |
| 27 | + |
26 | 28 | /**
|
27 |
| - * Extracts resource class, operation name and format request attributes. Throws an exception if the request does not contain required |
28 |
| - * attributes. |
| 29 | + * Extracts resource class, operation name and format request attributes. Throws an exception if the request does not |
| 30 | + * contain required attributes. |
29 | 31 | *
|
30 | 32 | * @param Request $request
|
31 | 33 | *
|
32 | 34 | * @throws RuntimeException
|
33 | 35 | *
|
34 |
| - * @return array [$resourceClass, $collectionOperation, $itemOperation, $format] |
| 36 | + * @return array |
35 | 37 | */
|
36 | 38 | public static function extractAttributes(Request $request)
|
37 | 39 | {
|
38 |
| - $resourceClass = $request->attributes->get('_resource_class'); |
39 |
| - if (!$resourceClass) { |
40 |
| - throw new RuntimeException('The request attribute "_resource_class" must be defined.'); |
41 |
| - } |
| 40 | + $result = []; |
| 41 | + |
| 42 | + foreach (self::API_ATTRIBUTES as $key) { |
| 43 | + $attributeKey = '_api_'.$key; |
| 44 | + $attributeValue = $request->attributes->get($attributeKey); |
42 | 45 |
|
43 |
| - $collectionOperation = $request->attributes->get('_collection_operation_name'); |
44 |
| - $itemOperation = $request->attributes->get('_item_operation_name'); |
45 |
| - if (!$itemOperation && !$collectionOperation) { |
46 |
| - throw new RuntimeException('One of the request attribute "_item_operation_name" or "_collection_operation_name" must be defined.'); |
| 46 | + if (null === $attributeValue) { |
| 47 | + throw new RuntimeException(sprintf('The request attribute "%s" must be defined.', $attributeKey)); |
| 48 | + } |
| 49 | + |
| 50 | + $result[$key] = $attributeValue; |
47 | 51 | }
|
48 | 52 |
|
49 |
| - $format = $request->attributes->get('_api_format'); |
50 |
| - if (!$format) { |
51 |
| - throw new RuntimeException('The request attribute "_api_format" must be defined.'); |
| 53 | + $collectionOperationName = $request->attributes->get('_api_collection_operation_name'); |
| 54 | + $itemOperationName = $request->attributes->get('_api_item_operation_name'); |
| 55 | + |
| 56 | + if ($collectionOperationName) { |
| 57 | + $result['collection_operation_name'] = $collectionOperationName; |
| 58 | + } elseif ($itemOperationName) { |
| 59 | + $result['item_operation_name'] = $itemOperationName; |
| 60 | + } else { |
| 61 | + throw new RuntimeException('One of the request attribute "_api_collection_operation_name" or "_api_item_operation_name" must be defined.'); |
52 | 62 | }
|
53 | 63 |
|
54 |
| - return [$resourceClass, $collectionOperation, $itemOperation, $format]; |
| 64 | + return $result; |
55 | 65 | }
|
56 | 66 | }
|
0 commit comments