You are here

public static function TestFileCreationTrait::generateFile in Drupal 10

Same name and namespace in other branches
  1. 8 core/tests/Drupal/Tests/TestFileCreationTrait.php \Drupal\Tests\TestFileCreationTrait::generateFile()
  2. 9 core/tests/Drupal/Tests/TestFileCreationTrait.php \Drupal\Tests\TestFileCreationTrait::generateFile()

Generates a test file.

Parameters

string $filename: The name of the file, including the path. The suffix '.txt' is appended to the supplied file name and the file is put into the public:// files directory.

int $width: The number of characters on one line.

int $lines: The number of lines in the file.

string $type: (optional) The type, one of:

  • text: The generated file contains random ASCII characters.
  • binary: The generated file contains random characters whose codes are in the range of 0 to 31.
  • binary-text: The generated file contains random sequence of '0' and '1' values.

Return value

string The name of the file, including the path.

File

core/tests/Drupal/Tests/TestFileCreationTrait.php, line 147

Class

TestFileCreationTrait
Provides methods to create test files from given values.

Namespace

Drupal\Tests

Code

public static function generateFile($filename, $width, $lines, $type = 'binary-text') {
  $text = '';
  for ($i = 0; $i < $lines; $i++) {

    // Generate $width - 1 characters to leave space for the "\n" character.
    for ($j = 0; $j < $width - 1; $j++) {
      switch ($type) {
        case 'text':
          $text .= chr(rand(32, 126));
          break;
        case 'binary':
          $text .= chr(rand(0, 31));
          break;
        case 'binary-text':
        default:
          $text .= rand(0, 1);
          break;
      }
    }
    $text .= "\n";
  }

  // Create filename.
  $filename = 'public://' . $filename . '.txt';
  file_put_contents($filename, $text);
  return $filename;
}