Completed
Push — master ( be72f0...b6ccc1 )
by Alex
17s queued 14s
created

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