Commit 3f2fe1a8 authored by catch's avatar catch
Browse files

fix: #3616328 Key the typed data prototype cache by the definition, not by...

fix: #3616328 Key the typed data prototype cache by the definition, not by root type and property path

By: michaellander
By: xjm
By: dries
By: fago
By: f0ns
By: d34dman
By: longwave
By: catch
(cherry picked from commit 747bda6d)
parent f8a712f4
Loading
Loading
Loading
Loading
Loading
−6
Changes for core/.phpstan-baseline.php: 0 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -14431,12 +14431,6 @@
	'count' => 1,
	'path' => __DIR__ . '/lib/Drupal/Core/TypedData/TypedDataManager.php',
];
$ignoreErrors[] = [
	'message' => '#^Storing entity storage as a class property is not recommended\\. Call Drupal\\\\Core\\\\Entity\\\\EntityTypeManagerInterface\\:\\:getStorage\\(\\) at the call\\-site instead\\.$#',
	'identifier' => 'drupal.entityStoragePropertyAssignment',
	'count' => 1,
	'path' => __DIR__ . '/lib/Drupal/Core/TypedData/TypedDataManager.php',
];
$ignoreErrors[] = [
	'message' => '#^Method Drupal\\\\Core\\\\TypedData\\\\TypedDataManagerInterface\\:\\:setValidationConstraintManager\\(\\) has no return type specified\\.$#',
	'identifier' => 'missingType.return',
+34 −41
Changes for core/lib/Drupal/Core/TypedData/TypedDataManager.php: 34 added lines, 41 removed lines.
Original line number Diff line number Diff line
@@ -5,7 +5,6 @@
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\TypedData\Attribute\DataType;
@@ -20,7 +19,6 @@
 * Manages data type plugins.
 */
class TypedDataManager extends DefaultPluginManager implements TypedDataManagerInterface {
  use DependencySerializationTrait;

  /**
   * The validator used for validating typed data.
@@ -37,11 +35,17 @@ class TypedDataManager extends DefaultPluginManager implements TypedDataManagerI
  protected $constraintManager;

  /**
   * An array of typed data property prototypes.
   * Typed data property prototypes, keyed by their data definition object.
   *
   * @var array
   * The map is created on the first lookup.
   *
   * @var \WeakMap<\Drupal\Core\TypedData\DataDefinitionInterface, \Drupal\Core\TypedData\TypedDataInterface>|null
   *
   * @todo Add the ?\WeakMap type in drupal:13.0.0. Until then the property is
   *   untyped, so that code writing an array to it gets a deprecation instead
   *   of a TypeError.
   */
  protected $prototypes = [];
  protected $prototypes = NULL;

  /**
   * Constructs a new TypedDataManager.
@@ -154,39 +158,6 @@ public function getInstance(array $options) {
   * {@inheritdoc}
   */
  public function getPropertyInstance(TypedDataInterface $object, $property_name, $value = NULL) {
    // For performance, try to reuse existing prototypes instead of
    // constructing new objects when possible. A prototype is reused when
    // creating a data object:
    // - for a similar root object (same data type and settings),
    // - at the same property path under that root object.
    $root_definition = $object->getRoot()->getDataDefinition();
    // If the root object is a list, we want to look at the data type and the
    // settings of its item definition.
    if ($root_definition instanceof ListDataDefinition) {
      $root_definition = $root_definition->getItemDefinition();
    }

    // Root data type and settings.
    $parts[] = $root_definition->getDataType();
    if ($settings = $root_definition->getSettings()) {
      // Include the settings serialized as JSON as part of the key. The JSON is
      // a shorter string than the serialized form, so array access is faster.
      $parts[] = json_encode($settings);
    }
    // Property path for the requested data object.
    $parts[] = $object->getPropertyPath();
    // Only property instances of complex data types should be cached by the
    // property name, as they represent different properties. Properties of list
    // data types are the items of the list and the property name represents
    // only the delta in that list and not an unique property, which is why all
    // items should use the same prototype.
    if ($object instanceof ComplexDataInterface) {
      $parts[] = $property_name;
    }
    $key = implode(':', $parts);

    // Create the prototype if needed.
    if (!isset($this->prototypes[$key])) {
    // Fetch the data definition for the child object from the parent.
    if ($object instanceof ComplexDataInterface) {
      $definition = $object->getDataDefinition()->getPropertyDefinition($property_name);
@@ -200,18 +171,40 @@ public function getPropertyInstance(TypedDataInterface $object, $property_name,
    if (!$definition) {
      throw new \InvalidArgumentException("Property $property_name is unknown.");
    }

    // For performance, try to reuse existing prototypes instead of
    // constructing new objects when possible. A prototype is derived from the
    // definition it was built from: create() takes the class from
    // $definition->getClass(), and the name and parent passed below are wiped
    // again by setContext(NULL, NULL). Prototypes are therefore keyed by the
    // definition object itself, so that two distinct definition objects never
    // share a prototype.
    //
    // The prototypes are held in a \WeakMap so that each one is released
    // together with the data definition it was built from, instead of growing
    // an array that is only ever emptied by clearCachedDefinitions().
    if (!$this->prototypes instanceof \WeakMap) {
      if ($this->prototypes !== NULL) {
        @trigger_error('Setting \\Drupal\\Core\\TypedData\\TypedDataManager::$prototypes to anything other than a \\WeakMap or NULL is deprecated in drupal:11.6.0 and is removed from drupal:13.0.0. See https://www.drupal.org/node/3638699', E_USER_DEPRECATED);
      }
      $this->prototypes = new \WeakMap();
    }
    $prototype = $this->prototypes[$definition] ?? NULL;

    // Create the prototype if needed.
    if ($prototype === NULL) {
      // Create the prototype without any value, but with initial parenting
      // so that constructors can set up the objects correctly.
      $prototype = $this->create($definition, NULL, $property_name, $object);
      // Unset the parent so that it is not statically cached within the
      // prototype. It will be set again later anyway.
      $prototype->setContext(NULL, NULL);
      $this->prototypes[$key] = $prototype;
      $this->prototypes[$definition] = $prototype;
    }

    // Clone the prototype, update its parenting information, and assign the
    // value.
    $property = clone $this->prototypes[$key];
    $property = clone $prototype;
    $property->setContext($property_name, $object);
    if (isset($value)) {
      $property->setValue($value, FALSE);
@@ -288,7 +281,7 @@ public function getDefaultConstraints(DataDefinitionInterface $definition) {
   */
  public function clearCachedDefinitions() {
    parent::clearCachedDefinitions();
    $this->prototypes = [];
    $this->prototypes = new \WeakMap();
  }

  /**
+5 −4
Changes for core/lib/Drupal/Core/TypedData/TypedDataManagerInterface.php: 5 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -134,13 +134,14 @@ public function getInstance(array $options);
   * Get a typed data instance for a property of a given typed data object.
   *
   * This method will use prototyping for fast and efficient instantiation of
   * many property objects with the same property path; for example,
   * many property objects sharing the same data definition; for example,
   * when multiple comments are used comment_body.0.value needs to be
   * instantiated very often.
   *
   * Prototyping is done by the root object's data type and the given
   * property path, i.e. all property instances having the same property path
   * and inheriting from the same data type are prototyped.
   * Prototyping is done per data definition object, i.e. all property
   * instances created from the same property or item data definition object
   * share a prototype. Two distinct definition objects never share one, even
   * when they declare the same property name under the same root.
   *
   * @param \Drupal\Core\TypedData\TypedDataInterface $object
   *   The parent typed data object, implementing the TypedDataInterface and
+1 −1
Changes for core/modules/migrate/src/Plugin/migrate/destination/EntityFieldInstance.php: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -41,7 +41,7 @@
 * @endcode
 *
 * @see \Drupal\field\Entity\FieldConfig
 * @see \Drupal\field\Entity\FieldConfigBase
 * @see \Drupal\Core\Field\FieldConfigBase
 */
#[MigrateDestination('entity:field_config')]
class EntityFieldInstance extends EntityConfigBase {
+167
Changes for core/tests/Drupal/KernelTests/Core/TypedData/TypedDataManagerPrototypeCacheEntityTest.php: 167 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\KernelTests\Core\TypedData;

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests the typed data prototype cache on the entity field path.
 *
 * Entity field access is the path prototyping exists for. Field and item
 * definition objects are built once per bundle, so prototypes must still be
 * shared across entities and across the deltas of one field. A field definition
 * that is deliberately rebuilt must not keep the prototype that was cached for
 * its previous state.
 *
 * @see \Drupal\Core\TypedData\TypedDataManager::getPropertyInstance()
 * @see \Drupal\KernelTests\Core\TypedData\TypedDataManagerPrototypeCacheTest
 */
#[Group('TypedData')]
#[RunTestsInSeparateProcesses]
class TypedDataManagerPrototypeCacheEntityTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['system', 'user', 'field', 'node', 'text', 'filter'];

  /**
   * The typed data manager.
   *
   * @var \Drupal\Core\TypedData\TypedDataManagerInterface
   */
  protected $typedDataManager;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $this->typedDataManager = $this->container->get('typed_data_manager');

    $this->installEntitySchema('user');
    $this->installEntitySchema('node');
    $this->installConfig(['filter', 'node']);
    NodeType::create(['type' => 'article', 'name' => 'Article'])->save();

    FieldStorageConfig::create([
      'field_name' => 'field_multi',
      'entity_type' => 'node',
      'type' => 'string',
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
    ])->save();
    FieldConfig::create([
      'field_name' => 'field_multi',
      'entity_type' => 'node',
      'bundle' => 'article',
    ])->save();
  }

  /**
   * Returns the number of cached typed data prototypes.
   *
   * @return int
   *   The number of prototypes currently held by the typed data manager.
   */
  protected function protoCount(): int {
    $ref = new \ReflectionProperty($this->typedDataManager, 'prototypes');
    $value = $ref->getValue($this->typedDataManager);
    return $value === NULL ? 0 : count($value);
  }

  /**
   * Tests further entities and further deltas do not add prototypes.
   *
   * All deltas of a field resolve to the same item definition object, so
   * touching many of them must rely on a single prototype.
   */
  public function testEntityFieldAccessReusesPrototypes(): void {
    // Warm the cache on one node with a single delta.
    $node = Node::create([
      'type' => 'article',
      'title' => 'First',
      'uid' => 0,
      'field_multi' => ['one'],
    ]);
    $node->get('title')->get(0)->get('value')->getValue();
    $node->get('uid')->get(0)->get('target_id')->getValue();
    $node->get('field_multi')->get(0)->get('value')->getValue();
    $warm = $this->protoCount();
    $this->assertGreaterThan(0, $warm);

    // A node with twenty deltas must not add a prototype per delta.
    $many = Node::create([
      'type' => 'article',
      'title' => 'Many',
      'uid' => 0,
      'field_multi' => array_fill(0, 20, 'value'),
    ]);
    $this->assertCount(20, $many->get('field_multi'));
    foreach ($many->get('field_multi') as $item) {
      $item->get('value')->getValue();
    }
    $this->assertSame($warm, $this->protoCount(), 'Further deltas of the same field reuse the item prototype.');

    // Five more nodes must not add any prototypes either.
    for ($i = 0; $i < 5; $i++) {
      $other = Node::create([
        'type' => 'article',
        'title' => 'Node ' . $i,
        'uid' => 0,
        'field_multi' => ['one'],
      ]);
      $other->get('title')->get(0)->get('value')->getValue();
      $other->get('uid')->get(0)->get('target_id')->getValue();
      $other->get('field_multi')->get(0)->get('value')->getValue();
    }
    $this->assertSame($warm, $this->protoCount(), 'Further entities of the same bundle reuse the existing prototypes.');
  }

  /**
   * Tests a rebuilt field item definition is not served a stale prototype.
   *
   * FieldConfigBase::addPropertyConstraints() resets the item definition so
   * that the next instantiation picks up the new constraints.
   *
   * @see \Drupal\Core\Field\FieldConfigBase::addPropertyConstraints()
   */
  public function testFieldPropertyConstraintsAreNotStale(): void {
    $field_definitions = $this->container->get('entity_field.manager')->getFieldDefinitions('node', 'article');
    $field_definition = $field_definitions['field_multi'];
    $this->assertInstanceOf(FieldConfig::class, $field_definition);

    // Warm the prototype cache with the unconstrained item definition.
    $node = Node::create([
      'type' => 'article',
      'title' => 'First',
      'uid' => 0,
      'field_multi' => ['this is way too long'],
    ]);
    $this->assertCount(0, $node->get('field_multi')->get(0)->validate());

    // Adding a property constraint resets the item definition.
    $field_definition->addPropertyConstraints('value', ['Length' => ['max' => 3]]);

    // The next item must be built from the new definition, constraints
    // included.
    $constrained = Node::create([
      'type' => 'article',
      'title' => 'Second',
      'uid' => 0,
      'field_multi' => ['this is way too long'],
    ]);
    $violations = $constrained->get('field_multi')->get(0)->validate();
    $this->assertCount(1, $violations, 'The added property constraint is enforced instead of the prototype cached before the definition was reset.');
    $this->assertSame('value', $violations->get(0)->getPropertyPath());
  }

}
Loading