From 2969f2496188e83f65a0c21b07986c4c1e7f16dd Mon Sep 17 00:00:00 2001 From: epriestley Date: Tue, 3 May 2022 14:06:15 -0700 Subject: [PATCH] Add an ArgumentParser helper for integers Summary: Ref T13676. With increased PHP8.1 strictness around null, it seems reasonable to add some convenience parsing to "PhutilArgumentParser". Add a helper function for parsing integers. Test Plan: See next change. Tried these arguments: ``` --count '' --count asdf --count 0 --count -3 --count 999999999999999999999999999999999999999999999234 --count 5 ``` Got sensible parsing and appropriate feedback in all cases. Maniphest Tasks: T13676 Differential Revision: https://secure.phabricator.com/D21799 --- src/parser/argument/PhutilArgumentParser.php | 27 ++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/parser/argument/PhutilArgumentParser.php b/src/parser/argument/PhutilArgumentParser.php index 04b04666..6391fd83 100644 --- a/src/parser/argument/PhutilArgumentParser.php +++ b/src/parser/argument/PhutilArgumentParser.php @@ -625,6 +625,33 @@ final class PhutilArgumentParser extends Phobject { return $this->specs[$name]->getDefault(); } + public function getArgAsInteger($name) { + $value = $this->getArg($name); + + if ($value === null) { + return $value; + } + + if (!preg_match('/^-?\d+\z/', $value)) { + throw new PhutilArgumentUsageException( + pht( + 'Parameter provided to argument "--%s" must be an integer.', + $name)); + } + + $intvalue = (int)$value; + + if (phutil_string_cast($intvalue) !== phutil_string_cast($value)) { + throw new PhutilArgumentUsageException( + pht( + 'Parameter provided to argument "--%s" is too large to '. + 'parse as an integer.', + $name)); + } + + return $intvalue; + } + public function getUnconsumedArgumentVector() { return $this->argv; }