Skip to content
This repository has been archived by the owner on Feb 26, 2018. It is now read-only.

Conditional element method calls #110

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
16 changes: 16 additions & 0 deletions src/AdamWathan/Form/Elements/Element.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
27 changes: 27 additions & 0 deletions tests/TextAreaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '<textarea name="loldogz" rows="10" cols="50"></textarea>';
$result = $text->render();
$this->assertEquals($expected, $result);

$text = new TextArea('lolcatz');
$text = $text->disabledIf(true);
$expected = '<textarea name="lolcatz" rows="10" cols="50" disabled="disabled"></textarea>';
$result = $text->render();
$this->assertEquals($expected, $result);

$text = new TextArea('gluteous');
$text = $text->maxlengthIf(false, '5');
$expected = '<textarea name="gluteous" rows="10" cols="50"></textarea>';
$result = $text->render();
$this->assertEquals($expected, $result);

$text = new TextArea('maximus');
$text = $text->maxlengthIf(true, '5');
$expected = '<textarea name="maximus" rows="10" cols="50" maxlength="5"></textarea>';
$result = $text->render();
$this->assertEquals($expected, $result);
}
}