|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Illuminate\Database\Eloquent\Relations\Concerns; |
| 4 | + |
| 5 | +use Illuminate\Database\Eloquent\Model; |
| 6 | + |
| 7 | +trait SupportsDefaultModels |
| 8 | +{ |
| 9 | + /** |
| 10 | + * Indicates if a default model instance should be used. |
| 11 | + * |
| 12 | + * Alternatively, may be a Closure or array. |
| 13 | + * |
| 14 | + * @var \Closure|array|bool |
| 15 | + */ |
| 16 | + protected $withDefault; |
| 17 | + |
| 18 | + /** |
| 19 | + * Make a new related instance for the given model. |
| 20 | + * |
| 21 | + * @param \Illuminate\Database\Eloquent\Model $parent |
| 22 | + * @return \Illuminate\Database\Eloquent\Model |
| 23 | + */ |
| 24 | + abstract protected function newRelatedInstanceFor(Model $parent); |
| 25 | + |
| 26 | + /** |
| 27 | + * Return a new model instance in case the relationship does not exist. |
| 28 | + * |
| 29 | + * @param \Closure|array|bool $callback |
| 30 | + * @return $this |
| 31 | + */ |
| 32 | + public function withDefault($callback = true) |
| 33 | + { |
| 34 | + $this->withDefault = $callback; |
| 35 | + |
| 36 | + return $this; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Get the default value for this relation. |
| 41 | + * |
| 42 | + * @param \Illuminate\Database\Eloquent\Model $parent |
| 43 | + * @return \Illuminate\Database\Eloquent\Model|null |
| 44 | + */ |
| 45 | + protected function getDefaultFor(Model $parent) |
| 46 | + { |
| 47 | + if (! $this->withDefault) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + $instance = $this->newRelatedInstanceFor($parent); |
| 52 | + |
| 53 | + if (is_callable($this->withDefault)) { |
| 54 | + return call_user_func($this->withDefault, $instance) ?: $instance; |
| 55 | + } |
| 56 | + |
| 57 | + if (is_array($this->withDefault)) { |
| 58 | + $instance->forceFill($this->withDefault); |
| 59 | + } |
| 60 | + |
| 61 | + return $instance; |
| 62 | + } |
| 63 | +} |
0 commit comments