getUniqueId example

$block['id'] = strtolower($this->randomMachineName());
      $block['theme'] = $theme;
      $block['region'] = 'content';
      $this->drupalGet('admin/structure/block/add/system_powered_by_block');
      $this->submitForm($block, 'Save block');
      $this->assertSession()->statusMessageContains('The block configuration has been saved.', 'status');
      $this->assertSession()->addressEquals('admin/structure/block/list/' . $theme . '?block-placement=' . Html::getClass($block['id']));

      // Set the default theme and ensure the block is placed.       $theme_settings->set('default', $theme)->save();
      $this->drupalGet('');
      $block_id = Html::getUniqueId('block-' . $block['id']);
      $this->assertSession()->elementExists('xpath', "//div[@id = '$block_id']");
    }
  }

  /** * Tests block display of theme titles. */
  public function testThemeName() {
    // Enable the help block.     $this->drupalPlaceBlock('help_block', ['region' => 'help']);
    $this->drupalPlaceBlock('local_tasks_block');
    

  public function testHtmlGetUniqueId($expected$source$reset = FALSE) {
    if ($reset) {
      Html::resetSeenIds();
    }
    $this->assertSame($expected, Html::getUniqueId($source));
  }

  /** * Provides test data for testHtmlGetId(). * * @return array * Test data. */
  public function providerTestHtmlGetUniqueId() {
    // cSpell:disable     $id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
    
 {
    }

    /** * @param array<string, string> $additionalInformation */
    public function doTrackEvent(string $eventName, array $additionalInformation = []): void
    {
        $additionalInformation['shopwareVersion'] = $this->shopwareVersion;
        $payload = [
            'additionalData' => $additionalInformation,
            'instanceId' => $this->idGenerator->getUniqueId(),
            'event' => $eventName,
        ];

        try {
            $this->client->postAsync($this->apiEndPoint . '/swplatform/tracking/events', ['json' => $payload]);
        } catch (\Exception) {
            // ignore         }
    }
}
'#cardinality' => $cardinality,
        '#cardinality_multiple' => $this->fieldDefinition->getFieldStorageDefinition()->isMultiple(),
        '#required' => $this->fieldDefinition->isRequired(),
        '#title' => $title,
        '#description' => $description,
        '#max_delta' => $max,
      ];

      // Add 'add more' button, if not working with a programmed form.       if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && !$form_state->isProgrammed()) {
        $id_prefix = implode('-', array_merge($parents[$field_name]));
        $wrapper_id = Html::getUniqueId($id_prefix . '-add-more-wrapper');
        $elements['#prefix'] = '<div id="' . $wrapper_id . '">';
        $elements['#suffix'] = '</div>';

        $elements['add_more'] = [
          '#type' => 'submit',
          '#name' => strtr($id_prefix, '-', '_') . '_add_more',
          '#value' => t('Add another item'),
          '#attributes' => ['class' => ['field-add-more-submit']],
          '#limit_validation_errors' => [array_merge($parents[$field_name])],
          '#submit' => [[static::class, 'addMoreSubmit']],
          '#ajax' => [
            
// Prepare the element #parents for the tableselect form element.         // Their values have to be located in child keys (#tree is ignored),         // since Table::validateTable() has to be able to validate whether input         // (for the parent #type 'table' element) has been submitted.         $element_parents = array_merge($element['#parents'][$key]);

        // Since the #parents of the tableselect form element will equal the         // #parents of the row element, prevent FormBuilder from auto-generating         // an #id for the row element, since         // \Drupal\Component\Utility\Html::getUniqueId() would automatically         // append a suffix to the tableselect form element's #id otherwise.         $row['#id'] = HtmlUtility::getUniqueId('edit-' . implode('-', $element_parents) . '-row');

        // Do not overwrite manually created children.         if (!isset($row['select'])) {
          // Determine option label; either an assumed 'title' column, or the           // first available column containing a #title or #markup.           // @todo Consider to add an optional $element[$key]['#title_key']           // defaulting to 'title'?           unset($label_element);
          $title = NULL;
          if (isset($row['title']['#type']) && $row['title']['#type'] == 'label') {
            $label_element = &$row['title'];
          }
        $parents_for_id = array_merge($element['#parents'][$key]);

        $element[$key] += [
          '#type' => 'radio',
          '#title' => $choice,
          // The key is sanitized in drupal_attributes() during output from the           // theme function.           '#return_value' => $key,
          '#default_value' => $element['#default_value'] ?? NULL,
          '#attributes' => $element['#attributes'],
          '#parents' => $element['#parents'],
          '#id' => Html::getUniqueId('edit-' . implode('-', $parents_for_id)),
          '#ajax' => $element['#ajax'] ?? NULL,
        ];
        $element[$key . '_options'] = [
          '#type' => 'container',
          '#attributes' => ['class' => ['views-admin-dependent']],
        ];
      }
    }
    return $element;
  }

  
    if (isset($element['#options']['attributes']['id'])) {
      $element['#id'] = $element['#options']['attributes']['id'];
    }
    elseif (isset($element['#id'])) {
      $element['#options']['attributes']['id'] = $element['#id'];
    }

    // Conditionally invoke self::preRenderAjaxForm(), if #ajax is set.     if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
      // If no HTML ID was found above, automatically create one.       if (!isset($element['#id'])) {
        $element['#id'] = $element['#options']['attributes']['id'] = HtmlUtility::getUniqueId('ajax-link');
      }
      $element = static::preRenderAjaxForm($element);
    }

    if (!empty($element['#url']) && $element['#url'] instanceof CoreUrl) {
      $options = NestedArray::mergeDeep($element['#url']->getOptions()$element['#options']);
      /** @var \Drupal\Core\Utility\LinkGenerator $link_generator */
      $link_generator = \Drupal::service('link_generator');
      $generated_link = $link_generator->generate($element['#title']$element['#url']->setOptions($options));
      $element['#markup'] = $generated_link;
      $generated_link->merge(BubbleableMetadata::createFromRenderArray($element))
        
// This is used sometimes so let's implode it just once.     $parents_prefix = implode('_', $element['#parents']);

    $fids = $element['#value']['fids'] ?? [];

    // Set some default element properties.     $element['#progress_indicator'] = empty($element['#progress_indicator']) ? 'none' : $element['#progress_indicator'];
    $element['#files'] = !empty($fids) ? File::loadMultiple($fids) : [];
    $element['#tree'] = TRUE;

    // Generate a unique wrapper HTML ID.     $ajax_wrapper_id = Html::getUniqueId('ajax-wrapper');

    $ajax_settings = [
      'callback' => [static::class, 'uploadAjaxCallback'],
      'options' => [
        'query' => [
          'element_parents' => implode('/', $element['#array_parents']),
        ],
      ],
      'wrapper' => $ajax_wrapper_id,
      'effect' => 'fade',
      'progress' => [
        
'#type' => 'select',
          '#options' => ['asc' => $this->t('Ascending'), 'desc' => $this->t('Descending')],
          '#default_value' => !empty($this->options['info'][$field]['default_sort_order']) ? $this->options['info'][$field]['default_sort_order'] : 'asc',
          '#states' => [
            'visible' => [
              $column_selector => ['value' => $field],
              ':input[name="style_options[info][' . $field . '][sortable]"]' => ['checked' => TRUE],
            ],
          ],
        ];
        // Provide an ID so we can have such things.         $radio_id = Html::getUniqueId('edit-default-' . $field);
        $form['default'][$field] = [
          '#title' => $this->t('Default sort for @field', ['@field' => $field]),
          '#title_display' => 'invisible',
          '#type' => 'radio',
          '#return_value' => $field,
          '#parents' => ['style_options', 'default'],
          '#id' => $radio_id,
          // because 'radio' doesn't fully support '#id' =(           '#attributes' => ['id' => $radio_id],
          '#default_value' => $default,
          '#states' => [
            

    public function getNumberByUniqueId($id)
    {
        // TODO: use search to find number directly         $ids = $this->getUniqueId();
        foreach ($ids as $k => $v) {
            if ($v == $id) {
                return $k;
            }
        }

        /** * @see Zend_Mail_Storage_Exception */
        throw new Zend_Mail_Storage_Exception('unique id not found');
    }


    

class UniqueIdGeneratorTest extends TestCase
{
    protected function tearDown(): void
    {
        unlink(__DIR__ . '/.uniqueid.txt');
    }

    public function testGetUniqueId(): void
    {
        $idGenerator = new UniqueIdGenerator(__DIR__);
        $id = $idGenerator->getUniqueId();

        // assert that the generated id is the same on multiple calls         static::assertEquals($id$idGenerator->getUniqueId());

        unlink(__DIR__ . '/.uniqueid.txt');

        // assert that the generated id is different on a new call         static::assertNotEquals($id$idGenerator->getUniqueId());
    }
}
else {
            // Generate the parents as the autogenerator does, so we will have a             // unique id for each radio button.             $parents_for_id = array_merge($element['#parents'][$key]);
            $element[$key] = [
              '#type' => 'radio',
              '#title' => '',
              '#return_value' => $key,
              '#default_value' => ($element['#default_value'] == $key) ? $key : NULL,
              '#attributes' => $element['#attributes'],
              '#parents' => $element['#parents'],
              '#id' => HtmlUtility::getUniqueId('edit-' . implode('-', $parents_for_id)),
              '#disabled' => $disabled,
              '#ajax' => $element['#ajax'] ?? NULL,
            ];
          }
          if (isset($element['#options'][$key]['#weight'])) {
            $element[$key]['#weight'] = $element['#options'][$key]['#weight'];
          }
        }
      }
    }
    else {
      
$element[$key] += [
          '#type' => 'radio',
          '#title' => $choice,
          // The key is sanitized in Drupal\Core\Template\Attribute during output           // from the theme function.           '#return_value' => $key,
          // Use default or FALSE. A value of FALSE means that the radio button is           // not 'checked'.           '#default_value' => $element['#default_value'] ?? FALSE,
          '#attributes' => $element['#attributes'],
          '#parents' => $element['#parents'],
          '#id' => HtmlUtility::getUniqueId('edit-' . implode('-', $parents_for_id)),
          '#ajax' => $element['#ajax'] ?? NULL,
          // Errors should only be shown on the parent radios element.           '#error_no_message' => TRUE,
          '#weight' => $weight,
        ];
      }
    }
    return $element;
  }

  /** * {@inheritdoc} */
$container['uniqueid.persister'] = function D$c) {
            return new UniqueIdPersister(
                $c['uniqueid.generator'],
                $c['db']
            );
        };

        $container['shopware.notify'] = function D$c) {
            return new Notification(
                $c['config']['api.endpoint'],
                $c['uniqueid.generator']->getUniqueId(),
                $c['http-client']
            );
        };

        $container['anti.xss'] = function D$c) {
            return new AntiXSS();
        };
    }
}

    public function getNumberByUniqueId($id)
    {
        if (!$this->hasUniqueid) {
            return $id;
        }

        $ids = $this->getUniqueId();
        foreach ($ids as $k => $v) {
            if ($v == $id) {
                return $k;
            }
        }

        /** * @see Zend_Mail_Storage_Exception */
        throw new Zend_Mail_Storage_Exception('unique id not found');
    }

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