Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
contenttype.php
1<?php
3
8
13final class ContentType extends Base
14{
15 const JSON = 'application/json';
16 const ERROR_INVALID_CONTENT_TYPE = 'invalid_content_type';
17
19 private $allowedTypes;
20
26 public function __construct(array $allowedTypes = [])
27 {
28 $this->allowedTypes = $allowedTypes;
29 parent::__construct();
30 }
31
38 public function onBeforeAction(Event $event)
39 {
40 $contentType = $this->getRequestContentType();
41 if (!in_array($contentType, $this->allowedTypes, true))
42 {
43 $this->addError(new Error(
44 "Wrong content type for current action. `"
45 . implode('`, `', $this->allowedTypes)
46 . "` expected, `{$contentType}` got.",
47 self::ERROR_INVALID_CONTENT_TYPE
48 ));
49
50 return new EventResult(EventResult::ERROR, null, null, $this);
51 }
52
53 switch ($this->getRequestContentType())
54 {
55 case self::JSON:
56 $jsonPayload = new Engine\JsonPayload();
57 $this->setActionSourceParametersToMap($jsonPayload);
58 break;
59 }
60
61 return null;
62 }
63
64 protected function setActionSourceParametersToMap(Engine\JsonPayload $payload)
65 {
66 $payload = $payload->getData();
67 if (!is_array($payload))
68 {
69 return;
70 }
71
72 $parameters = [];
73 foreach ($payload as $key => $value)
74 {
75 if ($key && !is_numeric($key))
76 {
77 $parameters[$key] = $value;
78 }
79 }
80
81 if (!$parameters)
82 {
83 return;
84 }
85
86 $controller = $this->getAction()->getController();
87 $controller->setSourceParametersList(array_merge(
88 $controller->getSourceParametersList(),
89 [$parameters]
90 ));
91 }
92
93 protected function getRequestContentType()
94 {
95 return $this->getAction()->getController()->getRequest()->getHeaders()->getContentType();
96 }
97}
setActionSourceParametersToMap(Engine\JsonPayload $payload)