bootstrap_five_layouts-1.0.x-dev/src/Traits/BytesFormatTrait.php

src/Traits/BytesFormatTrait.php
<?php

namespace Drupal\bootstrap_five_layouts\Traits;

/**
 * Class BootstrapLayout.
 */
trait BytesFormatTrait {

  /**
   * Converts a human-readable file size to bytes.
   *
   * @param string $size
   *   The size string (e.g., "2MB", "500k").  May contain spaces.
   *
   * @return int|string
   *   The size in bytes, or STRING on $size.
   */
  public function convertToBytes($size) {
    // Normalize string and extract parts.
    $size = mb_strtolower(trim($size));
    preg_match('/^([\d\.]+)\s*([a-z]+)$/i', $size, $matches);

    if (!isset($matches[2])) {
      // No unit, assume bytes simply return (ensure int).
      return (int) $size;
    }

    $value = floatval($matches[1]);
    $unit = $matches[2];

    $units = [
      'b' => 0,
      'k' => 1, 'kb' => 1, 'kilo' => 1,
      'm' => 2, 'mb' => 2, 'meg' => 2, 'mega' => 2,
      'g' => 3, 'gb' => 3, 'gig' => 3, 'giga' => 3,
      't' => 4, 'tb' => 4, 'ter' => 4, 'tera' => 4,
      'p' => 5, 'pb' => 5, 'pet' => 5, 'peta' => 5,
      'e' => 6, 'eb' => 6, 'ex' => 6, 'exa' => 6,
      'z' => 7, 'zb' => 7, 'zet' => 7, 'zetta' => 7,
      'y' => 8, 'yb' => 8, 'yot' => 8, 'yotta' => 8,
    ];

    if (!isset($units[$unit])) {
      // Unknown, return false to signify error situation.
      return FALSE;
    }

    return (int) round($value * pow(1024, $units[$unit]));
  }

  /**
   * Formats bytes as a human-readable string.
   *
   * @param int $bytes
   *   The number of bytes.
   * @param int $decimals
   *   Number of decimal places.
   *
   * @return string
   *   The formatted string.
   */
  public function formatBytes($bytes, $decimals = 2) {
    $sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    if ($bytes == 0) {
      return '0 B';
    }
    $factor = floor(log($bytes, 1024));
    $number = sprintf("%.{$decimals}f", $bytes / pow(1024, $factor));
    $number = rtrim(rtrim($number, '0'), '.');
    return $number . ' ' . $sizes[$factor];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc