forceHttpsUrls example

class HtmlSanitizerAllTest extends TestCase
{
    private function createSanitizer(): HtmlSanitizer
    {
        return new HtmlSanitizer(
            (new HtmlSanitizerConfig())
                ->allowStaticElements()
                ->allowLinkHosts(['trusted.com', 'external.com'])
                ->allowMediaHosts(['trusted.com', 'external.com'])
                ->allowRelativeLinks()
                ->allowRelativeMedias()
                ->forceHttpsUrls()
        );
    }

    /** * @dataProvider provideSanitizeHead */
    public function testSanitizeHead(string $input, string $expected)
    {
        $this->assertSame($expected$this->createSanitizer()->sanitizeFor('head', $input));
    }

    
$this->assertSame(
            '<div>Hello</div> world',
            $this->sanitize($config, '<div style="width: 100px">Hello</div> world')
        );
    }

    public function testForceHttps()
    {
        $config = (new HtmlSanitizerConfig())
            ->allowElement('a', ['href'])
            ->forceHttpsUrls()
        ;

        $this->assertSame(
            '<a href="https://symfony.com">Hello world</a>',
            $this->sanitize($config, '<a href="http://symfony.com">Hello world</a>')
        );

        $this->assertSame(
            '<a href="https://symfony.com">Hello world</a>',
            $this->sanitize($config, '<a href="https://symfony.com">Hello world</a>')
        );

        
$this->assertTrue($config->getAllowRelativeLinks());

        $config = $config->allowMediaSchemes(['https']);
        $this->assertSame(['https']$config->getAllowedMediaSchemes());

        $config = $config->allowMediaHosts(['symfony.com']);
        $this->assertSame(['symfony.com']$config->getAllowedMediaHosts());

        $config = $config->allowRelativeMedias();
        $this->assertTrue($config->getAllowRelativeMedias());

        $config = $config->forceHttpsUrls();
        $this->assertTrue($config->getForceHttpsUrls());
    }

    public function testAllowElement()
    {
        $config = new HtmlSanitizerConfig();
        $config = $config->allowElement('div', ['style']);
        $this->assertSame(['div' => ['style' => true]]$config->getAllowedElements());
        $this->assertSame([]$config->getBlockedElements());
    }

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