Passed
Pull Request — master (#244)
by Alex
03:59
created

BaseService::getHost()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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