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
35 changes: 28 additions & 7 deletions src/Models/Concerns/UsesCustomFields.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,14 +214,27 @@ public function getCustomFieldValue(CustomField $customField): mixed

public function saveCustomFieldValue(CustomField $customField, mixed $value, ?Model $tenant = null): void
{
$data = ['custom_field_id' => $customField->getKey()];
$customFieldValue = $this->customFieldValues()->firstOrNew($this->customFieldValueKey($customField, $tenant));

$this->writeCustomFieldValue($customFieldValue, $customField, $value);
}

/**
* @return array<string, mixed>
*/
protected function customFieldValueKey(CustomField $customField, ?Model $tenant): array
{
$key = ['custom_field_id' => $customField->getKey()];

if (FeatureManager::isEnabled(CustomFieldsFeature::SYSTEM_MULTI_TENANCY)) {
$data[config('custom-fields.database.column_names.tenant_foreign_key')] = $this->resolveTenantId($tenant, $customField);
$key[config('custom-fields.database.column_names.tenant_foreign_key')] = $this->resolveTenantId($tenant, $customField);
}

$customFieldValue = $this->customFieldValues()->firstOrNew($data);
return $key;
}

protected function writeCustomFieldValue(CustomFieldValue $customFieldValue, CustomField $customField, mixed $value): void
{
if ($customField->settings?->encrypted) {
$customFieldValue->mergeCasts([$customField->getValueColumn() => 'encrypted']);
}
Expand Down Expand Up @@ -264,10 +277,18 @@ public function saveCustomFields(array $customFields, ?Model $tenant = null): vo
$objectId = spl_object_id($this);
unset(self::$changedCustomFieldValues[$objectId]);

$this->customFields()->each(function (CustomField $customField) use ($customFields, $tenant): void {
$value = $customFields[$customField->code] ?? null;
$this->saveCustomFieldValue($customField, $value, $tenant);
});
$fields = $this->customFields()->with('options')->get();
$existing = $this->customFieldValues()->whereIn('custom_field_id', $fields->modelKeys())->get()->groupBy('custom_field_id');

foreach ($fields as $customField) {
$key = $this->customFieldValueKey($customField, $tenant);
$customFieldValue = $existing->get($customField->getKey(), collect())
->first(fn (CustomFieldValue $row): bool => collect($key)->every(fn (mixed $expected, string $column): bool => $row->getAttribute($column) == $expected))
?? $this->customFieldValues()->make($key);

$customFieldValue->setRelation('customField', $customField);
$this->writeCustomFieldValue($customFieldValue, $customField, $customFields[$customField->code] ?? null);
}

if (! isset(self::$changedCustomFieldValues[$objectId])) {
return;
Expand Down
74 changes: 74 additions & 0 deletions tests/Feature/Models/UsesCustomFieldsTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -289,3 +289,77 @@ class GuardedTestModel extends Model implements HasCustomFields
expect($updates)->toBe(0);
});
});

describe('Query Count', function (): void {
function readQueriesWhileSaving(int $fieldCount): int
{
$section = CustomFieldSection::factory()->forEntityType(Post::class)->create(['active' => true]);
$codes = [];

for ($i = 0; $i < $fieldCount; $i++) {
$codes[] = CustomField::factory()->ofType('text')->create([
'custom_field_section_id' => $section->getKey(),
'entity_type' => Post::class,
])->code;
}

$post = Post::factory()->create();
$post->saveCustomFields(array_fill_keys($codes, 'first'));
$post = $post->fresh();

DB::flushQueryLog();
DB::enableQueryLog();
$post->update(['custom_fields' => array_fill_keys($codes, 'second')]);
$queries = collect(DB::getQueryLog())->filter(fn (array $query): bool => str_starts_with($query['query'], 'select'))->count();
DB::disableQueryLog();

return $queries;
}

it('reads the same number of rows whether a save touches 4 fields or 10', function (): void {
$four = readQueriesWhileSaving(4);
CustomField::query()->forceDelete();
$ten = readQueriesWhileSaving(10);

expect($ten)->toBe($four);
});

it('still clears every value when null is saved', function (): void {
$section = CustomFieldSection::factory()->forEntityType(Post::class)->create(['active' => true]);
$fields = CustomField::factory()->ofType('text')->count(3)->create([
'custom_field_section_id' => $section->getKey(),
'entity_type' => Post::class,
]);
$post = Post::factory()->create();
$post->saveCustomFields($fields->pluck('code')->mapWithKeys(fn (string $code): array => [$code => 'filled'])->all());

$post->saveCustomFields($fields->pluck('code')->mapWithKeys(fn (string $code): array => [$code => null])->all());

$post = $post->fresh();
expect($fields->map(fn (CustomField $field): mixed => $post->getCustomFieldValue($field))->filter()->all())->toBe([])
->and(CustomFieldValue::query()->count())->toBe(3);
});

it('hands a saved value its field with options loaded when lazy loading is prevented', function (): void {
$section = CustomFieldSection::factory()->forEntityType(Post::class)->create(['active' => true]);
$fields = CustomField::factory()->ofType('text')->count(2)->create([
'custom_field_section_id' => $section->getKey(),
'entity_type' => Post::class,
]);
$post = Post::factory()->create();
$optionCounts = [];
CustomFieldValue::saved(function (CustomFieldValue $value) use (&$optionCounts): void {
$optionCounts[] = $value->customField->options->count();
});

Model::preventLazyLoading();

try {
$post->saveCustomFields($fields->pluck('code')->mapWithKeys(fn (string $code): array => [$code => 'filled'])->all());
} finally {
Model::preventLazyLoading(false);
}

expect($optionCounts)->toBe([0, 0]);
});
});