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
9 changes: 7 additions & 2 deletions src/Fields/Fields.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,15 @@ public function only(...$keys): self

public function newInstance()
{
return (new static)
// Assign the items directly — setItems() would re-resolve every field, then
// setFields() would immediately discard that work. Clone so the two instances
// don't share one collection, which is what setItems() would have given us.
$instance = new static;
$instance->items = clone $this->items;

return $instance
->setParent($this->parent)
->setParentField($this->parentField, $this->parentIndex)
->setItems($this->items)
->setFields($this->fields)
->setFilled($this->filled);
}
Expand Down
9 changes: 7 additions & 2 deletions src/Fieldtypes/Entries.php
Original file line number Diff line number Diff line change
Expand Up @@ -379,18 +379,23 @@ protected function getCreatables()

protected function authorizeItemData($id): bool
{
return $this->authorizeViewable(Entry::find($id));
return $this->authorizeViewable($this->findEntry($id));
}

protected function toItemArray($id)
{
if (! $entry = Entry::find($id)) {
if (! $entry = $this->findEntry($id)) {
return $this->invalidItemArray($id);
}

return (new EntryResource($entry, $this))->resolve()['data'];
}

protected function findEntry($id)
{
return $this->itemCache[$id] ??= Entry::find($id);
}

protected function collect($value)
{
return new \Statamic\Entries\EntryCollection($value);
Expand Down
8 changes: 8 additions & 0 deletions src/Fieldtypes/Relationship.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ abstract class Relationship extends Fieldtype
'_' => '_', // forces an object in js
];
protected $formStackSize;
protected array $itemCache = [];

public function __clone()
{
// The fieldtype repository hands out clones of a single instance per handle,
// so without this the cache would be inherited by unrelated fields.
$this->itemCache = [];
}

protected function configFieldItems(): array
{
Expand Down
28 changes: 19 additions & 9 deletions src/Fieldtypes/Terms.php
Original file line number Diff line number Diff line change
Expand Up @@ -418,20 +418,14 @@ protected function getCreatables()

protected function authorizeItemData($id): bool
{
if ($this->usingSingleTaxonomy() && ! Str::contains($id, '::')) {
$id = "{$this->taxonomies()[0]}::{$id}";
}

return $this->authorizeViewable(Term::find($id));
return $this->authorizeViewable($this->findTerm($id));
}

protected function toItemArray($id)
{
if ($this->usingSingleTaxonomy() && ! Str::contains($id, '::')) {
$id = "{$this->taxonomies()[0]}::{$id}";
}
$id = $this->normalizeTermId($id);

if (! $term = Term::find($id)) {
if (! $term = $this->findTerm($id)) {
return $this->invalidItemArray($id);
}

Expand All @@ -457,6 +451,22 @@ protected function toItemArray($id)
];
}

protected function normalizeTermId($id): string
{
if ($this->usingSingleTaxonomy() && ! Str::contains($id, '::')) {
return "{$this->taxonomies()[0]}::{$id}";
}

return $id;
}

protected function findTerm($id)
{
$id = $this->normalizeTermId($id);

return $this->itemCache[$id] ??= Term::find($id);
}

protected function getColumns()
{
$columns = [Column::make('title')];
Expand Down
9 changes: 7 additions & 2 deletions src/Fieldtypes/Users.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,12 @@ public function preProcess($data)

protected function authorizeItemData($id): bool
{
return $this->authorizeViewable(User::find($id));
return $this->authorizeViewable($this->findUser($id));
}

protected function toItemArray($id, $site = null)
{
if ($user = User::find($id)) {
if ($user = $this->findUser($id)) {
$canViewUsers = $this->canViewUser($user);

return [
Expand All @@ -123,6 +123,11 @@ protected function toItemArray($id, $site = null)
return $this->invalidItemArray($id);
}

protected function findUser($id)
{
return $this->itemCache[$id] ??= User::find($id);
}

public function getIndexItems($request)
{
// Don't reveal existence to a user who can't view the listing; return an empty
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,15 @@ private function getConfig($request)

// The json may include unicode characters, so we'll try to convert it to UTF-8.
// See https://github.com/statamic/cms/issues/566
$utf8 = mb_convert_encoding($json, 'UTF-8', mb_list_encodings());

// In PHP 8.1 there's a bug where encoding will return null. It's fixed in 8.1.2.
// In this case, we'll fall back to the original JSON, but without the encoding.
// Issue #566 may still occur, but it's better than failing completely.
$json = empty($utf8) ? $json : $utf8;
// Fast path: skip encoding detection when already valid UTF-8.
if (! mb_check_encoding($json, 'UTF-8')) {
$utf8 = mb_convert_encoding($json, 'UTF-8', mb_list_encodings());

// In PHP 8.1 there's a bug where encoding will return null. It's fixed in 8.1.2.
// In this case, we'll fall back to the original JSON, but without the encoding.
// Issue #566 may still occur, but it's better than failing completely.
$json = empty($utf8) ? $json : $utf8;
}

return json_decode($json, true);
}
Expand Down
57 changes: 57 additions & 0 deletions tests/Fields/FieldsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,63 @@ public function it_gets_only_specific_fields()
$this->assertEquals(['one', 'two'], $fields->only(['one', 'two'])->all()->keys()->all());
}

#[Test]
public function it_carries_items_over_to_a_new_instance_without_resolving_them_again()
{
$items = [
['handle' => 'one', 'field' => ['display' => 'First']],
['handle' => 'two', 'field' => ['display' => 'Second']],
];

$fields = new Fields($items);
$instance = $fields->newInstance();

$this->assertNotSame($fields, $instance);
$this->assertEquals($items, $instance->items()->all());

// The already resolved fields get carried over as-is, rather than being
// resolved a second time only for setFields() to throw them away.
$this->assertSame($fields->get('one'), $instance->get('one'));
$this->assertSame($fields->get('two'), $instance->get('two'));
}

#[Test]
public function replacing_the_items_on_a_new_instance_doesnt_affect_the_original()
{
$fields = new Fields([
['handle' => 'one', 'field' => ['display' => 'First']],
]);

$instance = $fields->newInstance();

$instance->setItems([
['handle' => 'two', 'field' => ['display' => 'Second']],
]);

$this->assertEquals(['one'], $fields->items()->pluck('handle')->all());
$this->assertEquals(['two'], $instance->items()->pluck('handle')->all());
$this->assertTrue($fields->has('one'));
$this->assertFalse($fields->has('two'));
}

#[Test]
public function mutating_the_items_on_a_new_instance_doesnt_affect_the_original()
{
$fields = new Fields([
['handle' => 'one', 'field' => ['display' => 'First']],
]);

$instance = $fields->newInstance();

$this->assertNotSame($fields->items(), $instance->items());

$instance->items()->push(['handle' => 'two', 'field' => ['display' => 'Second']]);
$instance->items()->put(0, ['handle' => 'clobbered', 'field' => ['display' => 'Clobbered']]);

$this->assertEquals(['one'], $fields->items()->pluck('handle')->all());
$this->assertEquals(['clobbered', 'two'], $instance->items()->pluck('handle')->all());
}

#[Test]
public function converts_to_array_suitable_for_rendering_fields_in_publish_component()
{
Expand Down
18 changes: 18 additions & 0 deletions tests/Fieldtypes/EntriesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,24 @@ public function it_doesnt_localize_when_select_across_sites_setting_is_enabled()
$this->assertEquals(['one', 'two', 'three', 'four'], $augmented->get()->map->slug()->all());
}

#[Test]
public function it_doesnt_inherit_the_item_cache_from_another_fieldtype_instance()
{
$this->actingAs(Facades\User::make()->makeSuper());

$field = new Field('test', ['type' => 'entries', 'collections' => ['blog']]);

// The fieldtype repository hands out clones of a single instance per handle,
// so one field's lookups must not leak into another's.
$first = $field->fieldtype();
$this->assertFalse($first->getItemData(['123'])->first()['invalid'] ?? false);

Facades\Entry::find('123')->delete();

$second = $field->fieldtype();
$this->assertTrue($second->getItemData(['123'])->first()['invalid']);
}

public function fieldtype($config = [], $parent = null)
{
$field = new Field('test', array_merge([
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace Tests\Http\Controllers\CP\Fieldtypes;

use Facades\Tests\Factories\EntryFactory;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Facades;
use Statamic\Fieldtypes\Relationship;
use Tests\PreventSavingStacheItemsToDisk;
use Tests\TestCase;

class RelationshipFieldtypeControllerTest extends TestCase
{
use PreventSavingStacheItemsToDisk;

public function setUp(): void
{
parent::setUp();

Facades\Collection::make('blog')->save();
EntryFactory::id('123')->collection('blog')->slug('one')->data(['title' => 'One'])->create();
}

private function request($config, $selections = ['123'])
{
return $this
->actingAs(Facades\User::make()->makeSuper())
->post(cp_route('relationship.data'), [
// JSON.stringify() in the browser leaves multibyte characters as-is,
// so don't let PHP escape them to \uXXXX sequences here.
'config' => base64_encode(json_encode($config, JSON_UNESCAPED_UNICODE)),
'selections' => $selections,
]);
}

#[Test]
public function it_gets_item_data_for_the_configured_fieldtype()
{
$this->request(['type' => 'entries', 'collections' => ['blog']])
->assertOk()
->assertJsonPath('data.0.title', 'One');
}

#[Test]
public function it_doesnt_mangle_multibyte_characters_in_the_config()
{
// The base64-encoded JSON config used to be run through mb_convert_encoding()
// with a detection list, which could misdetect perfectly valid UTF-8 as another
// encoding and corrupt it. Emoji were mangled into Cyrillic. See #566.
(new class extends Relationship
{
public static function handle()
{
return 'config_echo';
}

protected function toItemArray($id)
{
return ['id' => $id, 'title' => $this->config('display')];
}

public function getIndexItems($request)
{
return collect();
}
})::register();

$display = '😀👍';

$this->request(['type' => 'config_echo', 'display' => $display])
->assertOk()
->assertJsonPath('data.0.title', $display);
}
}
Loading