Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.x] Allow ensuring fields in fieldsets #11097

Open
wants to merge 4 commits into
base: 5.x
Choose a base branch
from
Open
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
128 changes: 126 additions & 2 deletions src/Fields/Fieldset.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Statamic\Fields;

use Facades\Statamic\Fields\FieldRepository;
use Statamic\Events\FieldsetCreated;
use Statamic\Events\FieldsetCreating;
use Statamic\Events\FieldsetDeleted;
Expand All @@ -25,6 +26,7 @@ class Fieldset
{
protected $handle;
protected $contents = [];
protected $ensuredFields = [];
protected $afterSaveCallbacks = [];
protected $withEvents = true;
protected $initialPath;
Expand Down Expand Up @@ -80,7 +82,99 @@ public function setContents(array $contents)

public function contents(): array
{
return $this->contents;
return $this->getContents();
}

private function getContents()
{
$contents = $this->contents;

$contents['fields'] = $contents['fields'] ?? [];

if ($this->ensuredFields) {
$contents = $this->addEnsuredFieldsToContents($contents, $this->ensuredFields);
}

return array_filter($contents);
}

private function addEnsuredFieldsToContents($contents, $ensuredFields)
{
foreach ($ensuredFields as $field) {
$contents = $this->addEnsuredFieldToContents($contents, $field);
}

return $contents;
}

private function addEnsuredFieldToContents($contents, $ensured)
{
$imported = false;
$handle = $ensured['handle'];
$config = $ensured['config'];
$prepend = $ensured['prepend'];

$fields = collect($contents['fields'] ?? [])->keyBy(function ($field) {
return (isset($field['import'])) ? 'import:'.($field['prefix'] ?? null).$field['import'] : $field['handle'];
});

$importedFields = $fields->filter(function ($field, $key) {
return Str::startsWith($key, 'import:');
})->keyBy(function ($field) {
return ($field['prefix'] ?? null).$field['import'];
})->mapWithKeys(function ($field, $partial) {
return (new Fields([$field]))->all()->map(function ($field) use ($partial) {
return compact('partial', 'field');
});
});

// If a field with that handle is in the contents, its either an inline field or a referenced field...
$existingField = $fields->get($handle);

if ($exists = $existingField !== null) {
if (is_string($existingField['field'])) {
// If it's a string, then it's a reference field. We should merge any ensured config into the 'config'
// override array, but only keys that don't already exist in the actual partial field's config.
$referencedField = FieldRepository::find($existingField['field']);
$referencedFieldConfig = $referencedField->config();
$config = array_merge($config, $referencedFieldConfig);
$config = Arr::except($config, array_keys($referencedFieldConfig));
$field = ['handle' => $handle, 'field' => $existingField['field'], 'config' => $config];
} else {
// If it's not a string, then it's an inline field. We'll just merge the
// config right into the field key, with the user defined config winning.
$config = array_merge($config, $existingField['field']);
$field = ['handle' => $handle, 'field' => $config];
}
} else {
if ($importedField = $importedFields->get($handle)) {
$importKey = 'import:'.$importedField['partial'];
$field = $fields->get($importKey);
$importedConfig = $importedField['field']->config();
$config = array_merge($config, $importedConfig);
$config = Arr::except($config, array_keys($importedConfig));
$field['config'][$handle] = $config;
$fields->put($importKey, $field);
$imported = true;
} else {
$field = ['handle' => $handle, 'field' => $config];
}
}

// Set the field config in it's proper place.
if (! $imported) {
if ($exists) {
$fields->put($handle, $field);
} elseif (! $exists && $prepend) {
$fields->prepend($field);
} else {
$fields->push($field);
}
}

$contents['fields'] = $fields->values()->all();

return $contents;
}

public function title()
Expand All @@ -98,7 +192,7 @@ public function validateRecursion()

public function fields(): Fields
{
$fields = Arr::get($this->contents, 'fields', []);
$fields = Arr::get($this->contents(), 'fields', []);

return new Fields($fields);
}
Expand All @@ -108,6 +202,11 @@ public function field(string $handle): ?Field
return $this->fields()->get($handle);
}

public function hasField(string $handle): bool
{
return $this->fields()->has($handle);
}

public function isNamespaced(): bool
{
return Str::contains($this->handle(), '::');
Expand Down Expand Up @@ -291,6 +390,31 @@ public function reset()
return true;
}

public function ensureField($handle, $config, $prepend = false)
{
if (isset($this->ensuredFields[$handle])) {
return $this;
}

$this->ensuredFields[$handle] = compact('handle', 'prepend', 'config');

return $this;
}

public function ensureFieldPrepended($handle, $field)
{
return $this->ensureField($handle, $field, true);
}

public function ensureFieldHasConfig($handle, $config)
{
if (! $this->hasField($handle)) {
return $this;
}

return $this->ensureField($handle, $config);
}

public static function __callStatic($method, $parameters)
{
return Facades\Fieldset::{$method}(...$parameters);
Expand Down
1 change: 0 additions & 1 deletion tests/Feature/Fieldsets/StoreFieldsetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ public function fieldset_gets_created()
$fieldset = Facades\Fieldset::find('test');
$this->assertEquals([
'title' => 'Test',
'fields' => [],
], $fieldset->contents());
$this->assertEquals('test', $fieldset->handle());
}
Expand Down
207 changes: 207 additions & 0 deletions tests/Fields/FieldsetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -572,4 +572,211 @@ public function it_deletes_quietly()

$this->assertTrue($return);
}

#[Test]
public function it_ensures_a_field_exists()
{
$fieldset = (new Fieldset)->setContents(['fields' => [
['handle' => 'existing', 'field' => ['type' => 'text']],
]]);

$return = $fieldset->ensureField('new', ['type' => 'textarea']);

$this->assertEquals($fieldset, $return);
$this->assertTrue($fieldset->hasField('existing'));
$this->assertTrue($fieldset->hasField('new'));

$this->assertEquals(['fields' => [
['handle' => 'existing', 'field' => ['type' => 'text']],
['handle' => 'new', 'field' => ['type' => 'textarea']],
]], $fieldset->contents());

$this->assertEquals(['type' => 'textarea'], $fieldset->fields()->get('new')->config());
}

#[Test]
public function it_can_add_fields_multiple_times()
{
$fieldset = (new Fieldset)->setContents(['fields' => [
['handle' => 'existing', 'field' => ['type' => 'text']],
]]);

$fieldset
->ensureField('new_one', ['type' => 'text'])
->ensureField('new_two', ['type' => 'textarea']);

$this->assertTrue($fieldset->hasField('existing'));
$this->assertTrue($fieldset->hasField('new_one'));
$this->assertTrue($fieldset->hasField('new_two'));

$this->assertEquals(['fields' => [
['handle' => 'existing', 'field' => ['type' => 'text']],
['handle' => 'new_one', 'field' => ['type' => 'text']],
['handle' => 'new_two', 'field' => ['type' => 'textarea']],
]], $fieldset->contents());

$this->assertEquals(['type' => 'text'], $fieldset->fields()->get('new_one')->config());
$this->assertEquals(['type' => 'textarea'], $fieldset->fields()->get('new_two')->config());
}

#[Test]
public function it_ensures_a_field_has_config()
{
FieldsetRepository::shouldReceive('find')->with('the_partial')->andReturn(
(new Fieldset)->setContents(['fields' => [
[
'handle' => 'the_field',
'field' => ['type' => 'text', 'do_not_touch_other_config' => true],
],
]])
);

$fieldset = (new Fieldset)->setContents(['fields' => [
['handle' => 'title', 'field' => ['type' => 'text']],
['handle' => 'author', 'field' => ['type' => 'text', 'do_not_touch_other_config' => true]],
['handle' => 'content', 'field' => ['type' => 'text']],
['handle' => 'the_field', 'field' => 'the_partial.the_field', 'config' => ['type' => 'text', 'do_not_touch_other_config' => true]],
]]);

$fields = $fieldset
->ensureFieldHasConfig('author', ['visibility' => 'read_only'])
->ensureFieldHasConfig('the_field', ['visibility' => 'read_only'])
->fields();

$this->assertEquals(['type' => 'text'], $fields->get('title')->config());
$this->assertEquals(['type' => 'text'], $fields->get('content')->config());

$expectedConfig = [
'type' => 'text',
'do_not_touch_other_config' => true,
'visibility' => 'read_only',
];

$this->assertEquals($expectedConfig, $fields->get('author')->config());
$this->assertEquals($expectedConfig, $fields->get('the_field')->config());
}

#[Test]
public function it_merges_previously_undefined_keys_into_the_config_when_ensuring_a_field_exists_and_it_already_exists()
{
$fieldset = (new Fieldset)->setContents(['fields' => [
['handle' => 'existing', 'field' => ['type' => 'text']],
]]);

$return = $fieldset->ensureField('existing', ['type' => 'textarea', 'foo' => 'bar']);

$this->assertEquals($fieldset, $return);
$this->assertTrue($fieldset->hasField('existing'));

$this->assertEquals(['fields' => [
['handle' => 'existing', 'field' => ['type' => 'text', 'foo' => 'bar']],
]], $fieldset->contents());

$this->assertEquals(['type' => 'text', 'foo' => 'bar'], $fieldset->fields()->get('existing')->config());
}

#[Test]
public function it_merges_previously_undefined_keys_into_the_config_when_ensuring_prepended_a_field_exists_and_it_already_exists()
{
$fieldset = (new Fieldset)->setContents(['fields' => [
['handle' => 'first', 'field' => ['type' => 'text']],
['handle' => 'existing', 'field' => ['type' => 'text']],
]]);

$return = $fieldset->ensureField('existing', ['type' => 'textarea', 'foo' => 'bar']);

$this->assertEquals($fieldset, $return);
$this->assertTrue($fieldset->hasField('existing'));

$this->assertEquals(['fields' => [
['handle' => 'first', 'field' => ['type' => 'text']],
['handle' => 'existing', 'field' => ['type' => 'text', 'foo' => 'bar']],
]], $fieldset->contents());

$this->assertEquals(['type' => 'text', 'foo' => 'bar'], $fieldset->fields()->get('existing')->config());
}

#[Test]
public function it_merges_config_overrides_for_previously_undefined_keys_when_ensuring_a_field_and_it_already_exists_as_a_reference()
{
FieldsetRepository::shouldReceive('find')->with('the_partial')->andReturn(
(new Fieldset)->setContents(['fields' => [
[
'handle' => 'the_field',
'field' => ['type' => 'text'],
],
]])
);

$fieldset = (new Fieldset)->setContents(['fields' => [
['handle' => 'from_partial', 'field' => 'the_partial.the_field'],
]]);

$return = $fieldset->ensureField('from_partial', ['type' => 'textarea', 'foo' => 'bar']);

$this->assertEquals($fieldset, $return);
$this->assertTrue($fieldset->hasField('from_partial'));

$this->assertEquals(['fields' => [
['handle' => 'from_partial', 'field' => 'the_partial.the_field', 'config' => ['foo' => 'bar']],
]], $fieldset->contents());

$this->assertEquals(['type' => 'text', 'foo' => 'bar'], $fieldset->fields()->get('from_partial')->config());
}

#[Test]
public function it_merges_undefined_config_overrides_when_ensuring_a_field_that_already_exists_inside_an_imported_fieldset()
{
FieldsetRepository::shouldReceive('find')->with('the_partial')->andReturn(
(new Fieldset)->setContents(['fields' => [
[
'handle' => 'one',
'field' => ['type' => 'text'],
],
]])
);

$fieldset = (new Fieldset)->setContents(['fields' => [
['import' => 'the_partial'],
]]);

$return = $fieldset->ensureField('one', ['type' => 'textarea', 'foo' => 'bar']);

$this->assertEquals($fieldset, $return);
$this->assertTrue($fieldset->hasField('one'));

$this->assertEquals(['fields' => [
[
'import' => 'the_partial',
'config' => [
'one' => ['foo' => 'bar'],
],
],
]], $fieldset->contents());

$this->assertEquals(['type' => 'text', 'foo' => 'bar'], $fieldset->fields()->get('one')->config());
}

#[Test]
public function it_ensures_a_field_exists_if_it_doesnt_and_prepends_it()
{
$fieldset = (new Fieldset)->setContents(['fields' => [
['handle' => 'one', 'field' => ['type' => 'text']],
['handle' => 'two', 'field' => ['type' => 'text']],
]]);

$this->assertFalse($fieldset->hasField('three'));

$return = $fieldset->ensureFieldPrepended('three', ['type' => 'textarea']); // field "three" doesnt exist, so it should get added to the start.

$this->assertEquals($fieldset, $return);
$this->assertTrue($fieldset->hasField('three'));

tap($fieldset->fields()->all(), function ($items) {
$this->assertCount(3, $items);
$this->assertEveryItemIsInstanceOf(Field::class, $items);
$this->assertEquals(['three', 'one', 'two'], $items->map->handle()->values()->all());
$this->assertEquals(['textarea', 'text', 'text'], $items->map->type()->values()->all());
});
}
}