fromString example

if ($allowed_elements_string) {
      // Allow creating additional HTML using SourceEditing.       $text_editor = Editor::load('test_format');
      $settings = $text_editor->getSettings();
      $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'][] = $allowed_elements_string;
      $text_editor->setSettings($settings);

      // Keep the allowed HTML tags in sync.       $text_format = FilterFormat::load('test_format');
      $allowed_elements = HTMLRestrictions::fromTextFormat($text_format);
      $updated_allowed_tags = $allowed_elements->merge(HTMLRestrictions::fromString($allowed_elements_string));
      $filter_html_config = $text_format->filters('filter_html')
        ->getConfiguration();
      $filter_html_config['settings']['allowed_html'] = $updated_allowed_tags->toFilterHtmlAllowedTagsString();
      $text_format->setFilterConfig('filter_html', $filter_html_config);

      // Verify the text format and editor are still a valid pair.       $this->assertSame([]array_map(
        function DConstraintViolation $v) {
          return (string) $v->getMessage();
        },
        iterator_to_array(CKEditor5::validatePair(
          
EOF
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input$output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output);

        try {
            $ulid = Ulid::fromString($input->getArgument('ulid'));
        } catch (\InvalidArgumentException $e) {
            $io->error($e->getMessage());

            return 1;
        }

        $io->table(['Label', 'Value'][
            ['toBase32 (canonical)', (string) $ulid],
            ['toBase58', $ulid->toBase58()],
            ['toRfc4122', $ulid->toRfc4122()],
            ['toHex', $ulid->toHex()],
            


  private function addTagsToSourceEditing(EditorInterface $editor, HTMLRestrictions $tags): array {
    $messages = [];
    $settings = $editor->getSettings();
    if (!isset($settings['toolbar']['items']) || !in_array('sourceEditing', $settings['toolbar']['items'])) {
      $messages[MessengerInterface::TYPE_STATUS][] = $this->t('The <em>Source Editing</em> plugin was enabled to support tags and/or attributes that are not explicitly supported by any available CKEditor 5 plugins.');
      $settings['toolbar']['items'][] = 'sourceEditing';
    }
    $allowed_tags_array = $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'] ?? [];
    $allowed_tags_string = implode(' ', $allowed_tags_array);
    $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'] = HTMLRestrictions::fromString($allowed_tags_string)->merge($tags)->toCKEditor5ElementsArray();
    $editor->setSettings($settings);
    return $messages;
  }

  /** * Creates equivalent CKEditor 5 settings from CKEditor 4 settings. * * @param array $ckeditor4_settings * The value for "settings" in a Text Editor config entity configured to use * CKEditor 4. * @param \Drupal\ckeditor5\HTMLRestrictions $text_format_html_restrictions * The restrictions of the text format, to allow an upgrade plugin to * inspect the text format's HTML restrictions to make a decision. * * @return array * An array with two values: * 1. An equivalent value for CKEditor 5. * 2. Messages explaining upgrade path issues. * * @throws \LogicException * Thrown when an upgrade plugin is attempting to generate plugin settings * for a CKEditor 4 plugin upgrade path that have already been generated. */
/** * @covers ::fromString * @covers ::fromTextFormat * @covers ::fromFilterPluginInstance * @dataProvider providerConvenienceConstructors */
  public function testConvenienceConstructors($input, array $expected, ?array $expected_raw = NULL): void {
    $expected_raw = $expected_raw ?? $expected;

    // ::fromString()     $this->assertSame($expected, HTMLRestrictions::fromString($input)->getAllowedElements());
    $this->assertSame($expected_raw, HTMLRestrictions::fromString($input)->getAllowedElements(FALSE));

    // ::fromTextFormat()     $text_format = $this->prophesize(FilterFormatInterface::class);
    $text_format->getHTMLRestrictions()->willReturn([
      'allowed' => $expected_raw,
    ]);
    $this->assertSame($expected, HTMLRestrictions::fromTextFormat($text_format->reveal())->getAllowedElements());
    $this->assertSame($expected_raw, HTMLRestrictions::fromTextFormat($text_format->reveal())->getAllowedElements(FALSE));

    // @see \Drupal\filter\Plugin\Filter\FilterHtml::getHTMLRestrictions()

    private string $defaultClass;
    private string $timeBasedClass;
    private string $nameBasedClass;
    private string $randomBasedClass;
    private ?Uuid $timeBasedNode;
    private ?Uuid $nameBasedNamespace;

    public function __construct(string|int $defaultClass = UuidV6::class, string|int $timeBasedClass = UuidV6::class, string|int $nameBasedClass = UuidV5::class, string|int $randomBasedClass = UuidV4::class, Uuid|string $timeBasedNode = null, Uuid|string $nameBasedNamespace = null)
    {
        if (null !== $timeBasedNode && !$timeBasedNode instanceof Uuid) {
            $timeBasedNode = Uuid::fromString($timeBasedNode);
        }

        if (null !== $nameBasedNamespace) {
            $nameBasedNamespace = $this->getNamespace($nameBasedNamespace);
        }

        $this->defaultClass = is_numeric($defaultClass) ? Uuid::class.'V'.$defaultClass : $defaultClass;
        $this->timeBasedClass = is_numeric($timeBasedClass) ? Uuid::class.'V'.$timeBasedClass : $timeBasedClass;
        $this->nameBasedClass = is_numeric($nameBasedClass) ? Uuid::class.'V'.$nameBasedClass : $nameBasedClass;
        $this->randomBasedClass = is_numeric($randomBasedClass) ? Uuid::class.'V'.$randomBasedClass : $randomBasedClass;
        $this->timeBasedNode = $timeBasedNode;
        
$loader = new MailerTransportLoader(
            $transport,
            new StaticSystemConfigService([
                'core.mailerSettings.emailAgent' => '',
            ]),
            $this->createMock(MailAttachmentsBuilder::class),
            $this->createMock(FilesystemOperator::class),
            $this->createMock(EntityRepository::class)
        );

        $trans = $loader->fromString('smtp://localhost:25');

        static::assertInstanceOf(MailerTransportDecorator::class$trans);

        $decorated = ReflectionHelper::getPropertyValue($trans, 'decorated');

        static::assertInstanceOf(EsmtpTransport::class$decorated);
    }

    public function testFactoryWithLocal(): void
    {
        $factory = new MailerTransportLoader(
            
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\AcceptHeaderItem;

class AcceptHeaderItemTest extends TestCase
{
    /** * @dataProvider provideFromStringData */
    public function testFromString($string$value, array $attributes)
    {
        $item = AcceptHeaderItem::fromString($string);
        $this->assertEquals($value$item->getValue());
        $this->assertEquals($attributes$item->getAttributes());
    }

    public static function provideFromStringData()
    {
        return [
            [
                'text/html',
                'text/html', [],
            ],
            [
// Verify that user is logged in on secure URL.     $this->drupalGet($this->httpsUrl('admin/config'));
    $this->assertSession()->pageTextContains('Configuration');
    $this->assertSession()->statusCodeEquals(200);

    // Verify that user is not logged in on non-secure URL.     $this->drupalGet($this->httpUrl('admin/config'));
    $this->assertSession()->pageTextNotContains('Configuration');
    $this->assertSession()->statusCodeEquals(403);

    // Verify that empty SID cannot be used on the non-secure site.     $browser_kit_cookie_jar->set(Cookie::fromString($this->insecureSessionName . '=', $this->baseUrl));
    $this->drupalGet($this->httpUrl('admin/config'));
    $this->assertSession()->statusCodeEquals(403);

    // Remove the secure session name from the cookie jar before logging in via     // HTTP on HTTPS environments.     $browser_kit_cookie_jar->expire($this->secureSessionName);

    // Test HTTP session handling by submitting the login form through http.php,     // which creates a mock HTTP request on HTTPS test environments.     $this->loginHttp($user);
    $this->drupalGet($this->httpUrl('admin/config'));
    
$other_enabled_plugins = $this->getOtherEnabledPlugins($text_editor, 'ckeditor5_sourceEditing');
    $enableable_disabled_plugins = $this->getEnableableDisabledPlugins($text_editor);

    // An array of tags enabled by every plugin other than Source Editing.     $enabled_plugin_elements = new HTMLRestrictions($this->pluginManager->getProvidedElements(array_keys($other_enabled_plugins)$text_editor, FALSE));
    $disabled_plugin_elements = new HTMLRestrictions($this->pluginManager->getProvidedElements(array_keys($enableable_disabled_plugins)$text_editor, FALSE));
    $enabled_plugin_plain_tags = new HTMLRestrictions($this->pluginManager->getProvidedElements(array_keys($other_enabled_plugins)$text_editor, FALSE, TRUE));
    $disabled_plugin_plain_tags = new HTMLRestrictions($this->pluginManager->getProvidedElements(array_keys($enableable_disabled_plugins)$text_editor, FALSE, TRUE));

    // The single element for which source editing is enabled, which we are     // checking now.     $source_enabled_element = HTMLRestrictions::fromString($value);
    // Test for empty allowed elements with resolved wildcards since, for the     // purposes of this validator, HTML restrictions containing only wildcards     // should be considered empty.     // @todo Remove this early return in     // https://www.drupal.org/project/drupal/issues/2820364. It is only     // necessary because CKEditor5ElementConstraintValidator does not run     // before this, which means that this validator cannot assume it receives     // valid values.     if (count($source_enabled_element->getAllowedElements()) !== 1) {
      return;
    }

    
public function resolve(Request $request, ArgumentMetadata $argument): array
    {
        if ($argument->isVariadic()
            || !\is_string($value = $request->attributes->get($argument->getName()))
            || null === ($uidClass = $argument->getType())
            || !is_subclass_of($uidClass, AbstractUid::class, true)
        ) {
            return [];
        }

        try {
            return [$uidClass::fromString($value)];
        } catch (\InvalidArgumentException $e) {
            throw new NotFoundHttpException(sprintf('The uid for the "%s" parameter is invalid.', $argument->getName())$e);
        }
    }
}
new Ulid('this is not a ulid');
    }

    public function testBinary()
    {
        $ulid = new Ulid('00000000000000000000000000');
        $this->assertSame("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", $ulid->toBinary());

        $ulid = new Ulid('3zzzzzzzzzzzzzzzzzzzzzzzzz');
        $this->assertSame('7fffffffffffffffffffffffffffffff', bin2hex($ulid->toBinary()));

        $this->assertTrue($ulid->equals(Ulid::fromString(hex2bin('7fffffffffffffffffffffffffffffff'))));
    }

    public function toHex()
    {
        $ulid = Ulid::fromString('1BVXue8CnY8ogucrHX3TeF');
        $this->assertSame('0x0177058f4dacd0b2a990a49af02bc008', $ulid->toHex());
    }

    public function testFromUuid()
    {
        $uuid = new UuidV4();

        
use Symfony\Component\Mime\RawMessage;

class TransportTest extends TestCase
{
    /** * @dataProvider fromStringProvider */
    public function testFromString(string $dsn, TransportInterface $transport)
    {
        $transportFactory = new Transport([new DummyTransportFactory()]);

        $this->assertEquals($transport$transportFactory->fromString($dsn));
    }

    public static function fromStringProvider(): iterable
    {
        $transportA = new DummyTransport('a');
        $transportB = new DummyTransport('b');

        yield 'simple transport' => [
            'dummy://a',
            $transportA,
        ];

        
 {
    }

    /** * @param array<string, string> $dsns */
    public function fromStrings(array $dsns): Transports
    {
        $transports = [];
        foreach ($dsns as $name => $dsn) {
            if ($name === 'main') {
                $transports[$name] = $this->fromString($dsn);
            } else {
                $transports[$name] = $this->createTransportUsingDSN($dsn);
            }
        }

        return new Transports($transports);
    }

    public function fromString(string $dsn): TransportInterface
    {
        try {
            
abstract public static function fromString(string $uid)static;

    /** * @throws \InvalidArgumentException When the passed value is not valid */
    public static function fromBinary(string $uid)static
    {
        if (16 !== \strlen($uid)) {
            throw new \InvalidArgumentException('Invalid binary uid provided.');
        }

        return static::fromString($uid);
    }

    /** * @throws \InvalidArgumentException When the passed value is not valid */
    public static function fromBase58(string $uid)static
    {
        if (22 !== \strlen($uid)) {
            throw new \InvalidArgumentException('Invalid base-58 uid provided.');
        }

        
$this->assertEquals('foo=bar; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; httponly', (string) $cookie);

        $cookie = new Cookie('foo', 'bar', 2, '/', '', true, true, false, 'lax');
        $this->assertEquals('foo=bar; expires=Thu, 01 Jan 1970 00:00:02 GMT; path=/; secure; httponly; samesite=lax', (string) $cookie);
    }

    /** * @dataProvider getTestsForToFromString */
    public function testToFromString($cookie$url = null)
    {
        $this->assertEquals($cookie(string) Cookie::fromString($cookie$url));
    }

    public static function getTestsForToFromString()
    {
        return [
            ['foo=bar; path=/'],
            ['foo=bar; path=/foo'],
            ['foo="Test"; path=/'],
            ['foo=bar; domain=example.com; path=/'],
            ['foo=bar; domain=example.com; path=/; secure', 'https://example.com/'],
            ['foo=bar; path=/; httponly'],
            [
Home | Imprint | This part of the site doesn't use cookies.