Skip to content

Feature (reduce) Accumulator for multiple options of same name #93

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,18 @@ Aliases: `cast`, `castTo`

Perform a map operation on the value for this option. Takes function that accepts a string $value and return mixed (you can map to whatever you wish).

### `reduce (Closure $reducer [, mixed $seed])`

Aliases: `list`, `each`, `every`

Execute an accumulator/reducer function on every instance of the option in the command. Takes an accumulator function, and returns mixed (you can return any value). If you also supply a map for the option the map will execute on every value before it is passed to the accumulator function. If `$seed` value is supplied, this will be used as the default value.

Signature: `function(mixed $accumulated, mixed $value) : mixed`

- `$accumulated`: null|Option::default|mixed (the last value returned from the function, the option default value, or null.)
- `$value`: mixed (the value that comes after the option. if map is supplied, the value returned from the map function.)
- `return`: mixed (anything you want. The last value returned becomes the value of the Option after parsing.)

### `referToAs (string $name)`

Aliases: `title`, `referredToAs`
Expand Down
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,7 @@
"version": "0.3.0",
"autoload": {
"psr-0": {"Commando": "src/"}
},
"require-dev": {
}
}
34 changes: 32 additions & 2 deletions src/Commando/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ class Command implements \ArrayAccess, \Iterator
'cast' => 'map',
'castWith' => 'map',

'reduce' => 'reduce',
'each' => 'reduce',
'every' => 'reduce',
'list' => 'reduce',

'increment' => 'increment',
'repeatable' => 'increment',
'repeats' => 'increment',
Expand Down Expand Up @@ -340,6 +345,21 @@ private function _map(Option $option, \Closure $callback)
return $option->setMap($callback);
}

/**
* @param Option $option
* @param \Closure $callback
* @return Option
*/
private function _reduce(Option $option, \Closure $callback, $seed = null)
{
if (isset($seed))
{
$option->setDefault($seed);
}

return $option->setReducer($callback);
}

/**
* @param Option $option
* @param integer $max
Expand Down Expand Up @@ -461,6 +481,13 @@ public function parse()
}

$option = $this->getOption($name);
if ($option->hasReducer()) {
if (!isset($keyvals[$name])) {
$acc = $option->getDefault();
} else {
$acc = $keyvals[$name];
}
}
if ($option->isBoolean()) {
$keyvals[$name] = !$option->getDefault();// inverse of the default, as expected
} elseif ($option->isIncrement()) {
Expand All @@ -475,14 +502,17 @@ public function parse()
list($val, $type) = $this->_parseOption($token);
if ($type !== self::OPTION_TYPE_ARGUMENT)
throw new \Exception(sprintf('Unable to parse option %s: Expected an argument', $token));
$keyvals[$name] = $val;
if (!$option->hasReducer()) {
$keyvals[$name] = $val;
} else {
$keyvals[$name] = $option->reduce($acc, $option->map($val));
}
}
}
}

// Set values (validates and performs map when applicable)
foreach ($keyvals as $key => $value) {

$this->getOption($key)->setValue($value);
}

Expand Down
38 changes: 37 additions & 1 deletion src/Commando/Option.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
* @method Option defaultsTo (mixed $defaultValue)
* @method Option file ()
* @method Option expectsFile ()
* @method Option reduce (\Closure $reducer)
*
*/

Expand All @@ -51,6 +52,7 @@ class Option
$type = 0, /* int see constants */
$rule, /* closure */
$map, /* closure */
$reducer, /* closure */
$increment = false, /* bool */
$max_value = 0, /* int max value for increment */
$default, /* mixed default value for this option when no value is specified */
Expand Down Expand Up @@ -132,6 +134,15 @@ public function setIncrement($max = 0)
return $this;
}

/**
* @param Callable $reducer
* @return Option
*/
public function setReducer(Callable $reducer) {
$this->reducer = $reducer;
return $this;
}

/**
* Require that the argument is a file. This will
* make sure the argument is a valid file, will expand
Expand Down Expand Up @@ -243,6 +254,19 @@ public function map($value)
return call_user_func($this->map, $value);
}

/**
* @param mixed $value
* @return Option
*/
public function reduce($accumulator, $value)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

might be nice to include an optional initial value

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. At the time of writing I assumed this would be another use of default(), and it will get the default set using default() to seed the initial value of the accumulator.

I could ad an optional $default or $seed param on Command::_reduce, but I think I would implement it in a way that would just set the default value using default() anyway.

What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nategood Done.

{
if (!is_callable($this->reducer)) {
return $value;
}

return call_user_func($this->reducer, $accumulator, $value);
}


/**
* @param mixed $value
Expand Down Expand Up @@ -388,6 +412,14 @@ public function hasNeeds($optionsList)

}

/**
* @return boolean True if reducer is set
*/
public function hasReducer()
{
return is_callable($this->reducer);
}

/**
* @param mixed $value for this option (set on the command line)
* @throws \Exception
Expand Down Expand Up @@ -418,7 +450,11 @@ public function setValue($value)
$value = $file_path;
}
}
$this->value = $this->map($value);
if ($this->hasReducer()) {
$this->value = $value;
} else {
$this->value = $this->map($value);
}
}

/**
Expand Down
15 changes: 15 additions & 0 deletions tests/Commando/CommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,21 @@ public function testBooleanOption()
$this->assertTrue($cmd['b']);
}

public function testReduceOption() {
$tokens = array('filename', '--exclude', 'name1', '--exclude', 'name2');
$cmd = new Command($tokens);
$cmd
->option('exclude')
->reduce(function ($acc, $next) {
array_push($acc, $next);
return $acc;
})
->default([]);

$this->assertEquals(2, count($cmd['exclude']));
$this->assertEquals(array('name1', 'name2'), $cmd['exclude']);
}

public function testIncrementOption()
{
$tokens = array('filename', '-vvvv');
Expand Down
30 changes: 30 additions & 0 deletions tests/Commando/OptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,36 @@ public function testSetRequired()
$this->assertTrue(in_array('foo', $option->getNeeds()));
}

/**
* Test that the reducer gets set
*/
public function testSetReducer()
{
$option = new Option('f');

$this->assertTrue(!$option->hasReducer());

$option->setReducer(function() {});

$this->assertTrue($option->hasReducer());
}

/**
* Test that reducer is called
*/
public function testReduce()
{
$option = new Option('f');
$isCalled = false;
$option->setReducer(function () use (&$isCalled) {
$isCalled = true;
return ($isCalled);
});

$this->assertTrue($option->reduce(null, null));
$this->assertTrue($isCalled);
}

/**
* Test that the needed requirements are met
*/
Expand Down