function SecurityFileUploadEventSubscriberTest::testSanitizeName

Same name in other branches
  1. 10 core/modules/system/tests/src/Unit/Event/SecurityFileUploadEventSubscriberTest.php \Drupal\Tests\system\Unit\Event\SecurityFileUploadEventSubscriberTest::testSanitizeName()
  2. 11.x core/modules/system/tests/src/Unit/Event/SecurityFileUploadEventSubscriberTest.php \Drupal\Tests\system\Unit\Event\SecurityFileUploadEventSubscriberTest::testSanitizeName()

Tests file name sanitization.

@dataProvider provideFilenames

@covers ::sanitizeName

Parameters

string $filename: The original filename.

string $allowed_extensions: The allowed extensions.

string $expected_filename: The expected filename if 'allow_insecure_uploads' is set to FALSE.

string|null $expected_filename_with_insecure_uploads: The expected filename if 'allow_insecure_uploads' is set to TRUE.

File

core/modules/system/tests/src/Unit/Event/SecurityFileUploadEventSubscriberTest.php, line 33

Class

SecurityFileUploadEventSubscriberTest
SecurityFileUploadEventSubscriber tests.

Namespace

Drupal\Tests\system\Unit\Event

Code

public function testSanitizeName(string $filename, string $allowed_extensions, string $expected_filename, string $expected_filename_with_insecure_uploads = NULL) {
    // Configure insecure uploads to be renamed.
    $config_factory = $this->getConfigFactoryStub([
        'system.file' => [
            'allow_insecure_uploads' => FALSE,
        ],
    ]);
    $subscriber = new SecurityFileUploadEventSubscriber($config_factory);
    $event = new FileUploadSanitizeNameEvent($filename, $allowed_extensions);
    $subscriber->sanitizeName($event);
    // Check the results of the configured sanitization.
    $this->assertSame($expected_filename, $event->getFilename());
    $this->assertSame($expected_filename !== $filename, $event->isSecurityRename());
    // Rerun the event allowing insecure uploads.
    $config_factory = $this->getConfigFactoryStub([
        'system.file' => [
            'allow_insecure_uploads' => TRUE,
        ],
    ]);
    $subscriber = new SecurityFileUploadEventSubscriber($config_factory);
    $event = new FileUploadSanitizeNameEvent($filename, $allowed_extensions);
    $subscriber->sanitizeName($event);
    // Check the results of the configured sanitization.
    $expected_filename_with_insecure_uploads = $expected_filename_with_insecure_uploads ?? $expected_filename;
    $this->assertSame($expected_filename_with_insecure_uploads, $event->getFilename());
    $this->assertSame($expected_filename_with_insecure_uploads !== $filename, $event->isSecurityRename());
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.