| Conditions | 2 |
| Paths | 2 |
| Total Lines | 58 |
| Code Lines | 26 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 23 | public function editableCompose(\Formularium\Model $m, array $elements, string $previousCompose): string |
||
| 24 | { |
||
| 25 | $data = []; |
||
| 26 | foreach ($m->getFields() as $name => $field) { |
||
| 27 | $data[$name] = $field->getDatatype()->getDefault(); |
||
| 28 | } |
||
| 29 | |||
| 30 | $editableForm = join('', $elements); |
||
| 31 | $editableForm = str_replace('"{this.handleInputChange}"', '{this.handleInputChange}', $editableForm); |
||
| 32 | $editableForm = preg_replace( |
||
| 33 | '/value="\{this.state.([a-zA-Z0-9_]+)\}"/', |
||
| 34 | 'value={this.state.$1}', |
||
| 35 | $editableForm |
||
| 36 | ); |
||
| 37 | |||
| 38 | $jsonData = json_encode($data); |
||
| 39 | |||
| 40 | $id = 'reactapp'; |
||
| 41 | $component = $m->getName() . 'Component'; |
||
| 42 | $reactCode = <<<EOF |
||
| 43 | 'use strict'; |
||
| 44 | |||
| 45 | const e = React.createElement; |
||
| 46 | |||
| 47 | class {$component} extends React.Component { |
||
| 48 | constructor(props) { |
||
| 49 | super(props); |
||
| 50 | this.state = $jsonData; |
||
| 51 | |||
| 52 | this.handleInputChange = this.handleInputChange.bind(this); |
||
| 53 | } |
||
| 54 | |||
| 55 | handleInputChange(event) { |
||
| 56 | const target = event.target; |
||
| 57 | const value = target.type === 'checkbox' ? target.checked : target.value; |
||
| 58 | const name = target.name; |
||
| 59 | |||
| 60 | this.setState({ |
||
| 61 | [name]: value |
||
| 62 | }); |
||
| 63 | } |
||
| 64 | |||
| 65 | render() { |
||
| 66 | return ( |
||
| 67 | <form> |
||
| 68 | $editableForm |
||
| 69 | </form> |
||
| 70 | ); |
||
| 71 | } |
||
| 72 | } |
||
| 73 | |||
| 74 | const domContainer = document.querySelector('#{$id}'); |
||
| 75 | ReactDOM.render(e($component), domContainer); |
||
| 76 | EOF; |
||
| 77 | |||
| 78 | $t = new HTMLElement('div', ['id' => $id]); |
||
| 79 | $s = new HTMLElement('script', ['type' => "text/babel"], $reactCode, true); |
||
| 80 | return HTMLElement::factory('', [], [$t, $s])->getRenderHTML(); |
||
| 81 | } |
||
| 83 |