|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace LiamWiltshire\LaravelJitLoader\Concerns; |
| 4 | + |
| 5 | +use Illuminate\Database\Eloquent\Model; |
| 6 | +use LogicException; |
| 7 | +use Illuminate\Database\Eloquent\Relations\Relation; |
| 8 | +use Illuminate\Database\Eloquent\Collection; |
| 9 | + |
| 10 | +/** |
| 11 | + * Trait AutoloadsRelationships |
| 12 | + * @package LiamWiltshire\LaravelJitLoader\Concerns |
| 13 | + */ |
| 14 | +trait AutoloadsRelationships |
| 15 | +{ |
| 16 | + /** |
| 17 | + * The maximum collection size that we will autoload for |
| 18 | + * @var int |
| 19 | + */ |
| 20 | + protected $autoloadThreshold = 6000; |
| 21 | + |
| 22 | + /** |
| 23 | + * @var ?Collection |
| 24 | + */ |
| 25 | + protected $parentCollection = null; |
| 26 | + |
| 27 | + private function shouldAutoLoad(): bool |
| 28 | + { |
| 29 | + return ($this->parentCollection |
| 30 | + && count($this->parentCollection) > 1 |
| 31 | + && count($this->parentCollection) <= $this->autoloadThreshold); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Load the relationship for the given method, and then get a relationship value from a method. |
| 36 | + * @param string $method |
| 37 | + * @return mixed |
| 38 | + * |
| 39 | + * @throws LogicException |
| 40 | + */ |
| 41 | + public function getRelationshipFromMethod($method) |
| 42 | + { |
| 43 | + $relation = $this->$method(); |
| 44 | + |
| 45 | + if (!$relation instanceof Relation) { |
| 46 | + throw new LogicException( |
| 47 | + sprintf('%s::%s must return a relationship instance.', static::class, $method) |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + if ($this->shouldAutoLoad()) { |
| 52 | + $this->parentCollection->loadMissing($method); |
| 53 | + } |
| 54 | + |
| 55 | + return tap($relation->getResults(), function ($results) use ($method) { |
| 56 | + $this->setRelation($method, $results); |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Create a new Eloquent collection, and assign all models as a member of this collection |
| 62 | + * |
| 63 | + * @param array $models |
| 64 | + * @return Collection |
| 65 | + */ |
| 66 | + public function newCollection(array $models = []): Collection |
| 67 | + { |
| 68 | + $collection = new Collection($models); |
| 69 | + unset($models); |
| 70 | + |
| 71 | + foreach ($collection as &$model) { |
| 72 | + $model->parentCollection = &$collection; |
| 73 | + } |
| 74 | + |
| 75 | + return $collection; |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * Disable autoloading of relationships via this model |
| 80 | + * @return Model |
| 81 | + */ |
| 82 | + public function disableAutoload(): Model |
| 83 | + { |
| 84 | + $this->autoloadThreshold = 0; |
| 85 | + return $this; |
| 86 | + } |
| 87 | +} |
0 commit comments