diff --git a/core/includes/common.inc b/core/includes/common.inc index 805cdea..4a36bff 100644 --- a/core/includes/common.inc +++ b/core/includes/common.inc @@ -249,31 +249,28 @@ function check_url($uri) { * A translated string representation of the size. */ function format_size($size, $langcode = NULL) { - $val = Bytes::toUnitAndSize($size); $options = ['langcode' => $langcode]; - if ($val['unit'] == 'B') { - return \Drupal::translation()->formatPlural($val['size'], '1 byte', '@count bytes', [], $options); - } - else { - $args = ['@size' => $val['size']]; - switch ($val['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); - } + $value = Bytes::toUnitAndSize($size); + $args = ['@size' => $value['size']]; + switch ($value['unit']) { + case 'B': + return \Drupal::translation()->formatPlural($value['size'], '1 byte', '@count bytes', [], $options); + 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); } } diff --git a/core/lib/Drupal/Component/Utility/Bytes.php b/core/lib/Drupal/Component/Utility/Bytes.php index f64d610..bfbd322 100644 --- a/core/lib/Drupal/Component/Utility/Bytes.php +++ b/core/lib/Drupal/Component/Utility/Bytes.php @@ -47,52 +47,33 @@ public static function toInt($size) { /** * Returns unit of measurement and size of a byte quantity. * + * This method returns an array with unit of measurement and a float + * representing, rounded to 2 decimals, the size expressed in the unit of + * measurement. If you need to get a translation aware string or object, + * use format_size(). + * * @param float $size * A quantity of bytes. * * @return array - * An assocative array with the following keys: + * An associative array with the following keys: * - 'unit': unit of measurement (string) * - 'size': size (float, rounded to 2 decimals). + * An empty array if the input value is negative. + * + * @see format_size */ public static function toUnitAndSize($size) { - if ($size < self::KILOBYTE) { - return ['unit' => 'B', 'size' => $size]; + if ($size < 0) { + return []; } - else { - $size = $size / self::KILOBYTE; - foreach (['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as $unit) { - if (round($size, 2) >= self::KILOBYTE) { - $size = $size / self::KILOBYTE; - } - else { - $size = round($size, 2); - break; - } + foreach (['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as $unit) { + if (round($size, 2) < self::KILOBYTE) { + break; } + $size = $size / self::KILOBYTE; } - return ['unit' => $unit, 'size' => $size]; - } - - /** - * Returns a string representing a byte quantity. - * - * Note that this function returns a plain string. If you need to get a - * translation aware object representing a size in bytes, use format_size() - * instead. - * - * @param float $size - * A quantity of bytes. - * - * @return string - * A string expressed as a number of bytes or multiples, suffixed with the - * unit of measurement. - * - * @see format_size - */ - public static function toString($size) { - $val = self::toUnitAndSize($size); - return $val['size'] . ' ' . $val['unit']; + return ['unit' => $unit, 'size' => round($size, 2)]; } } diff --git a/core/lib/Drupal/Component/Utility/Environment.php b/core/lib/Drupal/Component/Utility/Environment.php index d95b433..087bcad 100644 --- a/core/lib/Drupal/Component/Utility/Environment.php +++ b/core/lib/Drupal/Component/Utility/Environment.php @@ -13,12 +13,12 @@ class Environment { /** - * Compares the memory required for an operation to the total memory. + * Compares the memory required for an operation to the available memory. * * @param string $required - * The memory required for the operation, expressed as a number of bytes - * with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, - * 8bytes, 9mbytes). + * The memory required for the operation, expressed as a number of bytes with + * optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes, + * 9mbytes). * @param $memory_limit * (optional) The memory limit for the operation, expressed as a number of * bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, @@ -42,33 +42,4 @@ public static function checkMemoryLimit($required, $memory_limit = NULL) { return ((!$memory_limit) || ($memory_limit == -1) || (Bytes::toInt($memory_limit) >= Bytes::toInt($required))); } - /** - * Compares the memory required for an operation to the remaining memory. - * - * @param string $required - * The memory required for the operation, expressed as a number of bytes - * with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, - * 8bytes, 9mbytes). - * @param string $memory_limit - * (optional) The memory limit for the operation, expressed as a number of - * bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, - * 6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP - * memory_limit will be used. Defaults to NULL. - * @param string $used_memory - * (optional) The current memory usage, expressed as a number of bytes - * with optional SI or IEC binary unit prefix. If no value is passed, the - * current PHP memory usage as returned by memory_get_usage will be used. - * Defaults to NULL. - * - * @return bool - * TRUE if there is sufficient memory to allow the operation, or FALSE - * otherwise. - */ - public static function checkAvailableMemory($required, $memory_limit = NULL, $used_memory = NULL) { - if (!$used_memory) { - $used_memory = memory_get_usage(TRUE); - } - return static::checkMemoryLimit(Bytes::toInt($used_memory) + Bytes::toInt($required), $memory_limit); - } - } diff --git a/core/lib/Drupal/Component/Utility/EnvironmentMemory.php b/core/lib/Drupal/Component/Utility/EnvironmentMemory.php new file mode 100644 index 0000000..3cb1ec8 --- /dev/null +++ b/core/lib/Drupal/Component/Utility/EnvironmentMemory.php @@ -0,0 +1,115 @@ +total)) { + $this->setTotal(); + } + return $this->total; + } + + /** + * Sets the total memory, in bytes, available to PHP. + * + * @param int|string $size + * (optional) The total memory available to PHP, expressed as a number of + * bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, + * 6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP + * memory_limit will be used. Defaults to NULL. + * + * @return $this + */ + public function setTotal($size = NULL) { + if (!$size) { + $size = ini_get('memory_limit'); + } + $this->total = (!$size || $size == -1) ? -1 : Bytes::toInt($size); + } + + /** + * Gets the amount of memory, in bytes, currently allocated to PHP. + * + * @return int + * The memory, in bytes, currently used by PHP. + */ + public function getUsed() { + return memory_get_usage(TRUE); + } + + /** + * Gets the amount of memory, in bytes, currently free to be used by PHP. + * + * @return int + * The amount of memory, in bytes, free for use by PHP. Returns -1 when no + * memory limit is set or it is set to unlimited. + */ + public function getFree() { + return $this->getTotal() == - 1 ? -1 : $this->getTotal() - $this->getUsed(); + } + + /** + * Compares the memory required for an operation to the total memory. + * + * @param string $required + * The memory required for the operation, expressed as a number of bytes + * with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, + * 8bytes, 9mbytes). + * + * @return bool + * TRUE if there is sufficient memory to allow the requirements, or FALSE + * otherwise. + */ + public function checkLimit($required) { + $memory_limit = $this->getTotal(); + // There is sufficient memory if: + // - No memory limit is set, or set to unlimited (-1). + // - The memory limit is greater than or equal to the memory required for + // the operation. + return ($memory_limit == -1 || $memory_limit >= Bytes::toInt($required)); + } + + /** + * Compares the memory required for an operation to the remaining memory. + * + * @param string $required + * The memory required for the operation, expressed as a number of bytes + * with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, + * 8bytes, 9mbytes). + * + * @return bool + * TRUE if there is sufficient remaining memory to allow the requirements, + * or FALSE otherwise. + */ + public function checkAvailable($required) { + $memory_limit = $this->getTotal(); + return ($memory_limit == -1 || $this->getFree() >= Bytes::toInt($required)); + } + +} diff --git a/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php b/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php index f8b7f81..9ca7893 100644 --- a/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php +++ b/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php @@ -9,7 +9,7 @@ use Drupal\Component\Utility\Bytes; use Drupal\Component\Utility\Color; -use Drupal\Component\Utility\Environment; +use Drupal\Component\Utility\EnvironmentMemory; use Drupal\Component\Utility\Unicode; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Form\FormStateInterface; @@ -186,11 +186,19 @@ protected function load() { } // Check if enough memory is available. - if (($required_memory = $this->checkAvailableMemory($this->getWidth(), $this->getHeight())) > 0) { + if (is_array($memory = $this->checkAvailableMemory($this->getWidth(), $this->getHeight()))) { // If not, it is not possible to load the GD resource. Mark the image as // invalid, to avoid useless attempts to manipulate it. $this->preLoadInfo = NULL; - $this->logger->error("Not enough memory (required: %required_memory) to load image '%file'", ['%required_memory' => Bytes::toString($required_memory), '%file' => $this->getSource()]); + $this->logger->error("Not enough memory (required: %req_size %req_unit, free: %free_size %free_unit, total: %tot_size %tot_unit) to load image '%file'", [ + '%req_size' => $memory['required']['size'], + '%req_unit' => $memory['required']['unit'], + '%free_size' => $memory['free']['size'], + '%free_unit' => $memory['free']['unit'], + '%tot_size' => $memory['total']['size'], + '%tot_unit' => $memory['total']['unit'], + '%file' => $this->getSource() + ]); return FALSE; } @@ -470,15 +478,25 @@ protected static function supportedTypes() { * http://php.net/manual/en/function.imagecreatetruecolor.php#99623. * Defaults to 1.7. * - * @return int - * -1 if there is sufficient memory to allow the operation. Otherwise, the - * required memory, in bytes. + * @return null|array + * NULL if there is sufficient memory to allow the operation. Otherwise, an + * associative array with information about required, free and total memory. * * @see http://php.net/manual/en/function.imagecreatetruecolor.php#99623 */ public function checkAvailableMemory($width, $height, $bits_per_pixel = 32, $tweak_factor = 1.7) { $required = (int) ($width * $height * ($bits_per_pixel / 8) * $tweak_factor); - return Environment::checkAvailableMemory($required) ? -1 : $required; + $memory = new EnvironmentMemory(); + if ($memory->checkAvailable($required)) { + return NULL; + } + else { + return [ + 'required' => Bytes::toUnitAndSize($required), + 'free' => Bytes::toUnitAndSize($memory->getFree()), + 'total' => Bytes::toUnitAndSize($memory->getTotal()), + ]; + } } } diff --git a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php index 3846aa8..8cd5503 100644 --- a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php +++ b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/CreateNew.php @@ -86,8 +86,8 @@ protected function validateArguments(array $arguments) { */ protected function execute(array $arguments) { // Check if enough memory is available. - if (($required_memory = $this->getToolkit()->checkAvailableMemory($arguments['width'], $arguments['height'])) > 0) { - throw new \RuntimeException("Not enough memory (required: " . Bytes::toString($required_memory) . ") to perform the image '{$this->getPluginId()}' operation"); + if (is_array($memory = $this->getToolkit()->checkAvailableMemory($arguments['width'], $arguments['height']))) { + throw new \RuntimeException("Not enough memory (required: {$memory['required']['size']} {$memory['required']['unit']}, free: {$memory['free']['size']} {$memory['free']['unit']}, total: {$memory['total']['size']} {$memory['total']['unit']}) to perform the image '{$this->getPluginId()}' operation"); } // Get the image type. diff --git a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php index 6712456..0edcc1b 100644 --- a/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php +++ b/core/modules/system/src/Plugin/ImageToolkit/Operation/gd/Rotate.php @@ -105,8 +105,8 @@ protected function execute(array $arguments) { // can never exceed the length of the diagonal of the rectangle represented // by the image. $diagonal = (int) sqrt(pow($this->getToolkit()->getWidth(), 2) + pow($this->getToolkit()->getHeight(), 2)) + 1; - if (($required_memory = $this->getToolkit()->checkAvailableMemory($diagonal, $diagonal)) > 0) { - throw new \RuntimeException("Not enough memory (required: " . Bytes::toString($required_memory) . ") to perform the image '{$this->getPluginId()}' operation"); + if (is_array($memory = $this->getToolkit()->checkAvailableMemory($diagonal, $diagonal))) { + throw new \RuntimeException("Not enough memory (required: {$memory['required']['size']} {$memory['required']['unit']}, free: {$memory['free']['size']} {$memory['free']['unit']}, total: {$memory['total']['size']} {$memory['total']['unit']}) to perform the image '{$this->getPluginId()}' operation"); } // Stores the original GD resource. diff --git a/core/modules/system/src/Tests/Common/SizeUnitTest.php b/core/modules/system/src/Tests/Common/SizeUnitTest.php index 1cc5d0e..4fcc751 100644 --- a/core/modules/system/src/Tests/Common/SizeUnitTest.php +++ b/core/modules/system/src/Tests/Common/SizeUnitTest.php @@ -24,6 +24,7 @@ protected function setUp() { parent::setUp(); $kb = Bytes::KILOBYTE; $this->exactTestCases = array( + '0 bytes' => 0, '1 byte' => 1, '1 KB' => $kb, '1 MB' => $kb * $kb, @@ -37,6 +38,7 @@ protected function setUp() { $this->roundedTestCases = array( '2 bytes' => 2, '1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!) + '3.77 GB' => 4053371676, // not 3.78 GB as before #2583041 round(3623651 / ($this->exactTestCases['1 MB']), 2) . ' MB' => 3623651, // megabytes round(67234178751368124 / ($this->exactTestCases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes round(235346823821125814962843827 / ($this->exactTestCases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes diff --git a/core/modules/system/tests/src/Unit/Plugin/ImageToolkit/GdToolkitTest.php b/core/modules/system/tests/src/Unit/Plugin/ImageToolkit/GdToolkitTest.php index 207053e..b6b96f6 100644 --- a/core/modules/system/tests/src/Unit/Plugin/ImageToolkit/GdToolkitTest.php +++ b/core/modules/system/tests/src/Unit/Plugin/ImageToolkit/GdToolkitTest.php @@ -48,6 +48,17 @@ class GdToolkitTest extends UnitTestCase { protected $toolkitOperation; /** + * An insufficient memory array for testing. + * + * @var array + */ + protected $insufficientMemory = [ + 'required' => ['size' => 300, 'unit' => 'B'], + 'free' => ['size' => 100, 'unit' => 'B'], + 'total' => ['size' => 200, 'unit' => 'B'], + ]; + + /** * @inheritdoc */ protected function setUp() { @@ -112,7 +123,7 @@ public function testLoad() { $this->setToolkitMock(['checkAvailableMemory']); $this->toolkit->expects($this->any()) ->method('checkAvailableMemory') - ->will($this->returnValue(-1)); + ->will($this->returnValue(NULL)); $this->image = new Image($this->toolkit, $this->source); $this->assertTrue(is_resource($this->image->getToolkit()->getResource())); @@ -130,7 +141,7 @@ public function testNotEnoughMemoryOnLoad() { $this->setToolkitMock(['checkAvailableMemory']); $this->toolkit->expects($this->any()) ->method('checkAvailableMemory') - ->will($this->returnValue(1024)); + ->will($this->returnValue($this->insufficientMemory)); // Getting image from file validates the Image object, since GD toolkit is // lazy loading the resource. @@ -156,7 +167,7 @@ public function testNotEnoughMemoryOnCreateNew() { $this->setToolkitOperationMock('CreateNew', $this->toolkit); $this->toolkit->expects($this->any()) ->method('checkAvailableMemory') - ->will($this->onConsecutiveCalls(-1, 1024)); + ->will($this->onConsecutiveCalls(NULL, $this->insufficientMemory)); $this->toolkit->expects($this->any()) ->method('getToolkitOperation') ->will($this->returnValue($this->toolkitOperation)); @@ -185,7 +196,7 @@ public function testNotEnoughMemoryOnRotate() { $this->setToolkitOperationMock('Rotate', $this->toolkit); $this->toolkit->expects($this->any()) ->method('checkAvailableMemory') - ->will($this->onConsecutiveCalls(-1, 1024)); + ->will($this->onConsecutiveCalls(NULL, $this->insufficientMemory)); $this->toolkit->expects($this->any()) ->method('getToolkitOperation') ->will($this->returnValue($this->toolkitOperation)); diff --git a/core/tests/Drupal/Tests/Component/Utility/BytesTest.php b/core/tests/Drupal/Tests/Component/Utility/BytesTest.php index 554c3a0..347bff2 100644 --- a/core/tests/Drupal/Tests/Component/Utility/BytesTest.php +++ b/core/tests/Drupal/Tests/Component/Utility/BytesTest.php @@ -71,61 +71,40 @@ public function providerTestToInt() { * @param array $expected_unit_and_size * The expected return value from * \Drupal\Component\Utility\Bytes::toUnitAndSize(). - * @param string $expected_string - * The expected return value from - * \Drupal\Component\Utility\Bytes::toString(). * - * @dataProvider providerTestBytes + * @dataProvider providerTestToUnitAndSize * @covers ::toUnitAndSize */ - public function testToUnitAndSize($size, array $expected_unit_and_size, $expected_string) { + public function testToUnitAndSize($size, array $expected_unit_and_size) { $this->assertEquals($expected_unit_and_size, Bytes::toUnitAndSize($size)); } /** - * Tests \Drupal\Component\Utility\Bytes::toString(). - * - * @param int $size - * The value for the size argument for - * \Drupal\Component\Utility\Bytes::toString(). - * @param array $expected_unit_and_size - * The expected return value from - * \Drupal\Component\Utility\Bytes::toUnitAndSize(). - * @param string $expected_string - * The expected return value from - * \Drupal\Component\Utility\Bytes::toString(). - * - * @dataProvider providerTestBytes - * @covers ::toString - */ - public function testToString($size, array $expected_unit_and_size, $expected_string) { - $this->assertEquals($expected_string, Bytes::toString($size)); - } - - /** - * Provides data for ::testToUnitAndSize and ::testToString. + * Provides data for ::testToUnitAndSize. * * @return array[] * An array of arrays, each containing the argument for - * \Drupal\Component\Utility\Bytes::toUnitAndSize() and - * \Drupal\Component\Utility\Bytes::toString(), and the expected return - * value from each method. + * \Drupal\Component\Utility\Bytes::toUnitAndSize(): size and the expected + * return value. */ - public function providerTestBytes() { + public function providerTestToUnitAndSize() { return [ - [1, ['unit' => 'B', 'size' => 1], '1 B'], - [768, ['unit' => 'B', 'size' => 768], '768 B'], - [Bytes::KILOBYTE, ['unit' => 'KB', 'size' => 1], '1 KB'], - [pow(Bytes::KILOBYTE, 2), ['unit' => 'MB', 'size' => 1], '1 MB'], - [pow(Bytes::KILOBYTE, 3), ['unit' => 'GB', 'size' => 1], '1 GB'], - [pow(Bytes::KILOBYTE, 4), ['unit' => 'TB', 'size' => 1], '1 TB'], - [pow(Bytes::KILOBYTE, 5), ['unit' => 'PB', 'size' => 1], '1 PB'], - [pow(Bytes::KILOBYTE, 6), ['unit' => 'EB', 'size' => 1], '1 EB'], - [pow(Bytes::KILOBYTE, 7), ['unit' => 'ZB', 'size' => 1], '1 ZB'], - [pow(Bytes::KILOBYTE, 8), ['unit' => 'YB', 'size' => 1], '1 YB'], - [23476892, ['unit' => 'MB', 'size' => 22.39], '22.39 MB'], - [79691776, ['unit' => 'MB', 'size' => 76], '76 MB'], - [81862076662, ['unit' => 'GB', 'size' => 76.24], '76.24 GB'], + [0, ['unit' => 'B', 'size' => 0]], + [1, ['unit' => 'B', 'size' => 1]], + [-1, []], + [768, ['unit' => 'B', 'size' => 768]], + [Bytes::KILOBYTE, ['unit' => 'KB', 'size' => 1]], + [pow(Bytes::KILOBYTE, 2), ['unit' => 'MB', 'size' => 1]], + [pow(Bytes::KILOBYTE, 3), ['unit' => 'GB', 'size' => 1]], + [pow(Bytes::KILOBYTE, 4), ['unit' => 'TB', 'size' => 1]], + [pow(Bytes::KILOBYTE, 5), ['unit' => 'PB', 'size' => 1]], + [pow(Bytes::KILOBYTE, 6), ['unit' => 'EB', 'size' => 1]], + [pow(Bytes::KILOBYTE, 7), ['unit' => 'ZB', 'size' => 1]], + [pow(Bytes::KILOBYTE, 8), ['unit' => 'YB', 'size' => 1]], + [23476892, ['unit' => 'MB', 'size' => 22.39]], + [79691776, ['unit' => 'MB', 'size' => 76]], + [81862076662, ['unit' => 'GB', 'size' => 76.24]], + [4053371676, ['unit' => 'GB', 'size' => 3.77]], ]; } } diff --git a/core/tests/Drupal/Tests/Component/Utility/EnvironmentMemoryTest.php b/core/tests/Drupal/Tests/Component/Utility/EnvironmentMemoryTest.php new file mode 100644 index 0000000..60a3c55 --- /dev/null +++ b/core/tests/Drupal/Tests/Component/Utility/EnvironmentMemoryTest.php @@ -0,0 +1,165 @@ +assertEquals($limit, $memory->getTotal()); + } + + /** + * Test getting memory limit after being changed via setTotal(). + * + * @covers ::getTotal + * @covers ::setTotal + */ + public function testGetTotalFromSetTotal() { + $memory = new EnvironmentMemory(); + $memory->setTotal('100MB'); + $this->assertEquals(104857600, $memory->getTotal()); + } + + /** + * @covers ::checkLimit + * + * @dataProvider providerTestCheckLimit + * + * @param string $required + * The required memory argument for + * \Drupal\Component\Utility\EnvironmentMemory::checkLimit(). + * @param string $custom_memory_limit + * The custom memory limit argument for + * \Drupal\Component\Utility\EnvironmentMemory::checkLimit(). + * @param bool $expected + * The expected return value from + * \Drupal\Component\Utility\EnvironmentMemory::checkLimit(). + */ + public function testCheckLimit($required, $custom_memory_limit, $expected) { + $memory = new EnvironmentMemory(); + $memory->setTotal($custom_memory_limit); + $this->assertEquals($expected, $memory->checkLimit($required)); + } + + /** + * Provides data for ::testCheckLimit(). + * + * @return array + * An array of arrays, each containing the arguments for + * \Drupal\Component\Utility\EnvironmentMemory::checkLimit(): + * required and memory_limit, and the expected return value. + */ + public function providerTestCheckLimit() { + $memory_limit = ini_get('memory_limit'); + $twice_avail_memory = ($memory_limit * 2) . 'MB'; + + return [ + // Minimal amount of memory should be available. + ['30MB', NULL, TRUE], + // Exceed a custom (unlimited) memory limit. + [$twice_avail_memory, -1, TRUE], + // Exceed a custom memory limit. + ['30MB', '16MB', FALSE], + // Available = required. + ['30MB', '30MB', TRUE], + ]; + } + + /** + * Test available memory based on current process memory usage. + * + * @covers ::checkAvailable + * @covers ::getUsed + */ + public function testCheckAvailableCurrent() { + $limit = ini_get('memory_limit'); + $limit = (!$limit || $limit == -1) ? -1 : Bytes::toInt($limit); + if ($limit > 0) { + $free_memory = $limit - memory_get_usage(TRUE); + $memory = new EnvironmentMemory(); + $this->assertTrue($memory->checkAvailable($free_memory - Bytes::toInt('4k'))); + $this->assertFalse($memory->checkAvailable($free_memory + Bytes::toInt('4k'))); + } + } + + /** + * Test available memory based on simulated memory usage. + * + * @covers ::checkAvailable + * + * @dataProvider providerTestCheckAvailable + * + * @param string $custom_memory_limit + * A custom memory limit argument for + * \Drupal\Component\Utility\EnvironmentMemory::checkAvailable(). + * @param string $used_memory + * A mocked value for used memory. + * @param string $required + * The required memory argument for + * \Drupal\Component\Utility\EnvironmentMemory::checkAvailable(). + * @param bool $expected + * The expected return value from + * \Drupal\Component\Utility\EnvironmentMemory::checkAvailable(). + */ + public function testCheckAvailable($custom_memory_limit, $used_memory, $required, $expected) { + $mock_builder = $this->getMockBuilder('Drupal\Component\Utility\EnvironmentMemory'); + $memory = $mock_builder + ->setMethods(['getUsed']) + ->getMock(); + $memory->expects($this->any()) + ->method('getUsed') + ->will($this->returnValue(Bytes::toInt($used_memory))); + + $memory->setTotal($custom_memory_limit); + $this->assertEquals($expected, $memory->checkAvailable($required)); + } + + /** + * Provides data for ::testCheckAvailable(). + * + * @return array[] + * An array of arrays, each containing the arguments for + * \Drupal\Component\Utility\EnvironmentMemory::checkAvailable(): + * memory_limit, used_memory, required memory and the expected + * return value. + */ + public function providerTestCheckAvailable() { + $currently_available = Bytes::toInt(ini_get('memory_limit')) - memory_get_usage(TRUE); + return [ + // 30MB should be available with limit of 60MB and usage of 10MB. + ['60MB', '10MB', '30MB', TRUE], + // Limit = required + used. + ['40MB', '30MB', '10MB', TRUE], + // Exceed memory limit. + ['20MB', '10MB', '30MB', FALSE], + // Exceed memory limit by 1 byte. + ['20MB', '20MB', '1', FALSE], + ]; + } + +} diff --git a/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php b/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php index 46e2d1f..72f04f7 100644 --- a/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php +++ b/core/tests/Drupal/Tests/Component/Utility/EnvironmentTest.php @@ -64,49 +64,4 @@ public function providerTestCheckMemoryLimit() { ); } - /** - * Tests \Drupal\Component\Utility\Environment::checkAvailableMemory(). - * - * @dataProvider providerTestCheckAvailableMemory - * @covers ::checkAvailableMemory - * - * @param string $custom_memory_limit - * A custom memory limit argument for - * \Drupal\Component\Utility\Environment::checkAvailableMemory(). - * @param string $used_memory - * A mocked value for used memory. - * @param string $required - * The required memory argument for - * \Drupal\Component\Utility\Environment::checkAvailableMemory(). - * @param bool $expected - * The expected return value from - * \Drupal\Component\Utility\Environment::checkAvailableMemory(). - */ - public function testCheckAvailableMemory($custom_memory_limit, $used_memory, $required, $expected) { - $actual = Environment::checkAvailableMemory($required, $custom_memory_limit, $used_memory); - $this->assertEquals($expected, $actual); - } - - /** - * Provides data for testCheckAvailableMemory(). - * - * @return array[] - * An array of arrays, each containing the arguments for - * \Drupal\Component\Utility\Environment::checkAvailableMemory(): - * memory_limit, used_memory, required memory and the expected - * return value. - */ - public function providerTestCheckAvailableMemory() { - return [ - // 30MB should be available with limit of 60MB and usage of 10MB. - ['60MB', '10MB', '30MB', TRUE], - // Limit = required + used. - ['40MB', '30MB', '10MB', TRUE], - // Exceed memory limit. - ['20MB', '10MB', '30MB', FALSE], - // Exceed memory limit by 1 byte. - ['20MB', '20MB', '1', FALSE], - ]; - } - }