-
Notifications
You must be signed in to change notification settings - Fork 15
/
EagerLoadIterator.php
113 lines (99 loc) · 2.62 KB
/
EagerLoadIterator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/*
* Copyright 2024 Cloud Creativity Limited
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
declare(strict_types=1);
namespace LaravelJsonApi\Eloquent\QueryBuilder\EagerLoading;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use IteratorAggregate;
use LaravelJsonApi\Core\Query\IncludePaths;
use LaravelJsonApi\Eloquent\Schema;
use Traversable;
/**
* Class EagerLoadIterator
*
* @internal
*/
class EagerLoadIterator implements IteratorAggregate
{
/**
* @var Schema
*/
private Schema $schema;
/**
* @var IncludePaths
*/
private IncludePaths $paths;
/**
* Fluent constructor.
*
* @param Schema $schema
* @param mixed $paths
* @return static
*/
public static function make(Schema $schema, IncludePaths $paths): self
{
return new self($schema, $paths);
}
/**
* EagerLoadIterator constructor.
*
* @param Schema $schema
* @param IncludePaths $paths
*/
public function __construct(Schema $schema, IncludePaths $paths)
{
$this->schema = $schema;
$this->paths = $paths;
}
/**
* Get the paths as a collection.
*
* Before returning the paths, we filter out any duplicates. For example, if the iterator
* yields `user` and `user.country`, we only want `user.country` to be in the collection.
*
* @return Collection
*/
public function collect(): Collection
{
$values = collect($this);
return $values->reject(
fn($path) => $values->contains(fn($check) => $path !== $check && Str::startsWith($check, $path))
)->sort()->values();
}
/**
* @return array
*/
public function all(): array
{
return $this->collect()->all();
}
/**
* @inheritDoc
*/
public function getIterator(): Traversable
{
/**
* We always need to yield the default paths on the base schema.
*/
foreach ($this->schema->with() as $relation) {
yield $relation;
}
/**
* Next we iterate over the include paths, using the EagerLoadPathList
* class to work out what the eager load path(s) are for each include
* path. (One JSON:API include path can map to one-to-many Eloquent
* eager load paths.)
*/
foreach ($this->paths as $path) {
foreach (new EagerLoadPathList($this->schema, $path) as $eagerLoadPath) {
yield $eagerLoadPath;
}
}
}
}