| 1 | <?php |
||
| 41 | abstract class AbstractViewModel implements ViewModel |
||
| 42 | { |
||
| 43 | /** |
||
| 44 | * @var array The actual view data |
||
| 45 | */ |
||
| 46 | protected $variables = []; |
||
| 47 | |||
| 48 | /** |
||
| 49 | * @var string[] The names of the valid set of fields that must be passed to the display() method |
||
| 50 | */ |
||
| 51 | protected $expect_var_names = []; |
||
| 52 | |||
| 53 | public function __construct() |
||
| 54 | { |
||
| 55 | // Assign the expect_var_names to ensure that we don't accidentally start requiring compiled fields |
||
| 56 | $this->expect_var_names = array_keys($this->variables); |
||
| 57 | } |
||
| 58 | |||
| 59 | /** |
||
| 60 | * Get field values |
||
| 61 | * |
||
| 62 | * @param string $name |
||
| 63 | * |
||
| 64 | * @return mixed |
||
| 65 | */ |
||
| 66 | public function __get($name) |
||
| 67 | { |
||
| 68 | if (array_key_exists($name, $this->variables)) { |
||
| 69 | return $this->variables[$name]; |
||
| 70 | } elseif (method_exists($this, 'var_'.$name)) { |
||
| 71 | $method = 'var_'.$name; |
||
| 72 | |||
| 73 | return $this->$method(); |
||
| 74 | } else { |
||
| 75 | throw UndefinedViewVarException::forClassAndVar(static::class, $name); |
||
| 76 | } |
||
| 77 | } |
||
| 78 | |||
| 79 | /** |
||
| 80 | * @param string $name |
||
| 81 | * @param mixed $value |
||
| 82 | * |
||
| 83 | * @throws \BadMethodCallException values cannot be assigned except with the display method |
||
| 84 | */ |
||
| 85 | public function __set($name, $value) |
||
|
1 ignored issue
–
show
|
|||
| 86 | { |
||
| 87 | throw InvalidViewVarAssignmentException::forReadOnlyVar(static::class, $name); |
||
| 88 | } |
||
| 89 | |||
| 90 | /** |
||
| 91 | * Set the data to be rendered in the view - note this does not actually render the view. |
||
| 92 | * |
||
| 93 | * @param array $variables |
||
| 94 | */ |
||
| 95 | public function display(array $variables) |
||
| 96 | { |
||
| 97 | if ($errors = $this->validateDisplayVariables($variables)) { |
||
| 98 | throw InvalidDisplayVariablesException::passedToDisplay(static::class, $errors); |
||
| 99 | } |
||
| 100 | |||
| 101 | $this->variables = $variables; |
||
| 102 | } |
||
| 103 | |||
| 104 | /** |
||
| 105 | * @param array $variables |
||
| 106 | * |
||
| 107 | * @return string[] of errors |
||
| 108 | */ |
||
| 109 | protected function validateDisplayVariables(array $variables) |
||
| 127 | |||
| 128 | } |
||
| 129 |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.