Skip to content

Commit cb2c545

Browse files
committed
Improved regex for capturing arguments. Updated unit test
1 parent 61441f5 commit cb2c545

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

src/CLILib/Argument/Iterator.php

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,23 @@ public function __construct(array $args = null, $ignoreFirst = true)
3535
*/
3636
// 1 - Fixed <name> capturing group so it handles hyphens.
3737
preg_match_all(
38-
'@(?:-{1,2}|\/)(?<name>[\w-]+)(?:[=:]?|\s+)(?<value>[^-\s"][^"]*?|"[^"]*")?(?=\s+[-/]|$)@i',
38+
'@(?:-{1,2}|\/)(?<name>[\w-]+)(?:(?:[:=]|\s+)(?:(?<value>[^-\s"][^"\s]+)|(?:"(?<value_in_quotes>[^"]+?)")))?@i',
3939
$string,
4040
$matches,
4141
PREG_SET_ORDER
4242
);
4343

4444
foreach ($matches as $arg) {
4545
$name = $arg['name'];
46-
$value = isset($arg['value'])
47-
? $arg['value']
48-
: true
49-
;
46+
47+
$value = true;
48+
if(isset($arg['value_in_quotes'])) {
49+
$value = $arg['value_in_quotes'];
50+
51+
} elseif(isset($arg['value'])) {
52+
$value = $arg['value'];
53+
}
54+
5055
$this->args[] = new CLILib\Argument($name, $value);
5156
$this->keys[] = $name;
5257
}

tests/Argument/Iterator/Test.php

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,25 @@ public function testValidPassArgsToConstructor()
1616
'--database myDB',
1717
'-h:local:host',
1818
'--lots-of-hyphens',
19-
'--with-hyphen=alrighty',
19+
'--with-hyphen="alrighty"',
20+
'-j /var/path/to/some_interesting_file.json',
21+
'-x "/var/path/to/some/otherfile.xml"'
2022
], false);
2123

22-
$this->assertEquals(7, iterator_count($it));
24+
$this->assertEquals(9, iterator_count($it));
2325
$this->assertTrue($it->find('hithere')->value());
2426
$this->assertEquals('cheese', $it->find('c')->value());
2527

2628
// 1 - Added tests to check for hyphens in argument names
2729
$this->assertTrue($it->find('lots-of-hyphens')->value());
2830
$this->assertEquals('alrighty', $it->find('with-hyphen')->value());
2931

32+
$this->assertEquals('/var/path/to/some_interesting_file.json', $it->find('j')->value());
33+
34+
$this->assertEquals('/var/path/to/some/otherfile.xml', $it->find('x')->value());
35+
3036
// Since iterator_count() was used, the iterator position should be at the end.
31-
$this->assertEquals(7, $it->key());
37+
$this->assertEquals(9, $it->key());
3238

3339
// Return to start and check the first item is "hithere" with a value of true
3440
$it->rewind();

0 commit comments

Comments
 (0)