You are here

function format_size in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/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()
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/src/Tests/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.
FileSize::render in core/modules/views/src/Plugin/views/field/FileSize.php
Renders the field.

... See full list

File

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

Code

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

    // Convert bytes to kilobytes.
    $units = [
      'KB',
      'MB',
      'GB',
      'TB',
      'PB',
      'EB',
      'ZB',
      'YB',
    ];
    foreach ($units as $unit) {
      if (round($size, 2) >= Bytes::KILOBYTE) {
        $size = $size / Bytes::KILOBYTE;
      }
      else {
        break;
      }
    }
    $args = [
      '@size' => round($size, 2),
    ];
    $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);
    }
  }
}