Browse Source

Parse only positional arguments after double-dash

Corey Taylor 3 years ago
parent
commit
893569b538

+ 13 - 0
src/Console/ConsoleOptionParser.php

@@ -691,10 +691,23 @@ class ConsoleOptionParser
             /** @psalm-suppress PossiblyNullReference */
             return $this->_subcommands[$command]->parser()->parse($argv, $io);
         }
+
         $params = $args = [];
         $this->_tokens = $argv;
+
+        $afterDoubleDash = false;
         while (($token = array_shift($this->_tokens)) !== null) {
             $token = (string)$token;
+            if ($token === '--') {
+                $afterDoubleDash = true;
+                continue;
+            }
+            if ($afterDoubleDash) {
+                // only positional arguments after --
+                $args = $this->_parseArg($token, $args);
+                continue;
+            }
+
             if (isset($this->_subcommands[$token])) {
                 continue;
             }

+ 22 - 0
tests/TestCase/Console/ConsoleOptionParserTest.php

@@ -729,6 +729,28 @@ class ConsoleOptionParserTest extends TestCase
         $this->assertCount(2, $result, 'Not enough arguments');
     }
 
+    public function testParseArgumentsDoubleDash(): void
+    {
+        $parser = new ConsoleOptionParser('test');
+
+        $result = $parser->parse(['one', 'two', '--', '-h', '--help', '--test=value'], $this->io);
+        $this->assertEquals(['one', 'two', '-h', '--help', '--test=value'], $result[1]);
+    }
+
+    public function testParseArgumentsOptionsDoubleDash(): void
+    {
+        $parser = new ConsoleOptionParser('test', false);
+        $parser->addOption('test');
+
+        $result = $parser->parse(['--test=value', '--', '--test'], $this->io);
+        $this->assertEquals(['test' => 'value', 'help' => false], $result[0]);
+        $this->assertEquals(['--test'], $result[1]);
+
+        $result = $parser->parse(['--', '--test'], $this->io);
+        $this->assertEquals(['help' => false], $result[0]);
+        $this->assertEquals(['--test'], $result[1]);
+    }
+
     /**
      * test setting a subcommand up.
      */