Passed
Pull Request — master (#206)
by Alex
05:49 queued 10s
created

IronicSerialiser::writePrimitiveProperties()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 19
rs 9.7998
cc 4
nc 4
nop 2
1
<?php
2
3
namespace AlgoWeb\PODataLaravel\Serialisers;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Facades\App;
9
use POData\Common\InvalidOperationException;
10
use POData\Common\Messages;
11
use POData\Common\ODataConstants;
12
use POData\Common\ODataException;
13
use POData\IService;
14
use POData\ObjectModel\IObjectSerialiser;
15
use POData\ObjectModel\ODataBagContent;
16
use POData\ObjectModel\ODataCategory;
17
use POData\ObjectModel\ODataEntry;
18
use POData\ObjectModel\ODataFeed;
19
use POData\ObjectModel\ODataLink;
20
use POData\ObjectModel\ODataMediaLink;
21
use POData\ObjectModel\ODataNavigationPropertyInfo;
22
use POData\ObjectModel\ODataProperty;
23
use POData\ObjectModel\ODataPropertyContent;
24
use POData\ObjectModel\ODataTitle;
25
use POData\ObjectModel\ODataURL;
26
use POData\ObjectModel\ODataURLCollection;
27
use POData\Providers\Metadata\IMetadataProvider;
28
use POData\Providers\Metadata\ResourceEntityType;
29
use POData\Providers\Metadata\ResourceProperty;
30
use POData\Providers\Metadata\ResourcePropertyKind;
31
use POData\Providers\Metadata\ResourceSet;
32
use POData\Providers\Metadata\ResourceSetWrapper;
33
use POData\Providers\Metadata\ResourceType;
34
use POData\Providers\Metadata\ResourceTypeKind;
35
use POData\Providers\Metadata\Type\Binary;
36
use POData\Providers\Metadata\Type\Boolean;
37
use POData\Providers\Metadata\Type\DateTime;
38
use POData\Providers\Metadata\Type\IType;
39
use POData\Providers\Metadata\Type\StringType;
40
use POData\Providers\Query\QueryResult;
41
use POData\Providers\Query\QueryType;
42
use POData\UriProcessor\QueryProcessor\ExpandProjectionParser\ExpandedProjectionNode;
43
use POData\UriProcessor\QueryProcessor\ExpandProjectionParser\ProjectionNode;
44
use POData\UriProcessor\QueryProcessor\ExpandProjectionParser\RootProjectionNode;
45
use POData\UriProcessor\QueryProcessor\OrderByParser\InternalOrderByInfo;
46
use POData\UriProcessor\RequestDescription;
47
use POData\UriProcessor\SegmentStack;
48
49
class IronicSerialiser implements IObjectSerialiser
50
{
51
    use SerialiseDepWrapperTrait;
52
    use SerialisePropertyCacheTrait;
53
    use SerialiseNavigationTrait;
54
    use SerialiseLowLevelWritersTrait;
55
56
    /**
57
     * Update time to insert into ODataEntry/ODataFeed fields
58
     * @var Carbon
59
     */
60
    private $updated;
61
62
    /**
63
     * Has base URI already been written out during serialisation?
64
     * @var bool
65
     */
66
    private $isBaseWritten = false;
67
68
    /**
69
     * @param IService                $service Reference to the data service instance
70
     * @param RequestDescription|null $request Type instance describing the client submitted request
71
     * @throws \Exception
72
     */
73
    public function __construct(IService $service, RequestDescription $request = null)
74
    {
75
        $this->service = $service;
76
        $this->request = $request;
77
        $this->absoluteServiceUri = $service->getHost()->getAbsoluteServiceUri()->getUrlAsString();
78
        $this->absoluteServiceUriWithSlash = rtrim($this->absoluteServiceUri, '/') . '/';
79
        $this->stack = new SegmentStack($request);
80
        $this->complexTypeInstanceCollection = [];
81
        $this->modelSerialiser = new ModelSerialiser();
82
        $this->updated = Carbon::now();
83
    }
84
85
    /**
86
     * Write a top level entry resource.
87
     *
88
     * @param QueryResult $entryObject Reference to the entry object to be written
89
     *
90
     * @return ODataEntry|null
91
     * @throws InvalidOperationException
92
     * @throws \ReflectionException
93
     * @throws ODataException
94
     */
95
    public function writeTopLevelElement(QueryResult $entryObject)
96
    {
97
        if (!isset($entryObject->results)) {
98
            array_pop($this->lightStack);
99
            return null;
100
        }
101
        if (!$entryObject->results instanceof Model) {
102
            $res = $entryObject->results;
103
            $msg = is_array($res) ? 'Entry object must be single Model' : get_class($res);
104
            throw new InvalidOperationException($msg);
105
        }
106
107
        $this->loadStackIfEmpty();
108
        $baseURI = $this->isBaseWritten ? null : $this->absoluteServiceUriWithSlash;
109
        $this->isBaseWritten = true;
110
111
        $stackCount = count($this->lightStack);
112
        $topOfStack = $this->lightStack[$stackCount-1];
113
        $payloadClass = get_class($entryObject->results);
114
        /** @var ResourceEntityType $resourceType */
115
        $resourceType = $this->getService()->getProvidersWrapper()->resolveResourceType($topOfStack['type']);
116
117
        // need gubbinz to unpack an abstract resource type
118
        $resourceType = $this->getConcreteTypeFromAbstractType($resourceType, $payloadClass);
119
120
        // make sure we're barking up right tree
121
        if (!$resourceType instanceof ResourceEntityType) {
122
            throw new InvalidOperationException(get_class($resourceType));
123
        }
124
125
        /** @var Model $res */
126
        $res = $entryObject->results;
127
        $targClass = $resourceType->getInstanceType()->getName();
128
        if (!($res instanceof $targClass)) {
129
            $msg = 'Object being serialised not instance of expected class, '
130
                   . $targClass . ', is actually ' . $payloadClass;
131
            throw new InvalidOperationException($msg);
132
        }
133
134
        $this->checkRelationPropertiesCached($targClass, $resourceType);
135
        /** @var ResourceProperty[] $relProp */
136
        $relProp = $this->propertiesCache[$targClass]['rel'];
137
        /** @var ResourceProperty[] $nonRelProp */
138
        $nonRelProp = $this->propertiesCache[$targClass]['nonRel'];
139
140
        $resourceSet = $resourceType->getCustomState();
141
        if (!$resourceSet instanceof ResourceSet) {
142
            throw new InvalidOperationException('');
143
        }
144
        $title = $resourceType->getName();
145
        $type = $resourceType->getFullName();
146
147
        $relativeUri = $this->getEntryInstanceKey(
148
            $res,
149
            $resourceType,
150
            $resourceSet->getName()
151
        );
152
        $absoluteUri = rtrim($this->absoluteServiceUri, '/') . '/' . $relativeUri;
153
154
        /** var $mediaLink ODataMediaLink|null */
155
        $mediaLink = null;
156
        /** var $mediaLinks ODataMediaLink[] */
157
        $mediaLinks = [];
158
        $this->writeMediaData(
159
            $res,
160
            $type,
161
            $relativeUri,
162
            $resourceType,
163
            $mediaLink,
164
            $mediaLinks
165
        );
166
167
        $propertyContent = $this->writePrimitiveProperties($res, $nonRelProp);
168
169
        $links = $this->buildLinksFromRels($entryObject, $relProp, $relativeUri);
170
171
        $odata = new ODataEntry();
172
        $odata->resourceSetName = $resourceSet->getName();
173
        $odata->id = $absoluteUri;
174
        $odata->title = new ODataTitle($title);
175
        $odata->type = new ODataCategory($type);
176
        $odata->propertyContent = $propertyContent;
177
        $odata->isMediaLinkEntry = $resourceType->isMediaLinkEntry();
178
        $odata->editLink = new ODataLink();
179
        $odata->editLink->url = $relativeUri;
180
        $odata->editLink->name = 'edit';
181
        $odata->editLink->title = $title;
182
        $odata->mediaLink = $mediaLink;
183
        $odata->mediaLinks = $mediaLinks;
184
        $odata->links = $links;
185
        $odata->updated = $this->getUpdated()->format(DATE_ATOM);
186
        $odata->baseURI = $baseURI;
187
188
        $newCount = count($this->lightStack);
189
        if ($newCount != $stackCount) {
190
            $msg = 'Should have ' . $stackCount . ' elements in stack, have ' . $newCount . ' elements';
191
            throw new InvalidOperationException($msg);
192
        }
193
        $this->lightStack[$newCount-1]['count']--;
194
        if (0 == $this->lightStack[$newCount-1]['count']) {
195
            array_pop($this->lightStack);
196
        }
197
        return $odata;
198
    }
199
200
    /**
201
     * Write top level feed element.
202
     *
203
     * @param QueryResult &$entryObjects Array of entry resources to be written
204
     *
205
     * @return ODataFeed
206
     * @throws InvalidOperationException
207
     * @throws ODataException
208
     * @throws \ReflectionException
209
     */
210
    public function writeTopLevelElements(QueryResult &$entryObjects)
211
    {
212
        $res = $entryObjects->results;
213
        if (!(is_array($res) || $res instanceof Collection)) {
214
            throw new InvalidOperationException('!is_array($entryObjects->results)');
215
        }
216
        if (is_array($res) && 0 == count($res)) {
217
            $entryObjects->hasMore = false;
218
        }
219
        if ($res instanceof Collection && 0 == $res->count()) {
220
            $entryObjects->hasMore = false;
221
        }
222
223
        $this->loadStackIfEmpty();
224
        $setName = $this->getRequest()->getTargetResourceSetWrapper()->getName();
225
226
        $title = $this->getRequest()->getContainerName();
227
        $relativeUri = $this->getRequest()->getIdentifier();
228
        $absoluteUri = $this->getRequest()->getRequestUrl()->getUrlAsString();
229
230
        $selfLink = new ODataLink();
231
        $selfLink->name = 'self';
232
        $selfLink->title = $relativeUri;
233
        $selfLink->url = $relativeUri;
234
235
        $odata = new ODataFeed();
236
        $odata->title = new ODataTitle($title);
237
        $odata->id = $absoluteUri;
238
        $odata->selfLink = $selfLink;
239
        $odata->updated = $this->getUpdated()->format(DATE_ATOM);
240
        $odata->baseURI = $this->isBaseWritten ? null : $this->absoluteServiceUriWithSlash;
241
        $this->isBaseWritten = true;
242
243
        if ($this->getRequest()->queryType == QueryType::ENTITIES_WITH_COUNT()) {
244
            $odata->rowCount = $this->getRequest()->getCountValue();
245
        }
246
        foreach ($res as $entry) {
247
            if (!$entry instanceof QueryResult) {
248
                $query = new QueryResult();
249
                $query->results = $entry;
250
            } else {
251
                $query = $entry;
252
            }
253
            if (!$query instanceof QueryResult) {
254
                throw new InvalidOperationException(get_class($query));
255
            }
256
            $odata->entries[] = $this->writeTopLevelElement($query);
257
        }
258
259
        $resourceSet = $this->getRequest()->getTargetResourceSetWrapper()->getResourceSet();
260
        $requestTop = $this->getRequest()->getTopOptionCount();
261
        $pageSize = $this->getService()->getConfiguration()->getEntitySetPageSize($resourceSet);
262
        $requestTop = (null === $requestTop) ? $pageSize+1 : $requestTop;
263
264
        if (true === $entryObjects->hasMore && $requestTop > $pageSize) {
265
            $stackSegment = $setName;
266
            $lastObject = end($entryObjects->results);
267
            $segment = $this->getNextLinkUri($lastObject);
268
            $nextLink = new ODataLink();
269
            $nextLink->name = ODataConstants::ATOM_LINK_NEXT_ATTRIBUTE_STRING;
270
            $nextLink->url = rtrim($this->absoluteServiceUri, '/') . '/' . $stackSegment . $segment;
271
            $odata->nextPageLink = $nextLink;
272
        }
273
274
        return $odata;
275
    }
276
277
    /**
278
     * Write top level url element.
279
     *
280
     * @param QueryResult $entryObject The entry resource whose url to be written
281
     *
282
     * @return ODataURL
283
     * @throws InvalidOperationException
284
     * @throws ODataException
285
     * @throws \ReflectionException
286
     */
287
    public function writeUrlElement(QueryResult $entryObject)
288
    {
289
        $url = new ODataURL();
290
        /** @var Model|null $res */
291
        $res = $entryObject->results;
292
        if (null !== $res) {
293
            $currentResourceType = $this->getCurrentResourceSetWrapper()->getResourceType();
294
            $relativeUri = $this->getEntryInstanceKey(
295
                $res,
296
                $currentResourceType,
297
                $this->getCurrentResourceSetWrapper()->getName()
298
            );
299
300
            $url->url = rtrim($this->absoluteServiceUri, '/') . '/' . $relativeUri;
301
        }
302
303
        return $url;
304
    }
305
306
    /**
307
     * Write top level url collection.
308
     *
309
     * @param QueryResult $entryObjects Array of entry resources whose url to be written
310
     *
311
     * @return ODataURLCollection
312
     * @throws InvalidOperationException
313
     * @throws ODataException
314
     * @throws \ReflectionException
315
     */
316
    public function writeUrlElements(QueryResult $entryObjects)
317
    {
318
        $urls = new ODataURLCollection();
319
        if (!empty($entryObjects->results)) {
320
            $i = 0;
321
            foreach ($entryObjects->results as $entryObject) {
322
                if (!$entryObject instanceof QueryResult) {
323
                    $query = new QueryResult();
324
                    $query->results = $entryObject;
325
                } else {
326
                    $query = $entryObject;
327
                }
328
                $urls->urls[$i] = $this->writeUrlElement($query);
329
                ++$i;
330
            }
331
332
            if ($i > 0 && true === $entryObjects->hasMore) {
333
                $stackSegment = $this->getRequest()->getTargetResourceSetWrapper()->getName();
334
                $lastObject = end($entryObjects->results);
0 ignored issues
show
Bug introduced by
It seems like $entryObjects->results can also be of type object; however, parameter $array of end() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

334
                $lastObject = end(/** @scrutinizer ignore-type */ $entryObjects->results);
Loading history...
335
                $segment = $this->getNextLinkUri($lastObject);
336
                $nextLink = new ODataLink();
337
                $nextLink->name = ODataConstants::ATOM_LINK_NEXT_ATTRIBUTE_STRING;
338
                $nextLink->url = rtrim($this->absoluteServiceUri, '/') . '/' . $stackSegment . $segment;
339
                $urls->nextPageLink = $nextLink;
340
            }
341
        }
342
343
        if ($this->getRequest()->queryType == QueryType::ENTITIES_WITH_COUNT()) {
344
            $urls->count = $this->getRequest()->getCountValue();
345
        }
346
347
        return $urls;
348
    }
349
350
    /**
351
     * Write top level complex resource.
352
     *
353
     * @param QueryResult  &$complexValue The complex object to be written
354
     * @param string       $propertyName  The name of the complex property
355
     * @param ResourceType &$resourceType Describes the type of complex object
356
     *
357
     * @return ODataPropertyContent
358
     * @throws InvalidOperationException
359
     * @throws \ReflectionException
360
     */
361
    public function writeTopLevelComplexObject(QueryResult &$complexValue, $propertyName, ResourceType &$resourceType)
362
    {
363
        $result = $complexValue->results;
364
365
        $propertyContent = new ODataPropertyContent();
366
        $odataProperty = new ODataProperty();
367
        $odataProperty->name = $propertyName;
368
        $odataProperty->typeName = $resourceType->getFullName();
369
        if (null != $result) {
370
            $internalContent = $this->writeComplexValue($resourceType, $result);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type array<mixed,object>; however, parameter $result of AlgoWeb\PODataLaravel\Se...er::writeComplexValue() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

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

370
            $internalContent = $this->writeComplexValue($resourceType, /** @scrutinizer ignore-type */ $result);
Loading history...
371
            $odataProperty->value = $internalContent;
372
        }
373
374
        $propertyContent->properties[$propertyName] = $odataProperty;
375
376
        return $propertyContent;
377
    }
378
379
    /**
380
     * Write top level bag resource.
381
     *
382
     * @param QueryResult  &$BagValue     The bag object to be
383
     *                                    written
384
     * @param string       $propertyName  The name of the
385
     *                                    bag property
386
     * @param ResourceType &$resourceType Describes the type of
387
     *                                    bag object
388
     *
389
     * @return ODataPropertyContent
390
     * @throws InvalidOperationException
391
     * @throws \ReflectionException
392
     */
393
    public function writeTopLevelBagObject(QueryResult &$BagValue, $propertyName, ResourceType &$resourceType)
394
    {
395
        $result = $BagValue->results;
396
397
        $propertyContent = new ODataPropertyContent();
398
        $odataProperty = new ODataProperty();
399
        $odataProperty->name = $propertyName;
400
        $odataProperty->typeName = 'Collection(' . $resourceType->getFullName() . ')';
401
        $odataProperty->value = $this->writeBagValue($resourceType, $result);
402
403
        $propertyContent->properties[$propertyName] = $odataProperty;
404
        return $propertyContent;
405
    }
406
407
    /**
408
     * Write top level primitive value.
409
     *
410
     * @param  QueryResult          &$primitiveValue   The primitive value to be
411
     *                                                 written
412
     * @param  ResourceProperty     &$resourceProperty Resource property describing the
413
     *                                                 primitive property to be written
414
     * @return ODataPropertyContent
415
     * @throws InvalidOperationException
416
     * @throws \ReflectionException
417
     */
418
    public function writeTopLevelPrimitive(QueryResult &$primitiveValue, ResourceProperty &$resourceProperty = null)
419
    {
420
        if (null === $resourceProperty) {
421
            throw new InvalidOperationException('Resource property must not be null');
422
        }
423
        $propertyContent = new ODataPropertyContent();
424
425
        $odataProperty = new ODataProperty();
426
        $odataProperty->name = $resourceProperty->getName();
427
        $iType = $resourceProperty->getInstanceType();
428
        if (!$iType instanceof IType) {
429
            throw new InvalidOperationException(get_class($iType));
430
        }
431
        $odataProperty->typeName = $iType->getFullTypeName();
432
        if (null == $primitiveValue->results) {
433
            $odataProperty->value = null;
434
        } else {
435
            $rType = $resourceProperty->getResourceType()->getInstanceType();
436
            if (!$rType instanceof IType) {
437
                throw new InvalidOperationException(get_class($rType));
438
            }
439
            $odataProperty->value = $this->primitiveToString($rType, $primitiveValue->results);
440
        }
441
442
        $propertyContent->properties[$odataProperty->name] = $odataProperty;
443
444
        return $propertyContent;
445
    }
446
447
    /**
448
     * Get update timestamp.
449
     *
450
     * @return Carbon
451
     */
452
    public function getUpdated()
453
    {
454
        return $this->updated;
455
    }
456
457
    /**
458
     * @param Model $entityInstance
459
     * @param ResourceType $resourceType
460
     * @param string $containerName
461
     * @return string
462
     * @throws InvalidOperationException
463
     * @throws ODataException
464
     * @throws \ReflectionException
465
     */
466
    protected function getEntryInstanceKey($entityInstance, ResourceType $resourceType, $containerName)
467
    {
468
        $typeName = $resourceType->getName();
469
        $keyProperties = $resourceType->getKeyProperties();
470
        if (0 == count($keyProperties)) {
471
            throw new InvalidOperationException('count($keyProperties) == 0');
472
        }
473
        $keyString = $containerName . '(';
474
        $comma = null;
475
        foreach ($keyProperties as $keyName => $resourceProperty) {
476
            $keyType = $resourceProperty->getInstanceType();
477
            if (!$keyType instanceof IType) {
478
                throw new InvalidOperationException('$keyType not instanceof IType');
479
            }
480
            $keyName = $resourceProperty->getName();
481
            $keyValue = $entityInstance->$keyName;
482
            if (!isset($keyValue)) {
483
                throw ODataException::createInternalServerError(
484
                    Messages::badQueryNullKeysAreNotSupported($typeName, $keyName)
485
                );
486
            }
487
488
            $keyValue = $keyType->convertToOData($keyValue);
489
            $keyString .= $comma . $keyName . '=' . $keyValue;
490
            $comma = ',';
491
        }
492
493
        $keyString .= ')';
494
495
        return $keyString;
496
    }
497
498
    /**
499
     * @param $entryObject
500
     * @param $type
501
     * @param $relativeUri
502
     * @param ResourceType $resourceType
503
     * @param ODataMediaLink|null $mediaLink
504
     * @param ODataMediaLink[] $mediaLinks
505
     * @return void
506
     * @throws InvalidOperationException
507
     */
508
    protected function writeMediaData(
509
        $entryObject,
510
        $type,
511
        $relativeUri,
512
        ResourceType $resourceType,
513
        ODataMediaLink &$mediaLink = null,
514
        array &$mediaLinks = []
515
    ) {
516
        $context = $this->getService()->getOperationContext();
517
        $streamProviderWrapper = $this->getService()->getStreamProviderWrapper();
518
        if (null == $streamProviderWrapper) {
519
            throw new InvalidOperationException('Retrieved stream provider must not be null');
520
        }
521
522
        /** @var ODataMediaLink|null $mediaLink */
523
        $mediaLink = null;
524
        if ($resourceType->isMediaLinkEntry()) {
525
            $eTag = $streamProviderWrapper->getStreamETag2($entryObject, null, $context);
0 ignored issues
show
Bug introduced by
The method getStreamETag2() does not exist on POData\Providers\Stream\StreamProviderWrapper. Did you maybe mean getStreamETag()? ( Ignorable by Annotation )

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

525
            /** @scrutinizer ignore-call */ 
526
            $eTag = $streamProviderWrapper->getStreamETag2($entryObject, null, $context);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
526
            $mediaLink = new ODataMediaLink($type, '/$value', $relativeUri . '/$value', '*/*', $eTag, 'edit-media');
527
        }
528
        /** @var ODataMediaLink[] $mediaLinks */
529
        $mediaLinks = [];
530
        if ($resourceType->hasNamedStream()) {
531
            $namedStreams = $resourceType->getAllNamedStreams();
532
            foreach ($namedStreams as $streamTitle => $resourceStreamInfo) {
533
                $readUri = $streamProviderWrapper->getReadStreamUri2(
0 ignored issues
show
Bug introduced by
The method getReadStreamUri2() does not exist on POData\Providers\Stream\StreamProviderWrapper. Did you maybe mean getReadStreamUri()? ( Ignorable by Annotation )

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

533
                /** @scrutinizer ignore-call */ 
534
                $readUri = $streamProviderWrapper->getReadStreamUri2(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
534
                    $entryObject,
535
                    $resourceStreamInfo,
536
                    $context,
537
                    $relativeUri
538
                );
539
                $mediaContentType = $streamProviderWrapper->getStreamContentType2(
0 ignored issues
show
Bug introduced by
The method getStreamContentType2() does not exist on POData\Providers\Stream\StreamProviderWrapper. Did you maybe mean getStreamContentType()? ( Ignorable by Annotation )

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

539
                /** @scrutinizer ignore-call */ 
540
                $mediaContentType = $streamProviderWrapper->getStreamContentType2(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
540
                    $entryObject,
541
                    $resourceStreamInfo,
542
                    $context
543
                );
544
                $eTag = $streamProviderWrapper->getStreamETag2(
545
                    $entryObject,
546
                    $resourceStreamInfo,
547
                    $context
548
                );
549
550
                $nuLink = new ODataMediaLink($streamTitle, $readUri, $readUri, $mediaContentType, $eTag);
551
                $mediaLinks[] = $nuLink;
552
            }
553
        }
554
    }
555
556
    /**
557
     * Wheter next link is needed for the current resource set (feed)
558
     * being serialized.
559
     *
560
     * @param int $resultSetCount Number of entries in the current
561
     *                            resource set
562
     *
563
     * @return bool true if the feed must have a next page link
564
     * @throws InvalidOperationException
565
     */
566
    protected function needNextPageLink($resultSetCount)
567
    {
568
        $currentResourceSet = $this->getCurrentResourceSetWrapper();
569
        $recursionLevel = count($this->getStack()->getSegmentNames());
570
        $pageSize = $currentResourceSet->getResourceSetPageSize();
571
572
        if (1 == $recursionLevel) {
573
            //presence of $top option affect next link for root container
574
            $topValueCount = $this->getRequest()->getTopOptionCount();
575
            if (null !== $topValueCount && ($topValueCount <= $pageSize)) {
576
                return false;
577
            }
578
        }
579
        return $resultSetCount == $pageSize;
580
    }
581
582
    /**
583
     * Get next page link from the given entity instance.
584
     *
585
     * @param  mixed          &$lastObject Last object serialized to be
586
     *                                     used for generating
587
     *                                     $skiptoken
588
     * @throws ODataException
589
     * @return string         for the link for next page
590
     * @throws InvalidOperationException
591
     */
592
    protected function getNextLinkUri(&$lastObject)
593
    {
594
        $currentExpandedProjectionNode = $this->getCurrentExpandedProjectionNode();
595
        $internalOrderByInfo = $currentExpandedProjectionNode->getInternalOrderByInfo();
596
        if (null === $internalOrderByInfo) {
597
            throw new InvalidOperationException('Null');
598
        }
599
        if (!$internalOrderByInfo instanceof InternalOrderByInfo) {
0 ignored issues
show
introduced by
$internalOrderByInfo is always a sub-type of POData\UriProcessor\Quer...ser\InternalOrderByInfo.
Loading history...
600
            throw new InvalidOperationException(get_class($internalOrderByInfo));
601
        }
602
        $numSegments = count($internalOrderByInfo->getOrderByPathSegments());
603
        $queryParameterString = $this->getNextPageLinkQueryParametersForRootResourceSet();
604
605
        $skipToken = $internalOrderByInfo->buildSkipTokenValue($lastObject);
606
        if (empty($skipToken)) {
607
            throw new InvalidOperationException('!is_null($skipToken)');
608
        }
609
        $token = (1 < $numSegments) ? '$skiptoken=' : '$skip=';
610
        $skipToken = (1 < $numSegments) ? $skipToken : intval(trim($skipToken, '\''));
611
        $skipToken = '?' . $queryParameterString . $token . $skipToken;
612
613
        return $skipToken;
614
    }
615
616
    /**
617
     * Builds the string corresponding to query parameters for top level results
618
     * (result set identified by the resource path) to be put in next page link.
619
     *
620
     * @return string|null string representing the query parameters in the URI
621
     *                     query parameter format, NULL if there
622
     *                     is no query parameters
623
     *                     required for the next link of top level result set
624
     * @throws InvalidOperationException
625
     */
626
    protected function getNextPageLinkQueryParametersForRootResourceSet()
627
    {
628
        /** @var string|null $queryParameterString */
629
        $queryParameterString = null;
630
        foreach ([ODataConstants::HTTPQUERY_STRING_FILTER,
631
                     ODataConstants::HTTPQUERY_STRING_EXPAND,
632
                     ODataConstants::HTTPQUERY_STRING_ORDERBY,
633
                     ODataConstants::HTTPQUERY_STRING_INLINECOUNT,
634
                     ODataConstants::HTTPQUERY_STRING_SELECT, ] as $queryOption) {
635
            /** @var string|null $value */
636
            $value = $this->getService()->getHost()->getQueryStringItem($queryOption);
637
            if (null !== $value) {
638
                if (null !== $queryParameterString) {
639
                    $queryParameterString = /** @scrutinizer ignore-type */$queryParameterString . '&';
640
                }
641
642
                $queryParameterString .= $queryOption . '=' . $value;
643
            }
644
        }
645
646
        $topCountValue = $this->getRequest()->getTopOptionCount();
647
        if (null !== $topCountValue) {
648
            $remainingCount = $topCountValue-$this->getRequest()->getTopCount();
649
            if (0 < $remainingCount) {
650
                if (null !== $queryParameterString) {
651
                    $queryParameterString .= '&';
652
                }
653
654
                $queryParameterString .= ODataConstants::HTTPQUERY_STRING_TOP . '=' . $remainingCount;
655
            }
656
        }
657
658
        if (null !== $queryParameterString) {
659
            $queryParameterString .= '&';
660
        }
661
662
        return $queryParameterString;
663
    }
664
665
    /**
666
     * @param QueryResult $entryObject
667
     * @param ResourceProperty $prop
668
     * @param $nuLink
669
     * @param $propKind
670
     * @param $propName
671
     * @throws InvalidOperationException
672
     * @throws ODataException
673
     * @throws \ReflectionException
674
     */
675
    private function expandNavigationProperty(
676
        QueryResult $entryObject,
677
        ResourceProperty $prop,
678
        $nuLink,
679
        $propKind,
680
        $propName
681
    ) {
682
        $nextName = $prop->getResourceType()->getName();
683
        $nuLink->isExpanded = true;
684
        $value = $entryObject->results->$propName;
685
        $isCollection = ResourcePropertyKind::RESOURCESET_REFERENCE == $propKind;
686
        $nuLink->isCollection = $isCollection;
687
688
        if (is_array($value)) {
689
            if (1 == count($value) && !$isCollection) {
690
                $value = $value[0];
691
            } else {
692
                $value = collect($value);
693
            }
694
        }
695
696
        $result = new QueryResult();
697
        $result->results = $value;
698
        $nullResult = null === $value;
699
        $isSingleton = $value instanceof Model;
700
        $resultCount = $nullResult ? 0 : ($isSingleton ? 1 : $value->count());
701
702
        if (0 < $resultCount) {
703
            $newStackLine = ['type' => $nextName, 'prop' => $propName, 'count' => $resultCount];
704
            array_push($this->lightStack, $newStackLine);
705
            if (!$isCollection) {
706
                $nuLink->type = 'application/atom+xml;type=entry';
707
                $expandedResult = $this->writeTopLevelElement($result);
708
            } else {
709
                $nuLink->type = 'application/atom+xml;type=feed';
710
                $expandedResult = $this->writeTopLevelElements($result);
711
            }
712
            $nuLink->expandedResult = $expandedResult;
713
        } else {
714
            $type = $this->getService()->getProvidersWrapper()->resolveResourceType($nextName);
715
            if (!$isCollection) {
716
                $result = new ODataEntry();
717
                $result->resourceSetName = $type->getName();
718
            } else {
719
                $result = new ODataFeed();
720
                $result->selfLink = new ODataLink();
721
                $result->selfLink->name = ODataConstants::ATOM_SELF_RELATION_ATTRIBUTE_VALUE;
722
            }
723
            $nuLink->expandedResult = $result;
724
        }
725
        if (isset($nuLink->expandedResult->selfLink)) {
726
            $nuLink->expandedResult->selfLink->title = $propName;
727
            $nuLink->expandedResult->selfLink->url = $nuLink->url;
728
            $nuLink->expandedResult->title = new ODataTitle($propName);
729
            $nuLink->expandedResult->id = rtrim($this->absoluteServiceUri, '/') . '/' . $nuLink->url;
730
        }
731
        if (!isset($nuLink->expandedResult)) {
732
            throw new InvalidOperationException('');
733
        }
734
    }
735
736
    public static function isMatchPrimitive($resourceKind)
737
    {
738
        if (16 > $resourceKind) {
739
            return false;
740
        }
741
        if (28 < $resourceKind) {
742
            return false;
743
        }
744
        return 0 == ($resourceKind % 4);
745
    }
746
747
    /**
748
     * @param ResourceEntityType $resourceType
749
     * @param $payloadClass
750
     * @return ResourceEntityType|ResourceType
751
     * @throws InvalidOperationException
752
     * @throws \ReflectionException
753
     */
754
    protected function getConcreteTypeFromAbstractType(ResourceEntityType $resourceType, $payloadClass)
755
    {
756
        if ($resourceType->isAbstract()) {
757
            $derived = $this->getMetadata()->getDerivedTypes($resourceType);
758
            if (0 == count($derived)) {
759
                throw new InvalidOperationException('Supplied abstract type must have at least one derived type');
760
            }
761
            foreach ($derived as $rawType) {
762
                if (!$rawType->isAbstract()) {
763
                    $name = $rawType->getInstanceType()->getName();
764
                    if ($payloadClass == $name) {
765
                        $resourceType = $rawType;
766
                        break;
767
                    }
768
                }
769
            }
770
        }
771
        // despite all set up, checking, etc, if we haven't picked a concrete resource type,
772
        // wheels have fallen off, so blow up
773
        if ($resourceType->isAbstract()) {
774
            throw new InvalidOperationException('Concrete resource type not selected for payload ' . $payloadClass);
775
        }
776
        return $resourceType;
777
    }
778
779
    /**
780
     * @param QueryResult $entryObject
781
     * @param array $relProp
782
     * @param $relativeUri
783
     * @return array
784
     * @throws InvalidOperationException
785
     * @throws ODataException
786
     * @throws \ReflectionException
787
     */
788
    protected function buildLinksFromRels(QueryResult $entryObject, array $relProp, $relativeUri)
789
    {
790
        $links = [];
791
        foreach ($relProp as $prop) {
792
            $nuLink = new ODataLink();
793
            $propKind = $prop->getKind();
794
795
            if (!(ResourcePropertyKind::RESOURCESET_REFERENCE == $propKind
796
                  || ResourcePropertyKind::RESOURCE_REFERENCE == $propKind)) {
797
                $msg = '$propKind != ResourcePropertyKind::RESOURCESET_REFERENCE &&'
798
                       . ' $propKind != ResourcePropertyKind::RESOURCE_REFERENCE';
799
                throw new InvalidOperationException($msg);
800
            }
801
            $propTail = ResourcePropertyKind::RESOURCE_REFERENCE == $propKind ? 'entry' : 'feed';
802
            $propType = 'application/atom+xml;type=' . $propTail;
803
            $propName = $prop->getName();
804
            $nuLink->title = $propName;
805
            $nuLink->name = ODataConstants::ODATA_RELATED_NAMESPACE . $propName;
806
            $nuLink->url = $relativeUri . '/' . $propName;
807
            $nuLink->type = $propType;
808
            $nuLink->isExpanded = false;
809
            $nuLink->isCollection = 'feed' === $propTail;
810
811
            $shouldExpand = $this->shouldExpandSegment($propName);
812
813
            $navProp = new ODataNavigationPropertyInfo($prop, $shouldExpand);
814
            if ($navProp->expanded) {
815
                $this->expandNavigationProperty($entryObject, $prop, $nuLink, $propKind, $propName);
816
            }
817
            $nuLink->isExpanded = isset($nuLink->expandedResult);
818
            if (null === $nuLink->isCollection) {
819
                throw new InvalidOperationException('');
820
            }
821
822
            $links[] = $nuLink;
823
        }
824
        return $links;
825
    }
826
}
827