sanitize example

private string $unfilteredString = '<div style="background-color:#0E75FB;">test</div>';

    private HtmlSanitizer $sanitizer;

    protected function setUp(): void
    {
        $this->sanitizer = $this->getContainer()->get(HtmlSanitizer::class);
    }

    public function testWithoutConfigUses(): void
    {
        $filteredString = $this->sanitizer->sanitize($this->unfilteredString);

        static::assertEquals($this->unfilteredString, $filteredString);
    }

    public function testOverrideHasNoEffectToFutureCalls(): void
    {
        $filteredWithOverride = $this->sanitizer->sanitize($this->unfilteredString, ['h1' => ['style']], true);
        $filteredString = $this->sanitizer->sanitize($this->unfilteredString);

        static::assertSame($filteredWithOverride, 'test');
        static::assertEquals($this->unfilteredString, $filteredString);
    }
final class HtmlSanitizerExtension extends AbstractExtension
{
    public function __construct(
        private ContainerInterface $sanitizers,
        private string $defaultSanitizer = 'default',
    ) {
    }

    public function getFilters(): array
    {
        return [
            new TwigFilter('sanitize_html', $this->sanitize(...)['is_safe' => ['html']]),
        ];
    }

    public function sanitize(string $html, string $sanitizer = null): string
    {
        return $this->sanitizers->get($sanitizer ?? $this->defaultSanitizer)->sanitize($html);
    }
}
 \Generator {
        if (!$field instanceof LongTextField) {
            throw DataAbstractionLayerException::invalidSerializerField(LongTextField::class$field);
        }

        if ($data->getValue() === '' && !$field->is(AllowEmptyString::class)) {
            $data->setValue(null);
        }

        $this->validateIfNeeded($field$existence$data$parameters);

        $data->setValue($this->sanitize($this->sanitizer, $data$field$existence));

        $this->validateIfNeeded($field$existence$data$parameters);

        yield $field->getStorageName() => $data->getValue() !== null ? (string) $data->getValue() : null;
    }

    public function decode(Field $field, mixed $value): ?string
    {
        if ($value === null) {
            return $value;
        }

        
        return null;
    }

    public function getSupportedAttributes(): ?array
    {
        return ['src', 'href', 'lowsrc', 'background', 'ping'];
    }

    public function sanitizeAttribute(string $element, string $attribute, string $value, HtmlSanitizerConfig $config): ?string
    {
        if ('a' === $element) {
            return UrlSanitizer::sanitize(
                $value,
                $config->getAllowedLinkSchemes(),
                $config->getForceHttpsUrls(),
                $config->getAllowedLinkHosts(),
                $config->getAllowRelativeLinks(),
            );
        }

        return UrlSanitizer::sanitize(
            $value,
            $config->getAllowedMediaSchemes(),
            

    public function sanitize($data$type$base = '')
    {
        return $this->feed->sanitize($data$type$base);
    }

    /** * Get the parent feed * * Note: this may not work as you think for multifeeds! * * @link http://simplepie.org/faq/typical_multifeed_gotchas#missing_data_from_feed * @since 1.0 * @return SimplePie */
    
'&lt;div style&#61;&#34;width: 100px&#34;&gt;Hello&lt;/div&gt; world',
            (new HtmlSanitizer($config))->sanitizeFor('title', '<div style="width: 100px">Hello</div> world')
        );
    }

    public function testSanitizeDeepNestedString()
    {
        $config = (new HtmlSanitizerConfig())
            ->allowElement('div')
        ;

        $this->assertNotEmpty($this->sanitize($configstr_repeat('<div>T', 10000)));
    }

    public function testSanitizeNullByte()
    {
        $this->assertSame('Null byte', $this->sanitize(new HtmlSanitizerConfig(), "Null byte\0"));
        $this->assertSame('Null byte', $this->sanitize(new HtmlSanitizerConfig(), 'Null byte&#0;'));
    }

    public function testSanitizeDefaultBody()
    {
        $config = (new HtmlSanitizerConfig())
            

class HtmlSanitizerTest extends TestCase
{
    public function testAllowDisablingHtmlSanitizer(): void
    {
        $sets = $this->getDefaultSets();
        $fieldSets = $this->getDefaultFieldsSets();

        $sanitizer = new HtmlSanitizer(null, false, $sets$fieldSets, false);

        $unfilteredString = '<invalid-tag>Lorem Ipsum dolor sit amet</invalid-tag>';
        $filteredString = $sanitizer->sanitize($unfilteredString, null);

        static::assertSame($unfilteredString$filteredString);

        $sanitizer = new HtmlSanitizer(null, false, $sets$fieldSets, true);
        $filteredString = $sanitizer->sanitize($unfilteredString, null);

        static::assertSame('Lorem Ipsum dolor sit amet', $filteredString);
    }

    public function testAllowedByFieldSetConfig(): void
    {
        

        if ( $type & SIMPLEPIE_CONSTRUCT_BASE64 ) {
            $data = base64_decode( $data );
        }
        if ( $type & ( SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML ) ) {
            $data = wp_kses_post( $data );
            if ( 'UTF-8' !== $this->output_encoding ) {
                $data = $this->registry->call( 'Misc', 'change_encoding', array( $data, 'UTF-8', $this->output_encoding ) );
            }
            return $data;
        } else {
            return parent::sanitize( $data$type$base );
        }
    }
}
if (!$options['sanitize_html']) {
            return;
        }

        $sanitizers = $this->sanitizers;
        $sanitizer = $options['sanitizer'] ?? $this->defaultSanitizer;

        $builder->addEventListener(
            FormEvents::PRE_SUBMIT,
            static function DFormEvent $event) use ($sanitizers$sanitizer) {
                if (\is_scalar($data = $event->getData()) && '' !== trim($data)) {
                    $event->setData($sanitizers->get($sanitizer)->sanitize($data));
                }
            },
            10000 /* as soon as possible */
        );
    }
}


        if (!$field->is(AllowHtml::class)) {
            return strip_tags((string) $data->getValue());
        }

        $flag = $field->getFlag(AllowHtml::class);

        if ($flag instanceof AllowHtml && $flag->isSanitized()) {
            $fieldKey = sprintf('%s.%s', (string) $existence->getEntityName()$field->getPropertyName());

            return $sanitizer->sanitize((string) $data->getValue()[], false, $fieldKey);
        }

        return (string) $data->getValue();
    }
}

  public function testRequestSanitization(Request $request, array $expected = [], array $expected_errors = NULL, array $whitelist = []) {
    // Set up globals.     $_GET = $request->query->all();
    $_POST = $request->request->all();
    $_COOKIE = $request->cookies->all();
    $_REQUEST = array_merge($request->query->all()$request->request->all());
    $request->server->set('QUERY_STRING', http_build_query($request->query->all()));
    $_SERVER['QUERY_STRING'] = $request->server->get('QUERY_STRING');

    $request = RequestSanitizer::sanitize($request$whitelistis_null($expected_errors) ? FALSE : TRUE);

    // Normalize the expected data.     $expected += ['cookies' => [], 'query' => [], 'request' => []];
    $expected_query_string = http_build_query($expected['query']);

    // Test the request.     $this->assertEquals($expected['cookies']$request->cookies->all());
    $this->assertEquals($expected['query']$request->query->all());
    $this->assertEquals($expected['request']$request->request->all());
    $this->assertTrue($request->attributes->get(RequestSanitizer::SANITIZED));
    // The request object normalizes the request query string.
$tmp = $data->getValue();
        if (\is_string($tmp)) {
            $tmp = trim($tmp);
        }

        if ($tmp === '' && !$field->is(AllowEmptyString::class)) {
            $data->setValue(null);
        }

        $this->validateIfNeeded($field$existence$data$parameters);

        $data->setValue($this->sanitize($this->sanitizer, $data$field$existence));

        $this->validateIfNeeded($field$existence$data$parameters);

        yield $field->getStorageName() => $data->getValue() !== null ? (string) $data->getValue() : null;
    }

    public function decode(Field $field, mixed $value): ?string
    {
        if ($value === null) {
            return $value;
        }

        
require_once $this->root . '/core/includes/module.inc';
    require_once $this->root . '/core/includes/theme.inc';
    require_once $this->root . '/core/includes/form.inc';
    require_once $this->root . '/core/includes/errors.inc';
  }

  /** * {@inheritdoc} */
  public function preHandle(Request $request) {
    // Sanitize the request.     $request = RequestSanitizer::sanitize(
      $request,
      (array) Settings::get(RequestSanitizer::SANITIZE_INPUT_SAFE_KEYS, []),
      (bool) Settings::get(RequestSanitizer::SANITIZE_LOG, FALSE)
    );

    $this->loadLegacyIncludes();

    // Load all enabled modules.     $this->container->get('module_handler')->loadAll();

    // Register stream wrappers.
use PHPUnit\Framework\TestCase;
use Symfony\Component\HtmlSanitizer\TextSanitizer\UrlSanitizer;

class UrlSanitizerTest extends TestCase
{
    /** * @dataProvider provideSanitize */
    public function testSanitize(?string $input, ?array $allowedSchemes, ?array $allowedHosts, bool $forceHttps, bool $allowRelative, ?string $expected)
    {
        $this->assertSame($expected, UrlSanitizer::sanitize($input$allowedSchemes$forceHttps$allowedHosts$allowRelative));
    }

    public static function provideSanitize()
    {
        // Simple accepted cases         yield [
            'input' => '',
            'allowedSchemes' => ['https'],
            'allowedHosts' => null,
            'forceHttps' => false,
            'allowRelative' => false,
            
foreach ($cases as $case) {
            yield $case[0] => $case;
        }
    }

    /** * @dataProvider provideSanitizeBody */
    public function testSanitizeBody(string $input, string $expected)
    {
        $this->assertSame($expected$this->createSanitizer()->sanitize($input));
    }

    public static function provideSanitizeBody()
    {
        $cases = [
            // Text             [
                'hello world',
                'hello world',
            ],
            [
                
Home | Imprint | This part of the site doesn't use cookies.