Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 37 additions & 20 deletions src/Concerns/HasSnapshot.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Oobook\Snapshot\Models\Snapshot;
use Oobook\Snapshot\Relations\SnapshotSyncedRelationFactory;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
Expand Down Expand Up @@ -103,20 +104,41 @@ public static function bootHasSnapshot()
// $model->fillable = $model->originalFillableForSnapshot;
});

static::addGlobalScope('snapshot_required_for_synced', function ($builder) {
if (empty(static::getSourceRelationshipsToSync())) {
return;
}
$eagerLoads = $builder->getEagerLoads();
if (! array_key_exists('snapshot', $eagerLoads)) {
$builder->with('snapshot');
}
});

$sourceClass = static::getSnapshotSourceClass();
$sourceInstance = new $sourceClass();
$syncedSourceRelationships = static::getSourceRelationshipsToSync();

foreach ($syncedSourceRelationships as $relationship) {
if(!method_exists(static::class, $relationship)){
static::resolveRelationUsing($relationship, function ($snapshotable) use ($sourceInstance, $relationship) {
$source = $snapshotable->snapshotSource;

if($source){
return $source->{$relationship}();
if (! method_exists(static::class, $relationship)) {
static::resolveRelationUsing($relationship, function ($snapshotable) use ($sourceInstance, $relationship, $sourceClass) {
$sourceRelation = $sourceInstance->{$relationship}();

if (SnapshotSyncedRelationFactory::supports($sourceRelation)) {
return SnapshotSyncedRelationFactory::make(
$sourceRelation,
$snapshotable,
$sourceClass,
$relationship
);
}

return $sourceInstance->{$relationship}();
throw new \InvalidArgumentException(
sprintf(
'Snapshot relation [%s] on [%s] is not supported. Use BelongsTo, MorphTo, HasOne, HasMany, HasOneThrough, HasManyThrough, BelongsToMany, MorphOne, MorphMany, or MorphToMany.',
$relationship,
get_class($snapshotable)
)
);
});
}
}
Expand All @@ -131,11 +153,14 @@ public static function bootHasSnapshot()
*/
public function initializeHasSnapshot()
{
$this->makeHidden(array_merge($this->hidden, ['snapshotSource', 'snapshot']));
$this->mergeFillable($this->getFillableForSnapshot());

$this->withSnapshot = array_values(array_intersect($this->with, $this->getSourceRelationshipsToSnapshot()));

$this->with = array_merge(array_values(array_diff($this->with, $this->withSnapshot)), ['snapshot']);
$baseWith = array_merge(array_values(array_diff($this->with, $this->withSnapshot)), ['snapshot', 'snapshotSource']);
$syncedRelations = static::getSourceRelationshipsToSync();
$this->with = array_values(array_unique(array_merge($baseWith, $syncedRelations)));
}

/**
Expand Down Expand Up @@ -372,7 +397,6 @@ public function attributesToArray(): array

$snapshot = $this->snapshot;


if($source){
$reservedAttributes = $this->getReservedAttributesAgainstSnapshot();
$snapshotableSourceAttributes = $this->getSnapshotableSourceAttributes();
Expand All @@ -392,6 +416,7 @@ public function attributesToArray(): array

$snapshottedKeys = $this->getSourceAttributesToSnapshot();
$snapshottedAttributes = [];

if($snapshot){
$snapshottedAttributes = array_intersect_key($snapshot->data, array_flip($snapshottedKeys));
if($snapshottedWiths){
Expand All @@ -417,27 +442,22 @@ public function __get($key)
$sourceClass = new ($this->getSnapshotSourceClass());
$foreignKey = $this->getSnapshotSourceForeignKey();


if($this->exists
&& !in_array($key, $reservedAttributes)
&& !in_array($key, ['snapshot', 'source', 'snapshotSource'])
){

if($this->snapshot()->exists() && $foreignKey ){
if($this->snapshot && $foreignKey ){

$snapshot = $this->snapshot;

if($foreignKey == $key){
return $snapshot->source_id;
}

$source = $this->relationLoaded('snapshotSource')
? $this->getRelation('snapshotSource')
: $this->snapshotSource;

if($this->fieldIsSnapshotSynced($key)){
if($source){
return $source->{$key};
if($this->snapshotSource){
return $this->snapshotSource->{$key};
}
}

Expand Down Expand Up @@ -503,7 +523,6 @@ public function __get($key)
*/
public function __call($method, $parameters)
{

if($this->exists && !$this->hasColumn($method) ){

$snapshotSourceClass = $this->getSnapshotSourceClass();
Expand Down Expand Up @@ -541,8 +560,6 @@ public function __call($method, $parameters)
}
}



return parent::__call($method, $parameters);
}
}
4 changes: 4 additions & 0 deletions src/Models/Snapshot.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ class Snapshot extends Model
'data' => 'array',
];

protected $hidden = [
'data',
];

public function snapshotable(): \Illuminate\Database\Eloquent\Relations\MorphTo
{
return $this->morphTo();
Expand Down
119 changes: 119 additions & 0 deletions src/Relations/Concerns/ResolvesSnapshotSource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

declare(strict_types=1);

namespace Oobook\Snapshot\Relations\Concerns;

use Illuminate\Database\Eloquent\Model;
use Oobook\Snapshot\Models\Snapshot;

/**
* Trait for SnapshotSynced relations to resolve source model IDs from snapshot models.
*/
trait ResolvesSnapshotSource
{
/**
* Get source IDs from a batch of snapshot models.
* Ensures snapshot relation is loaded if needed.
*
* @param array<Model> $models Snapshot models (e.g. PressReleasePackage)
* @return array<int|string> Source model IDs
*/
protected function getSourceIdsFromSnapshotModels(array $models): array
{
$sourceIds = [];

foreach ($models as $model) {
$sourceId = $this->getSourceIdFromSnapshotModel($model);
if ($sourceId !== null) {
$sourceIds[] = $sourceId;
}
}

return array_values(array_unique($sourceIds));
}

/**
* Get source ID from a single snapshot model.
*
* @return int|string|null
*/
protected function getSourceIdFromSnapshotModel(Model $model)
{
$snapshot = $model->relationLoaded('snapshot')
? $model->getRelation('snapshot')
: $model->snapshot;

if ($snapshot instanceof Snapshot) {
return $snapshot->source_id;
}

$class = get_class($model);
if (method_exists($class, 'getSnapshotSourceForeignKey')) {
$foreignKey = $class::getSnapshotSourceForeignKey();

return $model->getAttribute($foreignKey);
}

return null;
}

/**
* Build a map of snapshot model key => source_id for matching.
*
* @param array<Model> $models
* @return array<string, int|string>
*/
protected function getSnapshotKeyToSourceIdMap(array $models): array
{
$map = [];

foreach ($models as $model) {
$sourceId = $this->getSourceIdFromSnapshotModel($model);
if ($sourceId !== null) {
$map[$model->getKey()] = $sourceId;
}
}

return $map;
}

/**
* Ensure snapshot relation is loaded on models that don't have it.
*
* @param array<Model> $models
*/
protected function ensureSnapshotLoaded(array $models): void
{
if (empty($models)) {
return;
}

$needsLoad = [];
foreach ($models as $model) {
if (! $model->relationLoaded('snapshot')) {
$needsLoad[] = $model;
}
}

if (empty($needsLoad)) {
return;
}

$modelClass = get_class($models[0]);
$ids = array_map(fn ($m) => $m->getKey(), $needsLoad);

$snapshots = Snapshot::query()
->where('snapshotable_type', $modelClass)
->whereIn('snapshotable_id', $ids)
->get()
->keyBy('snapshotable_id');

foreach ($needsLoad as $model) {
$snapshot = $snapshots->get($model->getKey());
if ($snapshot) {
$model->setRelation('snapshot', $snapshot);
}
}
}
}
Loading
Loading