diff --git a/src/AdamWathan/Form/Elements/Element.php b/src/AdamWathan/Form/Elements/Element.php index c593be2..0670a63 100644 --- a/src/AdamWathan/Form/Elements/Element.php +++ b/src/AdamWathan/Form/Elements/Element.php @@ -126,8 +126,24 @@ protected function splitKeysAndValues($array) return [$keys, $values]; } + protected function conditionalMethodCall($method, $params) + { + $condition = array_shift($params); + $method = substr($method, 0, -2); + + if ($condition) { + return call_user_func_array([$this, $method], $params); + } + + return $this; + } + public function __call($method, $params) { + if (substr($method, -2) === 'If') { + return $this->conditionalMethodCall($method, $params); + } + $params = count($params) ? $params : [$method]; $params = array_merge([$method], $params); call_user_func_array([$this, 'attribute'], $params); diff --git a/tests/TextAreaTest.php b/tests/TextAreaTest.php index 563cd2e..6911f63 100644 --- a/tests/TextAreaTest.php +++ b/tests/TextAreaTest.php @@ -143,4 +143,31 @@ public function testCanAddAttributesThroughMagicMethods() $result = $text->render(); $this->assertEquals($expected, $result); } + + public function testCanConditionallyAddAttributesThroughMagicMethods() + { + $text = new TextArea('loldogz'); + $text = $text->disabledIf(false); + $expected = ''; + $result = $text->render(); + $this->assertEquals($expected, $result); + + $text = new TextArea('lolcatz'); + $text = $text->disabledIf(true); + $expected = ''; + $result = $text->render(); + $this->assertEquals($expected, $result); + + $text = new TextArea('gluteous'); + $text = $text->maxlengthIf(false, '5'); + $expected = ''; + $result = $text->render(); + $this->assertEquals($expected, $result); + + $text = new TextArea('maximus'); + $text = $text->maxlengthIf(true, '5'); + $expected = ''; + $result = $text->render(); + $this->assertEquals($expected, $result); + } }