Passed
Pull Request — master (#267)
by Christopher
03:19
created

BaseService::handleBatchRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 1
eloc 9
c 4
b 1
f 0
nc 1
nop 1
dl 0
loc 12
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace POData;
6
7
use Exception;
8
use POData\BatchProcessor\BatchProcessor;
9
use POData\Common\ErrorHandler;
10
use POData\Common\HttpStatus;
11
use POData\Common\InvalidOperationException;
12
use POData\Common\Messages;
13
use POData\Common\MimeTypes;
14
use POData\Common\ODataConstants;
15
use POData\Common\ODataException;
16
use POData\Common\ReflectionHandler;
17
use POData\Common\Version;
18
use POData\Configuration\IServiceConfiguration;
19
use POData\Configuration\ServiceConfiguration;
20
use POData\ObjectModel\IObjectSerialiser;
21
use POData\ObjectModel\ObjectModelSerializer;
22
use POData\ObjectModel\ODataFeed;
23
use POData\ObjectModel\ODataURLCollection;
24
use POData\OperationContext\HTTPRequestMethod;
25
use POData\OperationContext\IOperationContext;
26
use POData\OperationContext\ServiceHost;
27
use POData\Providers\Metadata\IMetadataProvider;
28
use POData\Providers\Metadata\ResourceType;
29
use POData\Providers\Metadata\Type\Binary;
30
use POData\Providers\Metadata\Type\IType;
31
use POData\Providers\ProvidersWrapper;
32
use POData\Providers\Query\IQueryProvider;
33
use POData\Providers\Query\QueryResult;
34
use POData\Providers\Stream\IStreamProvider2;
35
use POData\Providers\Stream\StreamProviderWrapper;
36
use POData\Readers\Atom\AtomODataReader;
37
use POData\Readers\ODataReaderRegistry;
38
use POData\UriProcessor\Interfaces\IUriProcessor;
39
use POData\UriProcessor\RequestDescription;
40
use POData\UriProcessor\ResourcePathProcessor\SegmentParser\TargetKind;
41
use POData\UriProcessor\UriProcessorNew;
42
use POData\Writers\Atom\AtomODataWriter;
43
use POData\Writers\Json\JsonLightMetadataLevel;
44
use POData\Writers\Json\JsonLightODataWriter;
45
use POData\Writers\Json\JsonODataV1Writer;
46
use POData\Writers\Json\JsonODataV2Writer;
47
use POData\Writers\ODataWriterRegistry;
48
use POData\Writers\ResponseWriter;
49
use ReflectionException;
50
51
/**
52
 * Class BaseService.
53
 *
54
 * The base class for all BaseService specific classes. This class implements
55
 * the following interfaces:
56
 *  (1) IRequestHandler
57
 *      Implementing this interface requires defining the function
58
 *      'handleRequest' that will be invoked by dispatcher
59
 *  (2) IService
60
 *      Force BaseService class to implement functions for custom
61
 *      data service providers
62
 */
63
abstract class BaseService implements IRequestHandler, IService
64
{
65
    /**
66
     * The wrapper over IStreamProvider implementation.
67
     *
68
     * @var StreamProviderWrapper
69
     */
70
    protected $streamProvider;
71
    /**
72
     * To hold reference to ServiceConfiguration instance where the
73
     * service specific rules (page limit, resource set access rights
74
     * etc...) are defined.
75
     *
76
     * @var IServiceConfiguration
77
     */
78
    protected $config;
79
    /**
80
     * Hold reference to object serialiser - bit wot turns PHP objects
81
     * into message traffic on wire.
82
     *
83
     * @var IObjectSerialiser
84
     */
85
    protected $objectSerialiser;
86
    /** @var ODataWriterRegistry */
87
    protected $writerRegistry;
88
    /** @var ODataReaderRegistry */
89
    protected $readerRegistry;
90
    /**
91
     * The wrapper over IQueryProvider and IMetadataProvider implementations.
92
     *
93
     * @var ProvidersWrapper
94
     */
95
    private $providersWrapper;
96
    /**
97
     * Hold reference to the ServiceHost instance created by dispatcher,
98
     * using this library can access headers and body of Http Request
99
     * dispatcher received and the Http Response Dispatcher is going to send.
100
     *
101
     * @var ServiceHost
102
     */
103
    private $serviceHost;
104
105
    /**
106
     * BaseService constructor.
107
     * @param  IObjectSerialiser|null     $serialiser
108
     * @param  IMetadataProvider|null     $metaProvider
109
     * @param  IServiceConfiguration|null $config
110
     * @throws Exception
111
     */
112
    protected function __construct(
113
        IObjectSerialiser $serialiser = null,
114
        IMetadataProvider $metaProvider = null,
115
        IServiceConfiguration $config = null
116
    ) {
117
        if (null != $serialiser) {
118
            $serialiser->setService($this);
119
        } else {
120
            $serialiser = new ObjectModelSerializer($this, null);
121
        }
122
        $this->config           = $config ?? $this->initializeDefaultConfig(new ServiceConfiguration($metaProvider));
123
        $this->objectSerialiser = $serialiser;
124
    }
125
126
    //TODO: shouldn't we hide this from the interface..if we need it at all.
127
128
    protected function initializeDefaultConfig(IServiceConfiguration $config)
129
    {
130
        return $config;
131
    }
132
133
    /**
134
     * Sets the data service host instance.
135
     *
136
     * @param ServiceHost $serviceHost The data service host instance
137
     */
138
    public function setHost(ServiceHost $serviceHost): void
139
    {
140
        $this->serviceHost = $serviceHost;
141
    }
142
143
    /**
144
     * To get reference to operation context where we have direct access to
145
     * headers and body of Http Request, we have received and the Http Response
146
     * We are going to send.
147
     *
148
     * @return IOperationContext
149
     */
150
    public function getOperationContext(): IOperationContext
151
    {
152
        return $this->getHost()->getOperationContext();
153
    }
154
155
    /**
156
     * Get reference to the data service host instance.
157
     *
158
     * @return ServiceHost
159
     */
160
    public function getHost(): ServiceHost
161
    {
162
        assert(null != $this->serviceHost);
163
164
        return $this->serviceHost;
165
    }
166
167
    /**
168
     * Get reference to the wrapper over IStreamProvider or
169
     * IStreamProvider2 implementations.
170
     *
171
     * @return StreamProviderWrapper
172
     */
173
    public function getStreamProvider(): StreamProviderWrapper
174
    {
175
        if (null === $this->streamProvider) {
176
            $this->streamProvider = new StreamProviderWrapper();
177
            $this->streamProvider->setService($this);
178
        }
179
180
        return $this->streamProvider;
181
    }
182
183
    /**
184
     * Top-level handler invoked by Dispatcher against any request to this
185
     * service. This method will hand over request processing task to other
186
     * functions which process the request, set required headers and Response
187
     * stream (if any in Atom/Json format) in
188
     * WebOperationContext::Current()::OutgoingWebResponseContext.
189
     * Once this function returns, dispatcher uses global WebOperationContext
190
     * to write out the request response to client.
191
     * This function will perform the following operations:
192
     * (1) Check whether the top level service class implements
193
     *     IServiceProvider which means the service is a custom service, in
194
     *     this case make sure the top level service class implements
195
     *     IMetaDataProvider and IQueryProvider.
196
     *     These are the minimal interfaces that a custom service to be
197
     *     implemented in order to expose its data as OData. Save reference to
198
     *     These interface implementations.
199
     *     NOTE: Here we will ensure only providers for IDSQP and IDSMP. The
200
     *     IDSSP will be ensured only when there is an GET request on MLE/Named
201
     *     stream.
202
     *
203
     * (2). Invoke 'Initialize' method of top level service for
204
     *      collecting the configuration rules set by the developer for this
205
     *      service.
206
     *
207
     * (3). Invoke the Uri processor to process the request URI. The uri
208
     *      processor will do the following:
209
     *      (a). Validate the request uri syntax using OData uri rules
210
     *      (b). Validate the request using metadata of this service
211
     *      (c). Parse the request uri and using, IQueryProvider
212
     *           implementation, fetches the resources pointed by the uri
213
     *           if required
214
     *      (d). Build a RequestDescription which encapsulate everything
215
     *           related to request uri (e.g. type of resource, result
216
     *           etc...)
217
     * (3). Invoke handleRequest2 for further processing
218
     * @throws ODataException
219
     */
220
    public function handleRequest()
221
    {
222
        try {
223
            $this->createProviders();
224
            $this->getHost()->validateQueryParameters();
225
            $uriProcessor = UriProcessorNew::process($this);
226
            $request      = $uriProcessor->getRequest();
227
            if (TargetKind::BATCH() == $request->getTargetKind()) {
228
                //dd($request);
229
                $this->getProvidersWrapper()->startTransaction(true);
230
                try {
231
                    $this->handleBatchRequest($request);
232
                } catch (Exception $ex) {
233
                    $this->getProvidersWrapper()->rollBackTransaction();
234
                    throw $ex;
235
                }
236
                $this->getProvidersWrapper()->commitTransaction();
237
            } else {
238
                $this->serializeResult($request, $uriProcessor);
239
            }
240
        } catch (Exception $exception) {
241
            ErrorHandler::handleException($exception, $this);
242
            // Return to dispatcher for writing serialized exception
243
            return;
244
        }
245
    }
246
247
    /**
248
     * This method will query and validates for IMetadataProvider and IQueryProvider implementations, invokes
249
     * BaseService::Initialize to initialize service specific policies.
250
     *
251
     * @throws ODataException
252
     * @throws Exception
253
     */
254
    protected function createProviders()
255
    {
256
        $metadataProvider = $this->getMetadataProvider();
257
        if (null === $metadataProvider) {
258
            throw ODataException::createInternalServerError(Messages::providersWrapperNull());
259
        }
260
261
        if (!$metadataProvider instanceof IMetadataProvider) {
0 ignored issues
show
introduced by
$metadataProvider is always a sub-type of POData\Providers\Metadata\IMetadataProvider.
Loading history...
262
            throw ODataException::createInternalServerError(Messages::invalidMetadataInstance());
263
        }
264
265
        $queryProvider = $this->getQueryProvider();
266
267
        if (null === $queryProvider) {
268
            throw ODataException::createInternalServerError(Messages::providersWrapperNull());
269
        }
270
271
        $this->providersWrapper = new ProvidersWrapper(
272
            $metadataProvider,
273
            $queryProvider,
274
            $this->config
275
        );
276
277
        $this->initialize($this->config);
278
279
        //TODO: this seems like a bad spot to do this
280
        $this->writerRegistry = new ODataWriterRegistry();
281
        $this->readerRegistry = new ODataReaderRegistry();
282
        $this->registerWriters();
283
        $this->registerReaders();
284
    }
285
286
    /**
287
     * @return IMetadataProvider
288
     */
289
    abstract public function getMetadataProvider();
290
291
    /**
292
     * @return IQueryProvider|null
293
     */
294
    abstract public function getQueryProvider(): ?IQueryProvider;
295
296
    /**
297
     * @throws Exception
298
     */
299
    public function registerWriters()
300
    {
301
        $registry       = $this->getODataWriterRegistry();
302
        $serviceVersion = $this->getConfiguration()->getMaxDataServiceVersion();
303
        $serviceURI     = $this->getHost()->getAbsoluteServiceUri()->getUrlAsString();
304
305
        //We always register the v1 stuff
306
        $registry->register(
307
            new JsonODataV1Writer(
308
                $this->getConfiguration()->getLineEndings(),
309
                $this->getConfiguration()->getPrettyOutput()
310
            )
311
        );
312
        $registry->register(
313
            new AtomODataWriter(
314
                $this->getConfiguration()->getLineEndings(),
315
                $this->getConfiguration()->getPrettyOutput(),
316
                $serviceURI
317
            )
318
        );
319
320
        if (-1 < $serviceVersion->compare(Version::v2())) {
321
            $registry->register(
322
                new JsonODataV2Writer(
323
                    $this->getConfiguration()->getLineEndings(),
324
                    $this->getConfiguration()->getPrettyOutput()
325
                )
326
            );
327
        }
328
329
        if (-1 < $serviceVersion->compare(Version::v3())) {
330
            $registry->register(
331
                new JsonLightODataWriter(
332
                    $this->getConfiguration()->getLineEndings(),
333
                    $this->getConfiguration()->getPrettyOutput(),
334
                    JsonLightMetadataLevel::NONE(),
335
                    $serviceURI
336
                )
337
            );
338
            $registry->register(
339
                new JsonLightODataWriter(
340
                    $this->getConfiguration()->getLineEndings(),
341
                    $this->getConfiguration()->getPrettyOutput(),
342
                    JsonLightMetadataLevel::MINIMAL(),
343
                    $serviceURI
344
                )
345
            );
346
            $registry->register(
347
                new JsonLightODataWriter(
348
                    $this->getConfiguration()->getLineEndings(),
349
                    $this->getConfiguration()->getPrettyOutput(),
350
                    JsonLightMetadataLevel::FULL(),
351
                    $serviceURI
352
                )
353
            );
354
        }
355
    }
356
357
    /**
358
     * Returns the ODataWriterRegistry to use when writing the response to a service document or resource request.
359
     *
360
     * @return ODataWriterRegistry
361
     */
362
    public function getODataWriterRegistry(): ODataWriterRegistry
363
    {
364
        assert(null != $this->writerRegistry);
365
366
        return $this->writerRegistry;
367
    }
368
369
    /**
370
     * Gets reference to ServiceConfiguration instance so that
371
     * service specific rules defined by the developer can be
372
     * accessed.
373
     *
374
     * @return IServiceConfiguration
375
     */
376
    public function getConfiguration(): IServiceConfiguration
377
    {
378
        assert(null != $this->config);
379
380
        return $this->config;
381
    }
382
383
    public function registerReaders()
384
    {
385
        $registry = $this->getODataReaderRegistry();
386
        //We always register the v1 stuff
387
        $registry->register(new AtomODataReader());
388
    }
389
390
    /**
391
     * Returns the ODataReaderRegistry to use when writing the response to a service document or resource request.
392
     *
393
     * @return ODataReaderRegistry
394
     */
395
    public function getODataReaderRegistry(): ODataReaderRegistry
396
    {
397
        assert(null != $this->writerRegistry);
398
399
        return $this->readerRegistry;
400
    }
401
402
    /**
403
     * Get the wrapper over developer's IQueryProvider and IMetadataProvider implementation.
404
     *
405
     * @return ProvidersWrapper
406
     */
407
    public function getProvidersWrapper(): ProvidersWrapper
408
    {
409
        return $this->providersWrapper;
410
    }
411
412
    /**
413
     * @param $request
414
     * @throws ODataException
415
     */
416
    private function handleBatchRequest($request)
417
    {
418
        $cloneThis      = clone $this;
419
        $batchProcessor = new BatchProcessor($cloneThis, $request);
420
        $batchProcessor->handleBatch();
421
        $response = $batchProcessor->getResponse();
422
        $this->getHost()->setResponseStatusCode(HttpStatus::CODE_ACCEPTED);
423
        $this->getHost()->setResponseContentType('multipart/mixed; boundary=' . $batchProcessor->getBoundary());
424
        // Hack: this needs to be sorted out in the future as we hookup other versions.
425
        $this->getHost()->setResponseVersion('3.0;');
426
        $this->getHost()->setResponseCacheControl(ODataConstants::HTTPRESPONSE_HEADER_CACHECONTROL_NOCACHE);
427
        $this->getHost()->getOperationContext()->outgoingResponse()->setStream($response);
428
    }
429
430
    //TODO: i don't want this to be public..but it's the only way to test it right now...
431
432
    /**
433
     * Serialize the requested resource.
434
     *
435
     * @param RequestDescription $request      The description of the request  submitted by the client
436
     * @param IUriProcessor      $uriProcessor Reference to the uri processor
437
     *
438
     * @throws Common\HttpHeaderFailure
439
     * @throws Common\UrlFormatException
440
     * @throws InvalidOperationException
441
     * @throws ODataException
442
     * @throws ReflectionException
443
     * @throws Exception
444
     */
445
    protected function serializeResult(RequestDescription $request, IUriProcessor $uriProcessor)
446
    {
447
448
        if ($this->getConfiguration()->getValidateETagHeader() && !$request->isETagHeaderAllowed() &&
449
            (null !== $this->getHost()->getRequestIfMatch() || null !== $this->getHost()->getRequestIfNoneMatch())) {
450
            throw ODataException::createBadRequestError(
451
                Messages::eTagCannotBeSpecified($this->getHost()->getAbsoluteRequestUri()->getUrlAsString())
452
            );
453
        }
454
455
456
        $responseContentType = $this->getResponseContentType($request, $uriProcessor);
457
458
        if (null === $responseContentType && $request->getTargetKind() != TargetKind::MEDIA_RESOURCE()) {
459
            //the responseContentType can ONLY be null if it's a stream (media resource) and
460
            // that stream is storing null as the content type
461
            throw new ODataException(Messages::unsupportedMediaType(), 415);
462
        }
463
464
        $odataModelInstance = null;
465
        $hasResponseBody    = true;
466
        // Execution required at this point if request points to any resource other than
467
468
        // (1) media resource - For Media resource 'getResponseContentType' already performed execution as
469
        // it needs to know the mime type of the stream
470
        // (2) metadata - internal resource
471
        // (3) service directory - internal resource
472
        if ($request->needExecution()) {
473
            $method = $this->getHost()->getOperationContext()->incomingRequest()->getMethod();
474
            $uriProcessor->execute();
475
            if (HTTPRequestMethod::DELETE() == $method) {
476
                $this->getHost()->setResponseStatusCode(HttpStatus::CODE_NOCONTENT);
477
478
                return;
479
            }
480
481
            $objectModelSerializer = $this->getObjectSerialiser();
482
            $objectModelSerializer->setRequest($request);
483
484
            $targetResourceType = $request->getTargetResourceType();
485
            if (null === $targetResourceType) {
486
                throw new InvalidOperationException('Target resource type cannot be null');
487
            }
488
489
            $methodIsNotPost   = (HTTPRequestMethod::POST() != $method);
490
            $methodIsNotDelete = (HTTPRequestMethod::DELETE() != $method);
491
            if (!$request->isSingleResult() && $methodIsNotPost) {
492
                // Code path for collection (feed or links)
493
                $entryObjects = $request->getTargetResult();
494
                if (!$entryObjects instanceof QueryResult) {
495
                    throw new InvalidOperationException('!$entryObjects instanceof QueryResult');
496
                }
497
                if (!is_array($entryObjects->results)) {
498
                    throw new InvalidOperationException('!is_array($entryObjects->results)');
499
                }
500
                // If related resource set is empty for an entry then we should
501
                // not throw error instead response must be empty feed or empty links
502
                if ($request->isLinkUri()) {
503
                    $odataModelInstance = $objectModelSerializer->writeUrlElements($entryObjects);
504
                    if (!$odataModelInstance instanceof ODataURLCollection) {
0 ignored issues
show
introduced by
$odataModelInstance is always a sub-type of POData\ObjectModel\ODataURLCollection.
Loading history...
505
                        throw new InvalidOperationException('!$odataModelInstance instanceof ODataURLCollection');
506
                    }
507
                } else {
508
                    $odataModelInstance = $objectModelSerializer->writeTopLevelElements($entryObjects);
509
                    if (!$odataModelInstance instanceof ODataFeed) {
0 ignored issues
show
introduced by
$odataModelInstance is always a sub-type of POData\ObjectModel\ODataFeed.
Loading history...
510
                        throw new InvalidOperationException('!$odataModelInstance instanceof ODataFeed');
511
                    }
512
                }
513
            } else {
514
                // Code path for entity, complex, bag, resource reference link,
515
                // primitive type or primitive value
516
                $result = $request->getTargetResult();
517
                if (!$result instanceof QueryResult) {
518
                    $result          = new QueryResult();
519
                    $result->results = $request->getTargetResult();
520
                }
521
                $requestTargetKind = $request->getTargetKind();
522
                $requestProperty   = $request->getProjectedProperty();
523
                if ($request->isLinkUri()) {
524
                    // In the query 'Orders(1245)/$links/Customer', the targeted
525
                    // Customer might be null
526
                    if (null === $result->results && $methodIsNotPost && $methodIsNotDelete) {
527
                        throw ODataException::createResourceNotFoundError($request->getIdentifier());
528
                    }
529
                    if ($methodIsNotPost && $methodIsNotDelete) {
530
                        $odataModelInstance = $objectModelSerializer->writeUrlElement($result);
531
                    }
532
                } elseif (TargetKind::RESOURCE() == $requestTargetKind
533
                    || TargetKind::SINGLETON() == $requestTargetKind) {
534
                    if (null !== $this->getHost()->getRequestIfMatch()
535
                        && null !== $this->getHost()->getRequestIfNoneMatch()
536
                    ) {
537
                        throw ODataException::createBadRequestError(
538
                            Messages::bothIfMatchAndIfNoneMatchHeaderSpecified()
539
                        );
540
                    }
541
                    // handle entry resource
542
                    $needToSerializeResponse = true;
543
                    $eTag                    = $this->compareETag(
544
                        $result,
545
                        $targetResourceType,
546
                        $needToSerializeResponse
547
                    );
548
                    if ($needToSerializeResponse) {
549
                        if (null === $result || null === $result->results) {
550
                            // In the query 'Orders(1245)/Customer', the targeted
551
                            // Customer might be null
552
                            // set status code to 204 => 'No Content'
553
                            $this->getHost()->setResponseStatusCode(HttpStatus::CODE_NOCONTENT);
554
                            $hasResponseBody = false;
555
                        } else {
556
                            $odataModelInstance = $objectModelSerializer->writeTopLevelElement($result);
557
                        }
558
                    } else {
559
                        // Resource is not modified so set status code
560
                        // to 304 => 'Not Modified'
561
                        $this->getHost()->setResponseStatusCode(HttpStatus::CODE_NOT_MODIFIED);
562
                        $hasResponseBody = false;
563
                    }
564
565
                    // if resource has eTagProperty then eTag header needs to written
566
                    if (null !== $eTag) {
567
                        $this->getHost()->setResponseETag($eTag);
568
                    }
569
                } elseif (TargetKind::COMPLEX_OBJECT() == $requestTargetKind) {
570
                    if (null === $requestProperty) {
571
                        throw new InvalidOperationException('Projected request property cannot be null');
572
                    }
573
                    $odataModelInstance = $objectModelSerializer->writeTopLevelComplexObject(
574
                        $result,
575
                        $requestProperty->getName(),
576
                        $targetResourceType
577
                    );
578
                } elseif (TargetKind::BAG() == $requestTargetKind) {
579
                    if (null === $requestProperty) {
580
                        throw new InvalidOperationException('Projected request property cannot be null');
581
                    }
582
                    $odataModelInstance = $objectModelSerializer->writeTopLevelBagObject(
583
                        $result,
584
                        $requestProperty->getName(),
585
                        $targetResourceType
586
                    );
587
                } elseif (TargetKind::PRIMITIVE() == $requestTargetKind) {
588
                    $odataModelInstance = $objectModelSerializer->writeTopLevelPrimitive(
589
                        $result,
590
                        $requestProperty
591
                    );
592
                } elseif (TargetKind::PRIMITIVE_VALUE() == $requestTargetKind) {
593
                    // Code path for primitive value (Since its primitive no need for
594
                    // object model serialization)
595
                    // Customers('ANU')/CompanyName/$value => string
596
                    // Employees(1)/Photo/$value => binary stream
597
                    // Customers/$count => string
598
                } else {
599
                    throw new InvalidOperationException('Unexpected resource target kind');
600
                }
601
            }
602
        }
603
604
        //Note: Response content type can be null for named stream
605
        if ($hasResponseBody && null !== $responseContentType) {
606
            if (TargetKind::MEDIA_RESOURCE() != $request->getTargetKind()
607
                && MimeTypes::MIME_APPLICATION_OCTETSTREAM != $responseContentType) {
608
                //append charset for everything except:
609
                //stream resources as they have their own content type
610
                //binary properties (they content type will be App Octet for those...is this a good way?
611
                //we could also decide based upon the projected property
612
613
                $responseContentType .= ';charset=utf-8';
614
            }
615
        }
616
617
        if ($hasResponseBody) {
618
            ResponseWriter::write($this, $request, $odataModelInstance, $responseContentType);
619
        }
620
    }
621
622
    /**
623
     * Gets the response format for the requested resource.
624
     *
625
     * @param RequestDescription $request      The request submitted by client and it's execution result
626
     * @param IUriProcessor      $uriProcessor The reference to the IUriProcessor
627
     *
628
     * @throws Common\HttpHeaderFailure
629
     * @throws InvalidOperationException
630
     * @throws ODataException            , HttpHeaderFailure
631
     * @throws ReflectionException
632
     * @throws Common\UrlFormatException
633
     * @return string|null               the response content-type, a null value means the requested resource
634
     *                                   is named stream and IDSSP2::getStreamContentType returned null
635
     */
636
    public function getResponseContentType(
637
        RequestDescription $request,
638
        IUriProcessor $uriProcessor
639
    ): ?string {
640
        $baseMimeTypes = [
641
            MimeTypes::MIME_APPLICATION_JSON,
642
            MimeTypes::MIME_APPLICATION_JSON_FULL_META,
643
            MimeTypes::MIME_APPLICATION_JSON_NO_META,
644
            MimeTypes::MIME_APPLICATION_JSON_MINIMAL_META,
645
            MimeTypes::MIME_APPLICATION_JSON_VERBOSE,];
646
647
        // The Accept request-header field specifies media types which are acceptable for the response
648
649
        $host              = $this->getHost();
650
        $requestAcceptText = $host->getRequestAccept();
651
        $requestVersion    = $request->getResponseVersion();
652
653
        //if the $format header is present it overrides the accepts header
654
        $format = $host->getQueryStringItem(ODataConstants::HTTPQUERY_STRING_FORMAT);
655
        if (null !== $format) {
656
            //There's a strange edge case..if application/json is supplied and it's V3
657
            if (MimeTypes::MIME_APPLICATION_JSON == $format && Version::v3() == $requestVersion) {
658
                //then it's actual minimalmetadata
659
                //TODO: should this be done with the header text too?
660
                $format = MimeTypes::MIME_APPLICATION_JSON_MINIMAL_META;
661
            }
662
663
            $requestAcceptText = ServiceHost::translateFormatToMime($requestVersion, $format);
664
        }
665
666
        //The response format can be dictated by the target resource kind. IE a $value will be different then expected
667
        //getTargetKind doesn't deal with link resources directly and this can change things
668
        $targetKind = $request->isLinkUri() ? TargetKind::LINK() : $request->getTargetKind();
669
670
        $availableMimeTypesByTarget = [
671
            TargetKind::METADATA()->getValue()          => [MimeTypes::MIME_APPLICATION_XML],
672
            TargetKind::SERVICE_DIRECTORY()->getValue() => array_merge([MimeTypes::MIME_APPLICATION_ATOMSERVICE], $baseMimeTypes),
673
            TargetKind::PRIMITIVE()->getValue()              => array_merge([MimeTypes::MIME_APPLICATION_XML, MimeTypes::MIME_TEXTXML,], $baseMimeTypes),
674
            TargetKind::COMPLEX_OBJECT()->getValue()              => array_merge([MimeTypes::MIME_APPLICATION_XML, MimeTypes::MIME_TEXTXML,], $baseMimeTypes),
675
            TargetKind::BAG()->getValue()              => array_merge([MimeTypes::MIME_APPLICATION_XML, MimeTypes::MIME_TEXTXML,], $baseMimeTypes),
676
            TargetKind::LINK()->getValue()              => array_merge([MimeTypes::MIME_APPLICATION_XML, MimeTypes::MIME_TEXTXML,], $baseMimeTypes),
677
            TargetKind::SINGLETON()->getValue()          => array_merge([MimeTypes::MIME_APPLICATION_ATOM], $baseMimeTypes),
678
            TargetKind::RESOURCE()->getValue()          => array_merge([MimeTypes::MIME_APPLICATION_ATOM], $baseMimeTypes),
679
        ];
680
681
        if($targetKind && array_key_exists($targetKind->getValue(),$availableMimeTypesByTarget)){
682
            return HttpProcessUtility::selectMimeType($requestAcceptText, $availableMimeTypesByTarget[$targetKind->getValue()]);
683
684
        }
685
        switch ($targetKind) {
686
            case TargetKind::PRIMITIVE_VALUE():
687
                $supportedResponseMimeTypes = [MimeTypes::MIME_TEXTPLAIN];
688
689
                if ('$count' != $request->getIdentifier()) {
690
                    $projectedProperty = $request->getProjectedProperty();
691
                    if (null === $projectedProperty) {
692
                        throw new InvalidOperationException('is_null($projectedProperty)');
693
                    }
694
                    $type = $projectedProperty->getInstanceType();
695
                    if (!$type instanceof IType) {
696
                        throw new InvalidOperationException('!$type instanceof IType');
697
                    }
698
                    if ($type instanceof Binary) {
699
                        $supportedResponseMimeTypes = [MimeTypes::MIME_APPLICATION_OCTETSTREAM];
700
                    }
701
                }
702
703
                return HttpProcessUtility::selectMimeType(
704
                    $requestAcceptText,
705
                    $supportedResponseMimeTypes
706
                );
707
708
709
            case TargetKind::MEDIA_RESOURCE():
710
                if (!$request->isNamedStream() && !$request->getTargetResourceType()->isMediaLinkEntry()) {
711
                    throw ODataException::createBadRequestError(
712
                        Messages::badRequestInvalidUriForMediaResource(
713
                            $host->getAbsoluteRequestUri()->getUrlAsString()
714
                        )
715
                    );
716
                }
717
718
                $uriProcessor->execute();
719
                $request->setExecuted();
720
                // DSSW::getStreamContentType can throw error in 2 cases
721
                // 1. If the required stream implementation not found
722
                // 2. If IDSSP::getStreamContentType returns NULL for MLE
723
                $responseContentType = $this->getStreamProviderWrapper()
724
                    ->getStreamContentType(
725
                        $request->getTargetResult(),
726
                        $request->getResourceStreamInfo()
727
                    );
728
729
                // Note StreamWrapper::getStreamContentType can return NULL if the requested named stream has not
730
                // yet been uploaded. But for an MLE if IDSSP::getStreamContentType returns NULL
731
                // then StreamWrapper will throw error
732
                if (null !== $responseContentType) {
0 ignored issues
show
introduced by
The condition null !== $responseContentType is always true.
Loading history...
733
                    $responseContentType = HttpProcessUtility::selectMimeType(
734
                        $requestAcceptText,
735
                        [$responseContentType]
736
                    );
737
                }
738
739
                return $responseContentType;
740
        }
741
742
        //If we got here, we just don't know what it is...
743
        throw new ODataException(Messages::unsupportedMediaType(), 415);
744
    }
745
746
    /**
747
     * Gets reference to wrapper class instance over IDSSP implementation.
748
     *
749
     * @return StreamProviderWrapper
750
     */
751
    public function getStreamProviderWrapper()
752
    {
753
        return $this->streamProvider;
754
    }
755
756
    /**
757
     * Get reference to object serialiser - bit wot turns PHP objects
758
     * into message traffic on wire.
759
     *
760
     * @return IObjectSerialiser
761
     */
762
    public function getObjectSerialiser(): IObjectSerialiser
763
    {
764
        assert(null != $this->objectSerialiser);
765
766
        return $this->objectSerialiser;
767
    }
768
769
    /**
770
     * For the given entry object compare its eTag (if it has eTag properties)
771
     * with current eTag request headers (if present).
772
     *
773
     * @param mixed        &$entryObject             entity resource for which etag
774
     *                                               needs to be checked
775
     * @param ResourceType &$resourceType            Resource type of the entry
776
     *                                               object
777
     * @param bool         &$needToSerializeResponse On return, this will contain
778
     *                                               True if response needs to be
779
     *                                               serialized, False otherwise
780
     *
781
     * @throws InvalidOperationException
782
     * @throws ReflectionException
783
     * @throws ODataException
784
     * @return string|null               The ETag for the entry object if it has eTag properties
785
     *                                   NULL otherwise
786
     */
787
    protected function compareETag(
788
        &$entryObject,
789
        ResourceType &$resourceType,
790
        &$needToSerializeResponse
791
    ): ?string {
792
        $needToSerializeResponse = true;
793
        $eTag                    = null;
794
        $ifMatch                 = $this->getHost()->getRequestIfMatch();
795
        $ifNoneMatch             = $this->getHost()->getRequestIfNoneMatch();
796
        if (null === $entryObject) {
797
            if (null !== $ifMatch) {
798
                throw ODataException::createPreConditionFailedError(
799
                    Messages::eTagNotAllowedForNonExistingResource()
800
                );
801
            }
802
803
            return null;
804
        }
805
806
        if ($this->getConfiguration()->getValidateETagHeader() && !$resourceType->hasETagProperties()) {
807
            if (null !== $ifMatch || null !== $ifNoneMatch) {
808
                // No eTag properties but request has eTag headers, bad request
809
                throw ODataException::createBadRequestError(
810
                    Messages::noETagPropertiesForType()
811
                );
812
            }
813
814
            // We need write the response but no eTag header
815
            return null;
816
        }
817
818
        if (!$this->getConfiguration()->getValidateETagHeader()) {
819
            // Configuration says do not validate ETag, so we will not write ETag header in the
820
            // response even though the requested resource support it
821
            return null;
822
        }
823
824
        if (null === $ifMatch && null === $ifNoneMatch) {
825
            // No request eTag header, we need to write the response
826
            // and eTag header
827
        } elseif (0 === strcmp(strval($ifMatch), '*')) {
828
            // If-Match:* => we need to write the response and eTag header
829
        } elseif (0 === strcmp(strval($ifNoneMatch), '*')) {
830
            // if-None-Match:* => Do not write the response (304 not modified),
831
            // but write eTag header
832
            $needToSerializeResponse = false;
833
        } else {
834
            $eTag = $this->getETagForEntry($entryObject, $resourceType);
835
            // Note: The following code for attaching the prefix W\"
836
            // and the suffix " can be done in getETagForEntry function
837
            // but that is causing an issue in Linux env where the
838
            // firefox browser is unable to parse the ETag in this case.
839
            // Need to follow up PHP core devs for this.
840
            $eTag = ODataConstants::HTTP_WEAK_ETAG_PREFIX . $eTag . '"';
841
            if (null !== $ifMatch) {
842
                if (0 != strcmp($eTag, $ifMatch)) {
843
                    // Requested If-Match value does not match with current
844
                    // eTag Value then pre-condition error
845
                    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
846
                    throw ODataException::createPreConditionFailedError(
847
                        Messages::eTagValueDoesNotMatch()
848
                    );
849
                }
850
            } elseif (0 === strcmp($eTag, $ifNoneMatch)) {
851
                //304 not modified, but in write eTag header
852
                $needToSerializeResponse = false;
853
            }
854
        }
855
856
        if (null === $eTag) {
857
            $eTag = $this->getETagForEntry($entryObject, $resourceType);
858
            // Note: The following code for attaching the prefix W\"
859
            // and the suffix " can be done in getETagForEntry function
860
            // but that is causing an issue in Linux env where the
861
            // firefox browser is unable to parse the ETag in this case.
862
            // Need to follow up PHP core devs for this.
863
            $eTag = ODataConstants::HTTP_WEAK_ETAG_PREFIX . $eTag . '"';
864
        }
865
866
        return $eTag;
867
    }
868
869
    /**
870
     * Returns the etag for the given resource.
871
     * Note: This function will not add W\" prefix and " suffix, that is caller's
872
     * responsibility.
873
     *
874
     * @param mixed        &$entryObject  Resource for which etag value needs to
875
     *                                    be returned
876
     * @param ResourceType &$resourceType Resource type of the $entryObject
877
     *
878
     * @throws InvalidOperationException
879
     * @throws ReflectionException
880
     * @throws ODataException
881
     * @return string|null               ETag value for the given resource (with values encoded
882
     *                                   for use in a URI) there are etag properties, NULL if
883
     *                                   there is no etag property
884
     */
885
    protected function getETagForEntry(&$entryObject, ResourceType &$resourceType): ?string
886
    {
887
        $eTag  = null;
888
        $comma = null;
889
        foreach ($resourceType->getETagProperties() as $eTagProperty) {
890
            $type = $eTagProperty->getInstanceType();
891
            if (!$type instanceof IType) {
892
                throw new InvalidOperationException('!$type instanceof IType');
893
            }
894
895
            $value    = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $value is dead and can be removed.
Loading history...
896
            $property = $eTagProperty->getName();
897
            try {
898
                //TODO #88...also this seems like dupe work
899
                $value = ReflectionHandler::getProperty($entryObject, $property);
900
            } catch (ReflectionException $reflectionException) {
901
                throw ODataException::createInternalServerError(
902
                    Messages::failedToAccessProperty($property, $resourceType->getName())
903
                );
904
            }
905
906
            $eTagBase = $eTag . $comma;
907
            $eTag     = $eTagBase . ((null == $value) ? 'null' : $type->convertToOData($value));
908
909
            $comma = ',';
910
        }
911
912
        if (null !== $eTag) {
913
            // If eTag is made up of datetime or string properties then the above
914
            // IType::convertToOData will perform utf8 and url encode. But we don't
915
            // want this for eTag value.
916
            $eTag = urldecode(utf8_decode($eTag));
917
918
            return rtrim($eTag, ',');
919
        }
920
        return null;
921
    }
922
923
    /**
924
     * @return IStreamProvider2
925
     */
926
    abstract public function getStreamProviderX();
927
}
928