You are here

function format_size in Drupal 9

Same name and namespace in other branches
  1. 8 core/includes/common.inc \format_size()
  2. 4 includes/common.inc \format_size()
  3. 5 includes/common.inc \format_size()
  4. 6 includes/common.inc \format_size()
  5. 7 includes/common.inc \format_size()

Generates a string representation for the given byte count.

Parameters

$size: A size in bytes.

$langcode: Optional language code to translate to a language other than what is used to display the page.

Return value

\Drupal\Core\StringTranslation\TranslatableMarkup A translated string representation of the size.

Related topics

23 calls to format_size()
bartik_preprocess_image_widget in core/themes/bartik/bartik.theme
Implements hook_preprocess_image_widget().
color_scheme_form_submit in core/modules/color/color.module
Form submission handler for color_scheme_form().
editor_image_upload_settings_form in core/modules/editor/editor.admin.inc
Subform constructor to configure the text editor's image upload settings.
FileFieldValidateTest::testFileMaxSize in core/modules/file/tests/src/Functional/FileFieldValidateTest.php
Tests the max file size validator.
FileItem::fieldSettingsForm in core/modules/file/src/Plugin/Field/FieldType/FileItem.php
Returns a form for the field-level settings.

... See full list

File

core/includes/common.inc, line 137
Common functions that many Drupal modules will need to reference.

Code

function format_size($size, $langcode = NULL) {
  $absolute_size = abs($size);
  if ($absolute_size < Bytes::KILOBYTE) {
    return \Drupal::translation()
      ->formatPlural($size, '1 byte', '@count bytes', [], [
      'langcode' => $langcode,
    ]);
  }

  // Create a multiplier to preserve the sign of $size.
  $sign = $absolute_size / $size;
  foreach ([
    'KB',
    'MB',
    'GB',
    'TB',
    'PB',
    'EB',
    'ZB',
    'YB',
  ] as $unit) {
    $absolute_size /= Bytes::KILOBYTE;
    $rounded_size = round($absolute_size, 2);
    if ($rounded_size < Bytes::KILOBYTE) {
      break;
    }
  }
  $args = [
    '@size' => $rounded_size * $sign,
  ];
  $options = [
    'langcode' => $langcode,
  ];
  switch ($unit) {
    case 'KB':
      return new TranslatableMarkup('@size KB', $args, $options);
    case 'MB':
      return new TranslatableMarkup('@size MB', $args, $options);
    case 'GB':
      return new TranslatableMarkup('@size GB', $args, $options);
    case 'TB':
      return new TranslatableMarkup('@size TB', $args, $options);
    case 'PB':
      return new TranslatableMarkup('@size PB', $args, $options);
    case 'EB':
      return new TranslatableMarkup('@size EB', $args, $options);
    case 'ZB':
      return new TranslatableMarkup('@size ZB', $args, $options);
    case 'YB':
      return new TranslatableMarkup('@size YB', $args, $options);
  }
}