Passed
Pull Request — master (#255)
by Alex
03:12
created

ChangeSetParser::handleData()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 4
eloc 14
c 4
b 1
f 0
nc 4
nop 0
dl 0
loc 18
rs 9.7998
1
<?php
2
3
declare(strict_types=1);
4
5
namespace POData\BatchProcessor;
6
7
use Exception;
8
use POData\BaseService;
9
use POData\Common\ODataException;
10
use POData\Common\UrlFormatException;
11
use POData\OperationContext\HTTPRequestMethod;
12
use POData\OperationContext\ServiceHost;
13
use POData\OperationContext\Web\IncomingRequest;
14
use POData\OperationContext\Web\WebOperationContext;
15
16
/**
17
 * Class ChangeSetParser.
18
 * @package POData\BatchProcessor
19
 */
20
class ChangeSetParser implements IBatchParser
21
{
22
    protected $data;
23
    protected $changeSetBoundary;
24
    /**
25
     * @var WebOperationContext[]
26
     */
27
    protected $rawRequests = [];
28
    protected $service;
29
    protected $contentIDToLocationLookup = [];
30
31
    /**
32
     * ChangeSetParser constructor.
33
     * @param BaseService $service
34
     * @param $body
35
     */
36
    public function __construct(BaseService $service, $body)
37
    {
38
        $this->service            = $service;
39
        $this->data               = trim(str_replace("\r", '', $body)); // removes windows specific character
40
    }
41
42
    /**
43
     * @return mixed
44
     */
45
    public function getBoundary()
46
    {
47
        return $this->changeSetBoundary;
48
    }
49
50
    /**
51
     * @throws ODataException
52
     * @throws UrlFormatException
53
     * @throws Exception
54
     */
55
    public function process()
56
    {
57
        $raw = $this->getRawRequests();
58
        foreach ($raw as $contentID => &$workingObject) {
59
            foreach ($this->contentIDToLocationLookup as $lookupID => $location) {
60
                if (0 > $lookupID) {
61
                    continue;
62
                }
63
                $workingObject->incomingRequest()->applyContentID($lookupID, $location);
0 ignored issues
show
Bug introduced by
The method applyContentID() does not exist on POData\OperationContext\Web\IncomingRequest. It seems like you code against a sub-type of POData\OperationContext\Web\IncomingRequest such as POData\BatchProcessor\IncomingChangeSetRequest. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

63
                $workingObject->incomingRequest()->/** @scrutinizer ignore-call */ applyContentID($lookupID, $location);
Loading history...
64
            }
65
66
            $this->processSubRequest($workingObject);
67
            if (HTTPRequestMethod::GET() != $workingObject->incomingRequest()->getMethod() &&
68
                strpos($workingObject->incomingRequest()->getRawUrl(), '/$links/') === false) {
69
                if (null === $workingObject->outgoingResponse()->getHeaders()['Location']) {
70
                    $msg = 'Location header not set in subrequest response for ' . $workingObject->incomingRequest()->getMethod()
71
                        . ' request url ' . $workingObject->incomingRequest()->getRawUrl();
72
                    throw new Exception($msg);
73
                }
74
                $this->contentIDToLocationLookup[$contentID] = $workingObject->outgoingResponse()->getHeaders()['Location'];
75
            }
76
        }
77
    }
78
79
    /**
80
     * @return WebOperationContext[]
81
     */
82
    public function getRawRequests()
83
    {
84
        return $this->rawRequests;
85
    }
86
87
    /**
88
     * @param $newContext
89
     * @throws ODataException
90
     * @throws UrlFormatException
91
     */
92
    protected function processSubRequest(&$newContext)
93
    {
94
        $newHost    = new ServiceHost($newContext);
95
        $oldHost    = $this->getService()->getHost();
96
        $this->getService()->setHost($newHost);
97
        $this->getService()->handleRequest();
98
        $this->getService()->setHost($oldHost);
99
    }
100
101
    /**
102
     * @return BaseService
103
     */
104
    public function getService()
105
    {
106
        return $this->service;
107
    }
108
109
    /**
110
     * @return string
111
     */
112
    public function getResponse()
113
    {
114
        $ODataEOL = $this->getService()->getConfiguration()->getLineEndings();
115
116
        $response = '';
117
        $splitter = false === $this->changeSetBoundary ?
118
            '' :
119
            '--' . $this->changeSetBoundary . $ODataEOL;
120
        $raw = $this->getRawRequests();
121
        foreach ($raw as $contentID => &$workingObject) {
122
            $headers = $workingObject->outgoingResponse()->getHeaders();
123
            $response .= $splitter;
124
125
            $response .= 'Content-Type: application/http' . $ODataEOL;
126
            $response .= 'Content-Transfer-Encoding: binary' . $ODataEOL;
127
            $response .= $ODataEOL;
128
            $response .= 'HTTP/1.1 ' . $headers['Status'] . $ODataEOL;
129
            $response .= 'Content-ID: ' . $contentID . $ODataEOL;
130
131
            foreach ($headers as $headerName => $headerValue) {
132
                if (null !== $headerValue) {
133
                    $response .= $headerName . ': ' . $headerValue . $ODataEOL;
134
                }
135
            }
136
            $response .= $ODataEOL;
137
            $response .= $workingObject->outgoingResponse()->getStream();
138
        }
139
        $response .= trim($splitter);
140
        $response .= false === $this->changeSetBoundary ?
141
            $ODataEOL :
142
            '--' . $ODataEOL;
143
        $response = 'Content-Length: ' .
144
            strlen($response) .
145
            $ODataEOL .
146
            $ODataEOL .
147
            $response;
148
        $response = false === $this->changeSetBoundary ?
149
            $response :
150
            'Content-Type: multipart/mixed; boundary=' .
151
            $this->changeSetBoundary .
152
            $ODataEOL .
153
            $response;
154
        return $response;
155
    }
156
157
    public function handleData()
158
    {
159
        list($headerBlock, $contentBlock) = explode("\n\n", $this->getData(), 2);
160
        $headers                          = self::parse_headers($headerBlock);
161
        $this->changeSetBoundary          = $headers['Content-Type']['boundary'];
162
        $matches                          = array_filter(explode('--' . $this->changeSetBoundary, $contentBlock));
163
        $contentIDinit                    = -1;
164
        foreach ($matches as $match) {
165
            if ('--' === trim($match)) {
166
                continue;
167
            }
168
            $request   = new IncomingChangeSetRequest($match);
169
            $contentID = $request->getContentId() ?? $contentIDinit;
170
            $this->rawRequests[$contentID] = new WebOperationContext($request);
171
            if ($contentIDinit == $contentID) {
172
                $contentIDinit--;
173
            }
174
            continue;
175
        }
176
    }
177
178
    /**
179
     * @return string
180
     */
181
    public function getData()
182
    {
183
        return $this->data;
184
    }
185
    private static function parse_headers($headers, $splitter = "\n", $assignmentChar = ':')
186
    {
187
        $results = [];
188
        foreach (array_filter(explode($splitter, trim($headers))) as $line) {
189
            list($key, $value) = strpos($line, $assignmentChar) !== false ? explode($assignmentChar, $line, 2) : ['default', $line];
190
            $key               = trim($key);
191
            $value             = trim($value);
192
            if (strpos($value, ';') !== false) {
193
                $value = self::parse_headers($value, ';', '=');
194
            }
195
            $results[$key] = $value;
196
        }
197
        return $results;
198
    }
199
}
200