Skip to content

Commit

Permalink
Add MorphTo relation populator
Browse files Browse the repository at this point in the history
  • Loading branch information
greabock committed Oct 14, 2019
1 parent 7139af7 commit 3d3c7d6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Populator.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Greabock\Populator\Relation\MorphManyPopulator;
use Greabock\Populator\Relation\MorphOnePopulator;
use Greabock\Populator\Relation\MorphToManyPopulator;
use Greabock\Populator\Relation\MorphToPopulator;
use Greabock\Populator\Relation\RelationPopulator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
Expand All @@ -18,6 +19,7 @@
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
Expand Down Expand Up @@ -143,6 +145,7 @@ protected function populateRelation(Model $model, string $relationName, ?array $
private function initRelationPopulators(): void
{
$this->relationPopulators = [
MorphTo::class => new MorphToPopulator($this->resolver, $this->uow, $this),
HasMany::class => new HasManyPopulator($this->resolver, $this->uow, $this),
BelongsToMany::class => new BelongsToManyPopulator($this->resolver, $this->uow, $this),
BelongsTo::class => new BelongsToPopulator($this->resolver, $this->uow, $this),
Expand Down
33 changes: 33 additions & 0 deletions src/Relation/MorphToPopulator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Greabock\Populator\Relation;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Str;

class MorphToPopulator extends RelationPopulator
{
/**
* @param Model $model
* @param Relation|MorphTo $relation
* @param array|null $data
* @param string $relationName
* @throws \Exception
*/
function populate(Model $model, Relation $relation, ?array $data, string $relationName): void
{
$related = $this->populator->populate(get_class($relation->getRelated()), $data);

$this->fillRelationField($model, $relation, $related);

$model->setRelation(Str::snake($relation->getRelationName()), $related);
}

protected function fillRelationField(Model $model, BelongsTo $relation, ?Model $related): void
{
$model->{$relation->getForeignKeyName()} = $related ? $related->{$relation->getOwnerKeyName()} : null;
}
}

0 comments on commit 3d3c7d6

Please sign in to comment.