2 namespace Consolidation\AnnotatedCommand\Parser;
5 * An associative array that maps from key to default value;
6 * each entry can also have a description.
8 class DefaultsWithDescriptions
11 * @var array Associative array of key : default mappings
16 * @var array Associative array used like a set to indicate default value
19 protected $hasDefault;
22 * @var array Associative array of key : description mappings
24 protected $descriptions;
27 * @var mixed Default value that the default value of items in
28 * the collection should take when not specified in the 'add' method.
30 protected $defaultDefault;
32 public function __construct($values = [], $defaultDefault = null)
34 $this->values = $values;
35 $this->hasDefault = array_filter($this->values, function ($value) {
38 $this->descriptions = [];
39 $this->defaultDefault = $defaultDefault;
43 * Return just the key : default values mapping
47 public function getValues()
53 * Return true if this set of options is empty
57 public function isEmpty()
59 return empty($this->values);
63 * Check to see whether the speicifed key exists in the collection.
68 public function exists($key)
70 return array_key_exists($key, $this->values);
74 * Get the value of one entry.
76 * @param string $key The key of the item.
79 public function get($key)
81 if (array_key_exists($key, $this->values)) {
82 return $this->values[$key];
84 return $this->defaultDefault;
88 * Get the description of one entry.
90 * @param string $key The key of the item.
93 public function getDescription($key)
95 if (array_key_exists($key, $this->descriptions)) {
96 return $this->descriptions[$key];
102 * Add another argument to this command.
104 * @param string $key Name of the argument.
105 * @param string $description Help text for the argument.
106 * @param mixed $defaultValue The default value for the argument.
108 public function add($key, $description = '', $defaultValue = null)
110 if (!$this->exists($key) || isset($defaultValue)) {
111 $this->values[$key] = isset($defaultValue) ? $defaultValue : $this->defaultDefault;
113 unset($this->descriptions[$key]);
114 if (!empty($description)) {
115 $this->descriptions[$key] = $description;
120 * Change the default value of an entry.
123 * @param mixed $defaultValue
125 public function setDefaultValue($key, $defaultValue)
127 $this->values[$key] = $defaultValue;
128 $this->hasDefault[$key] = true;
133 * Check to see if the named argument definitively has a default value.
138 public function hasDefault($key)
140 return array_key_exists($key, $this->hasDefault);
146 * @param string $key The entry to remove
148 public function clear($key)
150 unset($this->values[$key]);
151 unset($this->descriptions[$key]);
155 * Rename an existing option to something else.
157 public function rename($oldName, $newName)
159 $this->add($newName, $this->getDescription($oldName), $this->get($oldName));
160 $this->clear($oldName);