cms icon indicating copy to clipboard operation
cms copied to clipboard

[5.x] Ensure unique blueprint instance

Open aerni opened this issue 1 year ago • 1 comments

This PR allows to programmatically add fields to an entry's blueprint without also altering the fields of other entries that use the same blueprint.

I've come across this issue on a multisite, where I need to extend the blueprint for only one localization. Consider this simplified event listener:

<?php

namespace App\Listeners;

use Statamic\Events\EntryBlueprintFound;

class ExtendEntryBlueprint
{
    public function handle(EntryBlueprintFound $event): void
    {
        if ($event->entry?->locale() !== 'german') {
            return;
        }

        $event->blueprint->ensureField('description', [
            'type' => 'text',
            'display' => 'Description',
        ]);

        ray($event->blueprint);
    }
}

While the listener would only add the description field when it encounters a German entry, the fields would still be added to other entries that share the same blueprint because we are dealing with the same blueprint instance.

A simple way to reproduce this issue on a fresh installation:

  1. Create a multisite and add german as the second site
  2. Add the german site to the pages collection
  3. Localize the Home page

The EntryBlueprintFound event is triggered for the german localization and its origin. Without this PR, the origin also ends up with the ensured description field.

aerni avatar Jun 21 '24 15:06 aerni

There are quite a few more tests failing because they all use assertSame and thus assert that the object instance is the same. So this PR might result in a minor breaking change and unexpected behavior for users that relied on it to work the way it works now. Though, I don't think it should cause any issues.

Please let me know what you think, and I'll fix the tests if you're up for merging this PR.

aerni avatar Jun 21 '24 16:06 aerni

Sorry for the delay. If this is still important to you feel free to fix the tests and reopen.

jasonvarga avatar Dec 05 '24 20:12 jasonvarga