Input fallback value option #2673

Closed
wants to merge 1 commit into
from
@@ -158,6 +158,9 @@ public function createInput($inputSpecification)
$input->setRequired(!$value);
}
break;
+ case 'fallback_value':
+ $input->setFallbackValue($value);
+ break;
case 'filters':
if ($value instanceof FilterChain) {
$input->setFilterChain($value);
@@ -65,6 +65,11 @@ class Input implements InputInterface
*/
protected $value;
+ /**
+ * @var mixed
+ */
+ protected $fallbackValue;
+
public function __construct($name = null)
{
$this->name = $name;
@@ -152,6 +157,16 @@ public function setValue($value)
}
/**
+ * @param mixed $value
+ * @return Input
+ */
+ public function setFallbackValue($value)
+ {
+ $this->fallbackValue = $value;
+ return $this;
+ }
+
+ /**
* @return boolean
*/
public function allowEmpty()
@@ -231,6 +246,14 @@ public function getValue()
}
/**
+ * @return mixed
+ */
+ public function getFallbackValue()
+ {
+ return $this->fallbackValue;
+ }
+
+ /**
* @param InputInterface $input
* @return Input
*/
@@ -260,7 +283,13 @@ public function isValid($context = null)
$this->injectNotEmptyValidator();
$validator = $this->getValidatorChain();
$value = $this->getValue();
- return $validator->isValid($value, $context);
+ $result = $validator->isValid($value, $context);
+ if (!$result && $fallbackValue = $this->getFallbackValue()) {
+ $this->setValue($fallbackValue);
+ $result = true;
+ }
+
+ return $result;
}
/**
@@ -272,6 +301,10 @@ public function getMessages()
return (array) $this->errorMessage;
}
+ if ($this->getFallbackValue()) {
+ return array();
+ }
+
$validator = $this->getValidatorChain();
return $validator->getMessages();
}