Skip to content

Commit

Permalink
Add support for \Path\To\Class::staticMethodName for defining field o…
Browse files Browse the repository at this point in the history
…ptions.

Related: octobercms/library@95d0b61
  • Loading branch information
LukeTowers committed Sep 10, 2020
1 parent 619be11 commit b407f26
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions modules/backend/lang/en/lang.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
'invalid_type' => 'Invalid field type used :type.',
'options_method_invalid_model' => "The attribute ':field' does not resolve to a valid model. Try specifying the options method for model class :model explicitly.",
'options_method_not_exists' => "The model class :model must define a method :method() returning options for the ':field' form field.",
'options_static_method_invalid_value' => "The static method ':method()' on :class did not return a valid options array.",
'colors_method_not_exists' => "The model class :model must define a method :method() returning html color HEX codes for the ':field' form field.",
],
'widget' => [
Expand Down
17 changes: 17 additions & 0 deletions modules/backend/widgets/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,7 @@ protected function getOptionsFromModel($field, $fieldOptions)
{
/*
* Advanced usage, supplied options are callable
* [\Path\To\Class, methodName]
*/
if (is_array($fieldOptions) && is_callable($fieldOptions)) {
$fieldOptions = call_user_func($fieldOptions, $this, $field);
Expand Down Expand Up @@ -1328,6 +1329,22 @@ protected function getOptionsFromModel($field, $fieldOptions)
* Field options are an explicit method reference
*/
elseif (is_string($fieldOptions)) {
// \Path\To\Class::staticMethodOptions
if (str_contains($fieldOptions, '::')) {
$options = explode('::', $fieldOptions);
if (count($options) === 2 && class_exists($options[0]) && method_exists($options[0], $options[1])) {
$result = $options[0]::{$options[1]}();
if (!is_array($result)) {
throw new ApplicationException(Lang::get('backend::lang.field.options_static_method_invalid_value', [
'class' => $options[0],
'method' => $options[1]
]));
}
return $result;
}
}

// $model->{$fieldOptions}()
if (!$this->objectMethodExists($this->model, $fieldOptions)) {
throw new ApplicationException(Lang::get('backend::lang.field.options_method_not_exists', [
'model' => get_class($this->model),
Expand Down

0 comments on commit b407f26

Please sign in to comment.