Skip to content

Commit 2dd225f

Browse files
committed
Support negative values
1 parent e8589ba commit 2dd225f

File tree

4 files changed

+31
-9
lines changed

4 files changed

+31
-9
lines changed

README.md

+6
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,12 @@ $size->add('2G')
6060
echo $size->asAuto(); // '10.00 GB'
6161
```
6262

63+
Negative values are supported. In the case below, 1.2 megabytes are subtracted:
64+
65+
```php
66+
$size->add('-1.2mb');
67+
```
68+
6369
You may also use `add()` and `subtract()` with an array of values:
6470

6571
```php

src/FileSize.php

+2-8
Original file line numberDiff line numberDiff line change
@@ -107,20 +107,14 @@ private function addSize($size)
107107
}
108108

109109
/**
110-
* Subtract from this filesize, stopping at 0 bytes.
110+
* Subtract from this filesize.
111111
*
112112
* @param string|int $size Such as '100 MB'
113113
* @return self
114114
*/
115115
private function subtractSize($size)
116116
{
117-
$bytesToSubtract = $this->sizeToBytes($size);
118-
119-
if ($bytesToSubtract <= $this->bytes) {
120-
$this->bytes -= $bytesToSubtract;
121-
} else {
122-
$this->bytes = 0;
123-
}
117+
$this->bytes -= $this->sizeToBytes($size);
124118

125119
return $this;
126120
}

src/FileSize/Parser/SizeStringParser.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class SizeStringParser
1818
* - 123 MB
1919
* - 1 gigabytes
2020
*/
21-
const SIZE_STRING_PATTERN = '/^([0-9\.]+)\s*?([A-Za-z]+)?$/';
21+
const SIZE_STRING_PATTERN = '/^([0-9\.-]+)\s*?([A-Za-z]+)?$/';
2222

2323
/**
2424
* Parse a size string into its parts (value, unit).

tests/FileSizeTest.php

+22
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ public function testAdd()
4141
$this->assertSame($size->as('B'), 129128448);
4242
}
4343

44+
/**
45+
* Test #add with a negative value.
46+
*/
47+
public function testAddNegative()
48+
{
49+
$size = new FileSize('10MB');
50+
$size->add('-20MB');
51+
52+
$this->assertSame($size->as('MB'), -10.0);
53+
}
54+
4455
/**
4556
* Test #subtract.
4657
*/
@@ -52,6 +63,17 @@ public function testSubtract()
5263
$this->assertSame($size->as('B'), 128821248);
5364
}
5465

66+
/**
67+
* Test #subtract with a negative value.
68+
*/
69+
public function testSubtractNegative()
70+
{
71+
$size = new FileSize('10MB');
72+
$size->subtract('-20MB');
73+
74+
$this->assertSame($size->as('MB'), 30.0);
75+
}
76+
5577
/**
5678
* Test adding an array of items.
5779
*/

0 commit comments

Comments
 (0)