getSections example

/** * Update timestamp formatter settings for Layout Builder fields. */
function layout_builder_post_update_timestamp_formatter(array &$sandbox = NULL): void {
  /** @var \Drupal\Core\Field\FormatterPluginManager $field_formatter_manager */
  $field_formatter_manager = \Drupal::service('plugin.manager.field.formatter');

  \Drupal::classResolver(ConfigEntityUpdater::class)->update($sandbox, 'entity_view_display', function DEntityViewDisplayInterface $entity_view_display) use ($field_formatter_manager): bool {
    $update = FALSE;
    if ($entity_view_display instanceof LayoutEntityDisplayInterface && $entity_view_display->isLayoutBuilderEnabled()) {
      foreach ($entity_view_display->getSections() as $section) {
        foreach ($section->getComponents() as $component) {
          if (str_starts_with($component->getPluginId(), 'field_block:')) {
            $configuration = $component->get('configuration');
            $formatter =& $configuration['formatter'];
            if ($formatter && isset($formatter['type'])) {
              $plugin_definition = $field_formatter_manager->getDefinition($formatter['type'], FALSE);
              // Check also potential plugins extending TimestampFormatter.               if ($plugin_definition && is_a($plugin_definition['class'], TimestampFormatter::class, TRUE)) {
                if (!isset($formatter['settings']['tooltip']) || !isset($formatter['settings']['time_diff'])) {
                  $update = TRUE;
                  // No need to check the rest of components.

  public function equals(FieldItemListInterface $list_to_compare) {
    if (!$list_to_compare instanceof LayoutSectionItemList) {
      return FALSE;
    }

    // Convert arrays of section objects to array values for comparison.     $convert = function DLayoutSectionItemList $list) {
      return array_map(function DSection $section) {
        return $section->toArray();
      }$list->getSections());
    };
    return $convert($this) === $convert($list_to_compare);
  }

  /** * Overrides \Drupal\Core\Field\FieldItemListInterface::defaultAccess(). * * @ingroup layout_builder_access */
  public function defaultAccess($operation = 'view', AccountInterface $account = NULL) {
    // @todo Allow access in https://www.drupal.org/node/2942975.
throw new \InvalidArgumentException('MoveBlockForm requires all parameters.');
      }
    }

    $this->sectionStorage = $section_storage;
    $this->delta = $delta;
    $this->uuid = $uuid;
    $this->region = $region;

    $form['#attributes']['data-layout-builder-target-highlight-id'] = $this->blockUpdateHighlightId($uuid);

    $sections = $section_storage->getSections();
    $contexts = $this->getPopulatedContexts($section_storage);
    $region_options = [];
    foreach ($sections as $section_delta => $section) {
      $layout = $section->getLayout($contexts);
      $layout_definition = $layout->getPluginDefinition();
      if (!($section_label = $section->getLayoutSettings()['label'])) {
        $section_label = $this->t('Section: @delta', ['@delta' => $section_delta + 1])->render();
      }
      foreach ($layout_definition->getRegions() as $region_name => $region_info) {
        // Group regions by section.         $region_options[$section_label]["$section_delta:$region_name"] = $this->t(
          
public function testStopwatch()
    {
        $sw = new Stopwatch(true);
        $sut = new TraceableHttpClient(new NativeHttpClient()$sw);
        $response = $sut->request('GET', 'http://localhost:8057');

        $response->getStatusCode();
        $response->getHeaders();
        $response->getContent();

        $this->assertArrayHasKey('__root__', $sections = $sw->getSections());
        $this->assertCount(1, $events = $sections['__root__']->getEvents());
        $this->assertArrayHasKey('GET http://localhost:8057', $events);
        $this->assertCount(3, $events['GET http://localhost:8057']->getPeriods());
        $this->assertGreaterThan(0.0, $events['GET http://localhost:8057']->getDuration());
    }

    public function testStopwatchError()
    {
        $sw = new Stopwatch(true);
        $sut = new TraceableHttpClient(new NativeHttpClient()$sw);
        $response = $sut->request('GET', 'http://localhost:8057/404');

        
return $this->homeSalesChannels;
    }

    public function setHomeSalesChannels(CmsPageCollection $homeSalesChannels): void
    {
        $this->homeSalesChannels = $homeSalesChannels;
    }

    public function getElementsOfType(string $type): array
    {
        $elements = [];
        if ($this->getSections() === null) {
            return $elements;
        }

        foreach ($this->getSections()->getBlocks() as $block) {
            if ($block->getSlots() === null) {
                continue;
            }

            foreach ($block->getSlots() as $slot) {
                if ($slot->getType() === $type) {
                    $elements[] = $slot;
                }
/** * {@inheritdoc} */
  public function extractFormValues(FieldItemListInterface $items, array $form, FormStateInterface $form_state) {
    // @todo This isn't resilient to being set twice, during validation and     // save https://www.drupal.org/project/drupal/issues/2833682.     if (!$form_state->isValidationComplete()) {
      return;
    }

    $items->setValue($this->getSectionStorage($form_state)->getSections());
  }

  /** * Gets the section storage. * * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. * * @return \Drupal\layout_builder\SectionStorageInterface * The section storage loaded from the tempstore. */
  
$request = new Request([][]['productId' => $product->getId()]);

        /** @var ProductPageLoadedEvent $event */
        $event = null;
        $this->catchEvent(ProductPageLoadedEvent::class$event);

        $page = $this->getPageLoader()->load($request$context);
        $cmsPage = $page->getCmsPage();
        $fieldConfigCollection = new FieldConfigCollection([new FieldConfig('content', 'static', 'overwrittenByProduct')]);

        static::assertNotNull($cmsPage);
        static::assertIsIterable($cmsPage->getSections());
        static::assertNotNull($cmsPage->getSections()->first());
        static::assertIsIterable($cmsPage->getSections()->first()->getBlocks());

        $blocks = $cmsPage->getSections()->first()->getBlocks();
        static::assertInstanceOf(CmsBlockCollection::class$blocks);
        static::assertIsIterable($blocks->getSlots());
        static::assertNotNull($blocks->getSlots()->get($firstSlotId));
        static::assertNotNull($blocks->getSlots()->get($secondSlotId));

        static::assertEquals(
            $productCmsPageData['slotConfig'][$firstSlotId],
            

  public function testGetEntitySections() {
    $entity = EntityTest::create(['name' => 'updated']);
    $section_storage_manager = $this->prophesize(SectionStorageManagerInterface::class);
    $section_storage_manager->load('')->willReturn(NULL);
    $section_storage = $this->prophesize(SectionStorageInterface::class);
    $sections = [
      new Section('layout_onecol'),
    ];
    $this->assertCount(1, $sections);
    $section_storage->getSections()->willReturn($sections);
    $section_storage->count()->willReturn(1);

    $section_storage_manager->findByContext(Argument::cetera())->willReturn($section_storage->reveal());
    $this->container->set('plugin.manager.layout_builder.section_storage', $section_storage_manager->reveal());
    $class = new TestLayoutEntityHelperTrait();
    // Ensure that if the entity has a section storage the sections will be     // returned.     $this->assertSame($sections$class->getEntitySections($entity));

    $section_storage_manager->findByContext(Argument::cetera())->willReturn(NULL);
    $this->container->set('plugin.manager.layout_builder.section_storage', $section_storage_manager->reveal());
    
/** * Gets the sections for an entity if any. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity. * * @return \Drupal\layout_builder\Section[] * The entity layout sections if available. */
  protected function getEntitySections(EntityInterface $entity) {
    $section_storage = $this->getSectionStorageForEntity($entity);
    return $section_storage ? $section_storage->getSections() : [];
  }

  /** * Gets components that have Inline Block plugins. * * @param \Drupal\layout_builder\Section[] $sections * The layout sections. * * @return \Drupal\layout_builder\SectionComponent[] * The components that contain Inline Block plugins. */
  
// ensure sections, blocks and slots are loaded, slots and blocks can be restricted by caller         $criteria->addAssociation('sections.backgroundMedia');
        $criteria->addAssociation('sections.blocks.backgroundMedia');
        $criteria->addAssociation('sections.blocks.slots');

        // step 1, load cms pages with blocks and slots         $result = $this->cmsPageRepository->search($criteria$context->getContext());
        $pages = $result->getEntities();

        foreach ($pages as $page) {
            if ($page->getSections() === null) {
                continue;
            }

            $page->getSections()->sort(fn (CmsSectionEntity $a, CmsSectionEntity $b) => $a->getPosition() <=> $b->getPosition());

            if (!$resolverContext) {
                $resolverContext = new ResolverContext($context$request);
            }

            // step 2, sort blocks into sectionPositions             foreach ($page->getSections() as $section) {
                
abstract protected function setSections(array $sections);

  /** * {@inheritdoc} */
  #[\ReturnTypeWillChange]   public function count() {
    if ($this->hasBlankSection()) {
      return 0;
    }

    return count($this->getSections());
  }

  /** * {@inheritdoc} */
  public function getSection($delta) {
    if (!$this->hasSection($delta)) {
      throw new \OutOfBoundsException(sprintf('Invalid delta "%s"', $delta));
    }

    return $this->getSections()[$delta];
  }

        $productId = Uuid::randomHex();
        $request = new Request([][]['productId' => $productId]);
        $salesChannelContext = $this->getSalesChannelContext();
        $reviews = $this->getCmsSlotConfig();

        $productPageLoader = $this->getProductPageLoaderWithProduct($productId$reviews$request$salesChannelContext);

        $page = $productPageLoader->load($request$salesChannelContext);

        /** @phpstan-ignore-next-line $slot */
        $slot = $page->getCmsPage()->getSections()->first()->getBlocks()->first()->getSlots()->first()->getSlot();

        static::assertEquals($reviewsjson_decode((string) $slot, true, 512, \JSON_THROW_ON_ERROR));
    }

    /** * @param array<string, array<string, array<string, array<string, array<string, string>>>>> $reviews */
    private function getProductPageLoaderWithProduct(string $productId, array $reviews, Request $request, SalesChannelContext $salesChannelContext): ProductPageLoader
    {
        $product = $this->getProductWithReviews($productId$reviews);

        
public function onPrepareLayout(PrepareLayoutEvent $event) {
    $section_storage = $event->getSectionStorage();

    // If the layout has pending changes, add a warning.     if ($this->layoutTempstoreRepository->has($section_storage)) {
      $this->messenger->addWarning($this->t('You have unsaved changes.'));
    }
    else {
      // If the layout is an override that has not yet been overridden, copy the       // sections from the corresponding default.       if ($section_storage instanceof OverridesSectionStorageInterface && !$section_storage->isOverridden()) {
        $sections = $section_storage->getDefaultSectionStorage()->getSections();
        foreach ($sections as $section) {
          $section_storage->appendSection($section);
        }
      }
      // Add storage to tempstore regardless of what the storage is.       $this->layoutTempstoreRepository->set($section_storage);
    }
  }

}
// @todo Remove in https://www.drupal.org/project/drupal/issues/3018782.     $label = new TranslatableMarkup('@entity being viewed', [
      '@entity' => $entity->getEntityType()->getSingularLabel(),
    ]);
    $contexts['layout_builder.entity'] = EntityContext::fromEntity($entity$label);

    $cacheability = new CacheableMetadata();
    $storage = $this->sectionStorageManager()->findByContext($contexts$cacheability);

    $build = [];
    if ($storage) {
      foreach ($storage->getSections() as $delta => $section) {
        $build[$delta] = $section->toRenderArray($contexts);
      }
    }
    // The render array is built based on decisions made by @SectionStorage     // plugins and therefore it needs to depend on the accumulated     // cacheability of those decisions.     $cacheability->applyTo($build);
    return $build;
  }

  /** * Gets the available contexts for a given entity. * * @param \Drupal\Core\Entity\FieldableEntityInterface $entity * The entity. * * @return \Drupal\Core\Plugin\Context\ContextInterface[] * An array of context objects for a given entity. */
$new_section_storage->getSection(0)->setLayoutSettings(['asdf' => 'qwer']);
    $this->assertSame(['setting_1' => 'Default']$this->sectionList->getSection(0)->getLayoutSettings());
  }

  /** * Asserts that the field list has the expected sections. * * @param \Drupal\layout_builder\Section[] $expected * The expected sections. */
  protected function assertSections(array $expected) {
    $result = $this->sectionList->getSections();
    $this->assertEquals($expected$result);
    $this->assertSame(array_keys($expected)array_keys($result));
  }

}
Home | Imprint | This part of the site doesn't use cookies.