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 |
||
| 18 | class TwigExtension extends \Twig_Extension |
||
| 19 | { |
||
| 20 | private $filters = []; |
||
| 21 | private $functions = []; |
||
| 22 | private $markupManager; |
||
| 23 | |||
| 24 | 54 | public function __construct(MarkupEngineManager $manager) |
|
| 28 | |||
| 29 | public function __call($name, $arguments) |
||
| 40 | |||
| 41 | public function parseMarkup($content, $tag) |
||
| 45 | |||
| 46 | 18 | View Code Duplication | public function addFilters(/*iterable*/ $filters) |
| 59 | |||
| 60 | View Code Duplication | public function addFunctions(/*iterable*/ $functions) |
|
| 73 | |||
| 74 | public function getFilters() |
||
| 75 | { |
||
| 76 | $filters = $this->filters; |
||
| 77 | |||
| 78 | foreach ($this->markupManager->getTemplateTags() as $tag) |
||
| 79 | { |
||
| 80 | // Since we can't pass what tag/markup language we're using to the callable, let's make the callable to a |
||
| 81 | // non-existent method that will be handled by __call() |
||
| 82 | $filters[] = new \Twig_SimpleFilter( |
||
| 83 | $tag, |
||
| 84 | [$this, 'parseMarkup' . ucfirst($tag)], |
||
| 85 | ['is_safe' => ['html']] |
||
| 86 | ); |
||
| 87 | } |
||
| 88 | |||
| 89 | return $filters; |
||
| 90 | } |
||
| 91 | |||
| 92 | public function getFunctions() |
||
| 93 | { |
||
| 94 | return $this->functions; |
||
| 95 | } |
||
| 96 | |||
| 97 | public function getTokenParsers() |
||
| 98 | { |
||
| 99 | $tokenParsers = []; |
||
| 100 | |||
| 101 | foreach ($this->markupManager->getTemplateTags() as $tag) |
||
| 102 | { |
||
| 103 | $tokenParsers[] = new TokenParser($tag); |
||
| 104 | } |
||
| 105 | |||
| 106 | return $tokenParsers; |
||
| 107 | } |
||
| 108 | |||
| 109 | 54 | public function getName() |
|
| 113 | } |
||
| 114 |
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@returnannotation as described here.