Completed
Push — master ( 57f6ab...1a78f7 )
by Andrew
9s
created

src/Scope.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of the League\Fractal package.
5
 *
6
 * (c) Phil Sturgeon <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 **/
11
12
namespace League\Fractal;
13
14
use InvalidArgumentException;
15
use League\Fractal\Resource\Collection;
16
use League\Fractal\Resource\Item;
17
use League\Fractal\Resource\NullResource;
18
use League\Fractal\Resource\ResourceInterface;
19
use League\Fractal\Serializer\SerializerAbstract;
20
21
/**
22
 * Scope
23
 *
24
 * The scope class acts as a tracker, relating a specific resource in a specific
25
 * context. For example, the same resource could be attached to multiple scopes.
26
 * There are root scopes, parent scopes and child scopes.
27
 */
28
class Scope
29
{
30
    /**
31
     * @var array
32
     */
33
    protected $availableIncludes = [];
34
35
    /**
36
     * @var string
37
     */
38
    protected $scopeIdentifier;
39
40
    /**
41
     * @var \League\Fractal\Manager
42
     */
43
    protected $manager;
44
45
    /**
46
     * @var ResourceInterface
47
     */
48
    protected $resource;
49
50
    /**
51
     * @var array
52
     */
53
    protected $parentScopes = [];
54
55
    /**
56
     * Create a new scope instance.
57
     *
58
     * @param Manager           $manager
59
     * @param ResourceInterface $resource
60
     * @param string            $scopeIdentifier
61
     *
62
     * @return void
63
     */
64 54
    public function __construct(Manager $manager, ResourceInterface $resource, $scopeIdentifier = null)
65
    {
66 54
        $this->manager = $manager;
67 54
        $this->resource = $resource;
68 54
        $this->scopeIdentifier = $scopeIdentifier;
69 54
    }
70
71
    /**
72
     * Embed a scope as a child of the current scope.
73
     *
74
     * @internal
75
     *
76
     * @param string            $scopeIdentifier
77
     * @param ResourceInterface $resource
78
     *
79
     * @return \League\Fractal\Scope
80
     */
81 27
    public function embedChildScope($scopeIdentifier, $resource)
82
    {
83 27
        return $this->manager->createData($resource, $scopeIdentifier, $this);
84
    }
85
86
    /**
87
     * Get the current identifier.
88
     *
89
     * @return string
90
     */
91 27
    public function getScopeIdentifier()
92
    {
93 27
        return $this->scopeIdentifier;
94
    }
95
96
    /**
97
     * Get the unique identifier for this scope.
98
     *
99
     * @param string $appendIdentifier
100
     *
101
     * @return string
102
     */
103 23
    public function getIdentifier($appendIdentifier = null)
104
    {
105 23
        $identifierParts = array_merge($this->parentScopes, [$this->scopeIdentifier, $appendIdentifier]);
106
107 23
        return implode('.', array_filter($identifierParts));
108
    }
109
110
    /**
111
     * Getter for parentScopes.
112
     *
113
     * @return mixed
114
     */
115 28
    public function getParentScopes()
116
    {
117 28
        return $this->parentScopes;
118
    }
119
120
    /**
121
     * Getter for resource.
122
     *
123
     * @return ResourceInterface
124
     */
125 1
    public function getResource()
126
    {
127 1
        return $this->resource;
128
    }
129
130
    /**
131
     * Getter for manager.
132
     *
133
     * @return \League\Fractal\Manager
134
     */
135 23
    public function getManager()
136
    {
137 23
        return $this->manager;
138
    }
139
140
    /**
141
     * Is Requested.
142
     *
143
     * Check if - in relation to the current scope - this specific segment is allowed.
144
     * That means, if a.b.c is requested and the current scope is a.b, then c is allowed. If the current
145
     * scope is a then c is not allowed, even if it is there and potentially transformable.
146
     *
147
     * @internal
148
     *
149
     * @param string $checkScopeSegment
150
     *
151
     * @return bool Returns the new number of elements in the array.
152
     */
153 32 View Code Duplication
    public function isRequested($checkScopeSegment)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
    {
155 32
        if ($this->parentScopes) {
156 14
            $scopeArray = array_slice($this->parentScopes, 1);
157 14
            array_push($scopeArray, $this->scopeIdentifier, $checkScopeSegment);
158 14
        } else {
159 32
            $scopeArray = [$checkScopeSegment];
160
        }
161
162 32
        $scopeString = implode('.', (array) $scopeArray);
163
164 32
        return in_array($scopeString, $this->manager->getRequestedIncludes());
165
    }
166
167
    /**
168
     * Is Excluded.
169
     *
170
     * Check if - in relation to the current scope - this specific segment should
171
     * be excluded. That means, if a.b.c is excluded and the current scope is a.b,
172
     * then c will not be allowed in the transformation whether it appears in
173
     * the list of default or available, requested includes.
174
     *
175
     * @internal
176
     *
177
     * @param string $checkScopeSegment
178
     *
179
     * @return bool
180
     */
181 23 View Code Duplication
    public function isExcluded($checkScopeSegment)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
182
    {
183 23
        if ($this->parentScopes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->parentScopes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
184 3
            $scopeArray = array_slice($this->parentScopes, 1);
185 3
            array_push($scopeArray, $this->scopeIdentifier, $checkScopeSegment);
186 3
        } else {
187 23
            $scopeArray = [$checkScopeSegment];
188
        }
189
190 23
        $scopeString = implode('.', (array) $scopeArray);
191
192 23
        return in_array($scopeString, $this->manager->getRequestedExcludes());
193
    }
194
195
    /**
196
     * Push Parent Scope.
197
     *
198
     * Push a scope identifier into parentScopes
199
     *
200
     * @internal
201
     *
202
     * @param string $identifierSegment
203
     *
204
     * @return int Returns the new number of elements in the array.
205
     */
206 1
    public function pushParentScope($identifierSegment)
207
    {
208 1
        return array_push($this->parentScopes, $identifierSegment);
209
    }
210
211
    /**
212
     * Set parent scopes.
213
     *
214
     * @internal
215
     *
216
     * @param string[] $parentScopes Value to set.
217
     *
218
     * @return $this
219
     */
220 27
    public function setParentScopes($parentScopes)
221
    {
222 27
        $this->parentScopes = $parentScopes;
223
224 27
        return $this;
225
    }
226
227
    /**
228
     * Convert the current data for this scope to an array.
229
     *
230
     * @return array
231
     */
232 43
    public function toArray()
233
    {
234 43
        list($rawData, $rawIncludedData) = $this->executeResourceTransformers();
235
236 42
        $serializer = $this->manager->getSerializer();
237
238 42
        $data = $this->serializeResource($serializer, $rawData);
239
240
        // If the serializer wants the includes to be side-loaded then we'll
241
        // serialize the included data and merge it with the data.
242 41
        if ($serializer->sideloadIncludes()) {
243 25
            $includedData = $serializer->includedData($this->resource, $rawIncludedData);
244
245
            // If the serializer wants to inject additional information
246
            // about the included resources, it can do so now.
247 25
            $data = $serializer->injectData($data, $rawIncludedData);
248
249 25
            if ($this->isRootScope()) {
250
                // If the serializer wants to have a final word about all
251
                // the objects that are sideloaded, it can do so now.
252 25
                $includedData = $serializer->filterIncludes(
253 25
                    $includedData,
254
                    $data
255 25
                );
256 25
            }
257
258 25
            $data = array_merge($data, $includedData);
259 25
        }
260
261 41
        if ($this->resource instanceof Collection) {
262 24
            if ($this->resource->hasCursor()) {
263 1
                $pagination = $serializer->cursor($this->resource->getCursor());
264 24
            } elseif ($this->resource->hasPaginator()) {
265 4
                $pagination = $serializer->paginator($this->resource->getPaginator());
266 4
            }
267
268 24
            if (! empty($pagination)) {
269 5
                $this->resource->setMetaValue(key($pagination), current($pagination));
270 5
            }
271 24
        }
272
273
        // Pull out all of OUR metadata and any custom meta data to merge with the main level data
274 41
        $meta = $serializer->meta($this->resource->getMeta());
275
276 41
        return array_merge($data, $meta);
277
    }
278
279
    /**
280
     * Convert the current data for this scope to JSON.
281
     *
282
     * @return string
283
     */
284 30
    public function toJson()
285
    {
286 30
        return json_encode($this->toArray());
287
    }
288
289
    /**
290
     * Execute the resources transformer and return the data and included data.
291
     *
292
     * @internal
293
     *
294
     * @return array
295
     */
296 43
    protected function executeResourceTransformers()
297
    {
298 43
        $transformer = $this->resource->getTransformer();
299 43
        $data = $this->resource->getData();
300
301 43
        $transformedData = $includedData = [];
302
303 43
        if ($this->resource instanceof Item) {
304 28
            list($transformedData, $includedData[]) = $this->fireTransformer($transformer, $data);
305 43
        } elseif ($this->resource instanceof Collection) {
306 24
            foreach ($data as $value) {
307 23
                list($transformedData[], $includedData[]) = $this->fireTransformer($transformer, $value);
308 24
            }
309 29
        } elseif ($this->resource instanceof NullResource) {
310 4
            $transformedData = null;
311 4
            $includedData = [];
312 4
        } else {
313 2
            throw new InvalidArgumentException(
314
                'Argument $resource should be an instance of League\Fractal\Resource\Item'
315
                .' or League\Fractal\Resource\Collection'
316 2
            );
317
        }
318
319 41
        return [$transformedData, $includedData];
320
    }
321
322
    /**
323
     * Serialize a resource
324
     *
325
     * @internal
326
     *
327
     * @param SerializerAbstract $serializer
328
     * @param mixed              $data
329
     *
330
     * @return array
331
     */
332 41
    protected function serializeResource(SerializerAbstract $serializer, $data)
333
    {
334 41
        $resourceKey = $this->resource->getResourceKey();
335
336 41
        if ($this->resource instanceof Collection) {
337 24
            return $serializer->collection($resourceKey, $data);
338
        }
339
340 30
        if ($this->resource instanceof Item) {
341 28
            return $serializer->item($resourceKey, $data);
342
        }
343
344 4
        return $serializer->null();
345
    }
346
347
    /**
348
     * Fire the main transformer.
349
     *
350
     * @internal
351
     *
352
     * @param TransformerAbstract|callable $transformer
353
     * @param mixed                        $data
354
     *
355
     * @return array
356
     */
357 39
    protected function fireTransformer($transformer, $data)
358
    {
359 39
        $includedData = [];
360
361 39
        if (is_callable($transformer)) {
362 4
            $transformedData = call_user_func($transformer, $data);
363 4
        } else {
364 35
            $transformer->setCurrentScope($this);
365 35
            $transformedData = $transformer->transform($data);
366
        }
367
368 39
        if ($this->transformerHasIncludes($transformer)) {
369 33
            $includedData = $this->fireIncludedTransformers($transformer, $data);
370 33
            $transformedData = $this->manager->getSerializer()->mergeIncludes($transformedData, $includedData);
371 33
        }
372
373 39
        return [$transformedData, $includedData];
374
    }
375
376
    /**
377
     * Fire the included transformers.
378
     *
379
     * @internal
380
     *
381
     * @param \League\Fractal\TransformerAbstract $transformer
382
     * @param mixed                               $data
383
     *
384
     * @return array
385
     */
386 33
    protected function fireIncludedTransformers($transformer, $data)
387
    {
388 33
        $this->availableIncludes = $transformer->getAvailableIncludes();
389
390 33
        return $transformer->processIncludedResources($this, $data) ?: [];
391
    }
392
393
    /**
394
     * Determine if a transformer has any available includes.
395
     *
396
     * @internal
397
     *
398
     * @param TransformerAbstract|callable $transformer
399
     *
400
     * @return bool
401
     */
402 39
    protected function transformerHasIncludes($transformer)
403
    {
404 39
        if (! $transformer instanceof TransformerAbstract) {
405 4
            return false;
406
        }
407
408 35
        $defaultIncludes = $transformer->getDefaultIncludes();
409 35
        $availableIncludes = $transformer->getAvailableIncludes();
410
411 35
        return ! empty($defaultIncludes) || ! empty($availableIncludes);
412
    }
413
414
    /**
415
     * Check, if this is the root scope.
416
     *
417
     * @return bool
418
     */
419 25
    protected function isRootScope()
420
    {
421 25
        return empty($this->parentScopes);
422
    }
423
}
424