function SanitizeNameTest::testInvalidUtf8Filename

Same name and namespace in other branches
  1. 11.x core/modules/file/tests/src/Unit/SanitizeNameTest.php \Drupal\Tests\file\Unit\SanitizeNameTest::testInvalidUtf8Filename()

Tests that filenames with invalid UTF-8 are coerced, not destroyed.

Both listeners are invoked, in the order the event dispatcher runs them, because ::ensureValidUtf8Filename() is what makes the filename safe for the PCRE /u modifier used throughout ::sanitizeFilename().

Attributes

#[DataProvider('provideInvalidUtf8Filenames')]

Parameters

string $original: The original filename.

string $expected: The expected filename.

array $options: Array of filename sanitization options, in this order: 0: boolean Transliterate. 1: string Character to use in replacements. 2: boolean Replace whitespace. 3: boolean Replace non-alphanumeric characters. 4: boolean De-duplicate separators. 5: boolean Convert to lowercase.

File

core/modules/file/tests/src/Unit/SanitizeNameTest.php, line 92

Class

SanitizeNameTest
Filename sanitization tests.

Namespace

Drupal\Tests\file\Unit

Code

public function testInvalidUtf8Filename(string $original, string $expected, array $options) : void {
  $config_factory = $this->getConfigFactoryStub([
    'file.settings' => [
      'filename_sanitization' => [
        'transliterate' => $options[0],
        'replacement_character' => $options[1],
        'replace_whitespace' => $options[2],
        'replace_non_alphanumeric' => $options[3],
        'deduplicate_separators' => $options[4],
        'lowercase' => $options[5],
      ],
    ],
  ]);
  $language_manager = $this->prophesize(LanguageManagerInterface::class);
  $language_manager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
    ->willReturn(new Language([
    'id' => 'en',
  ]));
  $event = new FileUploadSanitizeNameEvent($original, 'en');
  $subscriber = new FileEventSubscriber($config_factory, new PhpTransliteration(), $language_manager->reveal());
  $subscriber->ensureValidUtf8Filename($event);
  $subscriber->sanitizeFilename($event);
  $result = $event->getFilename();
  $this->assertTrue(mb_check_encoding($result, 'UTF-8'), 'Sanitized filename is valid UTF-8.');
  $this->assertSame($expected, $result);
}

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