22
33namespace BigFileTools \Driver ;
44use Brick \Math \BigInteger ;
5+ use Brick \Math \Exception \ArithmeticException ;
56
67class ExecDriver implements ISizeDriver
78{
@@ -41,36 +42,50 @@ public function getFileSize($path)
4142 }
4243 }
4344
45+ /**
46+ * Convert string into integer
47+ * Must be precise number, otherwise you will see and exception.
48+ *
49+ * @param $valueAsString
50+ * @return BigInteger
51+ * @throws Exception
52+ */
53+ private function convertToInteger ($ valueAsString ) {
54+ if (!is_string ($ valueAsString )) {
55+ throw new Exception ("Cannot convert to integer. Expected string, but got " . gettype ($ valueAsString ). ". " );
56+ }
57+ $ trimmedInput = trim ($ valueAsString );
58+
59+ try {
60+ return BigInteger::of ($ trimmedInput );
61+
62+ } catch (ArithmeticException $ e ) {
63+ throw new Exception ("Returned value cannot be converted to an integer. " ,0 , $ e );
64+ }
65+
66+ }
67+
4468 private function getFileSizeWindows ($ path )
4569 {
4670 $ escapedPath = escapeshellarg ($ path );
47- $ size = trim (exec ("for %F in ( $ escapedPath) do @echo %~zF " ));
48- if ($ size AND ctype_digit ($ size )) {
49- return BigInteger::of ($ size );
50- } else {
51- throw new Exception ("Exec returned invalid value " );
52- }
71+ return $ this ->convertToInteger (
72+ exec ("for %F in ( $ escapedPath) do @echo %~zF " )
73+ );
5374 }
5475
5576 private function getFileSizeLinux ($ path )
5677 {
5778 $ escapedPath = escapeshellarg ($ path );
58- $ size = trim (exec ("stat -Lc%s $ escapedPath " ));
59- if ($ size AND ctype_digit ($ size )) {
60- return BigInteger::of ($ size );
61- } else {
62- throw new Exception ("Exec returned invalid value " );
63- }
79+ return $ this ->convertToInteger (
80+ exec ("stat -Lc%s $ escapedPath " )
81+ );
6482 }
6583
6684 private function getFileSizeMac ($ path )
6785 {
6886 $ escapedPath = escapeshellarg ($ path );
69- $ size = trim (exec ("stat -f%z $ escapedPath " ));
70- if ($ size AND ctype_digit ($ size )) {
71- return BigInteger::of ($ size );
72- } else {
73- throw new Exception ("Exec returned invalid value " );
74- }
87+ return $ this ->convertToInteger (
88+ exec ("stat -f%z $ escapedPath " )
89+ );
7590 }
7691}
0 commit comments