class Bytes

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Component/Utility/Bytes.php \Drupal\Component\Utility\Bytes
  2. 8.9.x core/lib/Drupal/Component/Utility/Bytes.php \Drupal\Component\Utility\Bytes
  3. 10 core/lib/Drupal/Component/Utility/Bytes.php \Drupal\Component\Utility\Bytes

Provides helper methods for byte conversions.

Hierarchy

  • class \Drupal\Component\Utility\Bytes

Expanded class hierarchy of Bytes

10 files declare their use of Bytes
ByteSizeMarkup.php in core/lib/Drupal/Core/StringTranslation/ByteSizeMarkup.php
ByteSizeMarkupTest.php in core/tests/Drupal/Tests/Core/StringTranslation/ByteSizeMarkupTest.php
BytesTest.php in core/tests/Drupal/Tests/Component/Utility/BytesTest.php
CKEditor5ImageController.php in core/modules/ckeditor5/src/Controller/CKEditor5ImageController.php
FileItem.php in core/modules/file/src/Plugin/Field/FieldType/FileItem.php

... See full list

5 string references to 'Bytes'
core.data_types.schema.yml in core/config/schema/core.data_types.schema.yml
core/config/schema/core.data_types.schema.yml
core.data_types.schema.yml in core/config/schema/core.data_types.schema.yml
core/config/schema/core.data_types.schema.yml
editor.schema.yml in core/modules/editor/config/schema/editor.schema.yml
core/modules/editor/config/schema/editor.schema.yml
FieldFileSizeTest::testFieldFileSize in core/modules/views/tests/src/Kernel/Handler/FieldFileSizeTest.php
FileSize::render in core/modules/views/src/Plugin/views/field/FileSize.php
Renders the field.

File

core/lib/Drupal/Component/Utility/Bytes.php, line 10

Namespace

Drupal\Component\Utility
View source
class Bytes {
    
    /**
     * The number of bytes in a kilobyte.
     *
     * @see http://wikipedia.org/wiki/Kilobyte
     */
    const KILOBYTE = 1024;
    
    /**
     * The allowed suffixes of a bytes string in lowercase.
     *
     * @see http://wikipedia.org/wiki/Kilobyte
     */
    const ALLOWED_SUFFIXES = [
        '',
        'b',
        'byte',
        'bytes',
        'k',
        'kb',
        'kilobyte',
        'kilobytes',
        'm',
        'mb',
        'megabyte',
        'megabytes',
        'g',
        'gb',
        'gigabyte',
        'gigabytes',
        't',
        'tb',
        'terabyte',
        'terabytes',
        'p',
        'pb',
        'petabyte',
        'petabytes',
        'e',
        'eb',
        'exabyte',
        'exabytes',
        'z',
        'zb',
        'zettabyte',
        'zettabytes',
        'y',
        'yb',
        'yottabyte',
        'yottabytes',
    ];
    
    /**
     * Parses a given byte size.
     *
     * @param int|float|string $size
     *   An integer, float, or string size expressed as a number of bytes with
     *   optional SI or IEC binary unit prefix (e.g. 2, 2.4, 3K, 5MB, 10G, 6GiB,
     *   8 bytes, 9mbytes).
     *
     * @return float
     *   The floating point value of the size in bytes.
     */
    public static function toNumber($size) : float {
        // Remove the non-unit characters from the size.
        $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
        // Remove the non-numeric characters from the size.
        $size = preg_replace('/[^0-9\\.]/', '', $size);
        if ($unit) {
            // Find the position of the unit in the ordered string which is the power
            // of magnitude to multiply a kilobyte by.
            return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
        }
        else {
            // Ensure size is a proper number type.
            return round((double) $size);
        }
    }
    
    /**
     * Validate that a string is a representation of a number of bytes.
     *
     * @param string $string
     *   The string to validate.
     *
     * @return bool
     *   TRUE if the string is valid, FALSE otherwise.
     */
    public static function validate($string) : bool {
        // Ensure that the string starts with a numeric character.
        if (!preg_match('/^[0-9]/', $string)) {
            return FALSE;
        }
        // Remove the numeric characters from the beginning of the value.
        $string = preg_replace('/^[0-9\\.]+/', '', $string);
        // Remove remaining spaces from the value.
        $string = trim($string);
        return in_array(strtolower($string), self::ALLOWED_SUFFIXES);
    }
    
    /**
     * Validates a string is a representation of a number of bytes.
     *
     * To be used with the `Callback` constraint.
     *
     * @param string|int|float|null $value
     *   The string, integer or float to validate.
     * @param \Symfony\Component\Validator\Context\ExecutionContextInterface $context
     *   The validation execution context.
     *
     * @see \Symfony\Component\Validator\Constraints\CallbackValidator
     * @see core/config/schema/core.data_types.schema.yml
     */
    public static function validateConstraint(string|int|float|null $value, ExecutionContextInterface $context) : void {
        // Ignore NULL values (i.e. support `nullable: true`).
        if ($value === NULL) {
            return;
        }
        if (!self::validate((string) $value)) {
            $context->addViolation('This value must be a number of bytes, optionally with a unit such as "MB" or "megabytes". %value does not represent a number of bytes.', [
                '%value' => $value,
            ]);
        }
    }

}

Members

Title Sort descending Modifiers Object type Summary
Bytes::ALLOWED_SUFFIXES constant The allowed suffixes of a bytes string in lowercase.
Bytes::KILOBYTE constant The number of bytes in a kilobyte.
Bytes::toNumber public static function Parses a given byte size.
Bytes::validate public static function Validate that a string is a representation of a number of bytes.
Bytes::validateConstraint public static function Validates a string is a representation of a number of bytes.

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