Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 13 | class Link extends StringField implements EntityFieldInterface, TwigFieldInterface |
||
| 14 | { |
||
| 15 | /** |
||
| 16 | * @var Object |
||
| 17 | */ |
||
| 18 | protected $entity; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * Render link template filled with configured options. |
||
| 22 | * |
||
| 23 | * @param mixed $value |
||
| 24 | * @return string |
||
| 25 | */ |
||
| 26 | 2 | public function render($value) |
|
| 27 | { |
||
| 28 | 2 | $text = $this->options->get('text') ?: parent::render($value); |
|
| 29 | 2 | $parameters = []; |
|
| 30 | 2 | $accessor = PropertyAccess::createPropertyAccessor(); |
|
| 31 | |||
| 32 | 2 | foreach ($this->options->get('parameters') as $parameterName => $fieldName) { |
|
| 33 | 1 | if (!$fieldName) { |
|
| 34 | 1 | $fieldName = $parameterName; |
|
| 35 | } |
||
| 36 | 1 | $parameters[$parameterName] = $accessor->getValue($this->entity, $fieldName); |
|
| 37 | } |
||
| 38 | |||
| 39 | 2 | $render = $this->twig->render($this->options->get('template'), [ |
|
| 40 | 2 | 'text' => $text, |
|
| 41 | 2 | 'route' => $this->options->get('route'), |
|
| 42 | 2 | 'parameters' => $parameters, |
|
| 43 | 2 | 'target' => $this->options->get('target'), |
|
| 44 | 2 | 'url' => $this->options->get('url'), |
|
| 45 | 2 | 'title' => $this->options->get('title'), |
|
| 46 | 2 | 'icon' => $this->options->get('icon'), |
|
| 47 | ]); |
||
| 48 | |||
| 49 | 2 | return $render; |
|
| 50 | } |
||
| 51 | |||
| 52 | /** |
||
| 53 | * Configure options resolver. |
||
| 54 | * |
||
| 55 | * @param OptionsResolver $resolver |
||
| 56 | * @return void |
||
| 57 | */ |
||
| 58 | 2 | public function configureOptions(OptionsResolver $resolver) |
|
| 106 | |||
| 107 | /** |
||
| 108 | * Define field type. |
||
| 109 | * |
||
| 110 | * @return string |
||
| 111 | */ |
||
| 112 | public function getType() |
||
| 116 | |||
| 117 | /** |
||
| 118 | * Define entity. It will be use to fill parameters with properties values. |
||
| 119 | * |
||
| 120 | * @param $entity |
||
| 121 | */ |
||
| 122 | 1 | public function setEntity($entity) |
|
| 126 | } |
||
| 127 |