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:
Complex classes like ArticleInfoController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ArticleInfoController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
25 | class ArticleInfoController extends Controller |
||
26 | { |
||
27 | /** @var LabsHelper The Labs helper object. */ |
||
28 | private $lh; |
||
29 | /** @var mixed[] Information about the page in question. */ |
||
30 | private $pageInfo; |
||
31 | /** @var Edit[] All edits of the page. */ |
||
32 | private $pageHistory; |
||
33 | /** @var string The fully-qualified name of the revision table. */ |
||
34 | private $revisionTable; |
||
35 | /** @var Connection The projects' database connection. */ |
||
36 | protected $conn; |
||
37 | /** @var AutomatedEditsHelper The semi-automated edits helper. */ |
||
38 | protected $aeh; |
||
39 | /** @var PageviewsHelper The page-views helper. */ |
||
40 | protected $ph; |
||
41 | |||
42 | /** |
||
43 | * Override method to call ArticleInfoController::containerInitialized() when container set. |
||
44 | * @param ContainerInterface|null $container A ContainerInterface instance or null |
||
45 | */ |
||
46 | public function setContainer(ContainerInterface $container = null) |
||
47 | { |
||
48 | parent::setContainer($container); |
||
49 | $this->containerInitialized(); |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Perform some operations after controller initialized and container set. |
||
54 | */ |
||
55 | private function containerInitialized() |
||
56 | { |
||
57 | $this->lh = $this->get('app.labs_helper'); |
||
58 | $this->lh->checkEnabled('articleinfo'); |
||
59 | $this->conn = $this->getDoctrine()->getManager('replicas')->getConnection(); |
||
|
|||
60 | $this->ph = $this->get('app.pageviews_helper'); |
||
61 | $this->aeh = $this->get('app.automated_edits_helper'); |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * The search form. |
||
66 | * @Route("/articleinfo", name="articleinfo") |
||
67 | * @Route("/articleinfo", name="articleInfo") |
||
68 | * @Route("/articleinfo/", name="articleInfoSlash") |
||
69 | * @Route("/articleinfo/index.php", name="articleInfoIndexPhp") |
||
70 | * @Route("/articleinfo/{project}", name="ArticleInfoProject") |
||
71 | * @param Request $request The HTTP request. |
||
72 | * @return Response |
||
73 | */ |
||
74 | public function indexAction(Request $request) |
||
75 | { |
||
76 | $projectQuery = $request->query->get('project'); |
||
77 | $article = $request->query->get('article'); |
||
78 | |||
79 | if ($projectQuery != '' && $article != '') { |
||
80 | return $this->redirectToRoute('ArticleInfoResult', [ 'project'=>$projectQuery, 'article' => $article ]); |
||
81 | } elseif ($article != '') { |
||
82 | return $this->redirectToRoute('ArticleInfoProject', [ 'project'=>$projectQuery ]); |
||
83 | } |
||
84 | |||
85 | if ($projectQuery == '') { |
||
86 | $projectQuery = $this->container->getParameter('default_project'); |
||
87 | } |
||
88 | |||
89 | $project = ProjectRepository::getProject($projectQuery, $this->container); |
||
1 ignored issue
–
show
|
|||
90 | |||
91 | return $this->render('articleInfo/index.html.twig', [ |
||
92 | 'xtPage' => 'articleinfo', |
||
93 | 'xtPageTitle' => 'tool-articleinfo', |
||
94 | 'xtSubtitle' => 'tool-articleinfo-desc', |
||
95 | 'project' => $project, |
||
96 | ]); |
||
97 | } |
||
98 | |||
99 | /** |
||
100 | * Display the results. |
||
101 | * @Route("/articleinfo/{project}/{article}", name="ArticleInfoResult", requirements={"article"=".+"}) |
||
102 | * @param Request $request The HTTP request. |
||
103 | * @return Response |
||
104 | */ |
||
105 | public function resultAction(Request $request) |
||
106 | { |
||
107 | $projectQuery = $request->attributes->get('project'); |
||
108 | $project = ProjectRepository::getProject($projectQuery, $this->container); |
||
1 ignored issue
–
show
|
|||
109 | View Code Duplication | if (!$project->exists()) { |
|
110 | $this->addFlash('notice', ['invalid-project', $projectQuery]); |
||
111 | return $this->redirectToRoute('articleInfo'); |
||
112 | } |
||
113 | $projectUrl = $project->getUrl(); |
||
114 | $dbName = $project->getDatabaseName(); |
||
115 | |||
116 | $pageQuery = $request->attributes->get('article'); |
||
117 | $page = new Page($project, $pageQuery); |
||
118 | $pageRepo = new PagesRepository(); |
||
119 | $pageRepo->setContainer($this->container); |
||
1 ignored issue
–
show
|
|||
120 | $page->setRepository($pageRepo); |
||
121 | |||
122 | if (!$page->exists()) { |
||
123 | $this->addFlash('notice', ['no-exist', $pageQuery]); |
||
124 | return $this->redirectToRoute('articleInfo'); |
||
125 | } |
||
126 | |||
127 | $this->revisionTable = $project->getRepository()->getTableName( |
||
128 | $project->getDatabaseName(), |
||
129 | 'revision' |
||
130 | ); |
||
131 | |||
132 | // TODO: throw error if $basicInfo['missing'] is set |
||
1 ignored issue
–
show
|
|||
133 | |||
134 | $this->pageInfo = [ |
||
135 | 'project' => $project, |
||
136 | 'projectUrl' => $projectUrl, |
||
137 | 'page' => $page, |
||
138 | 'dbName' => $dbName, |
||
139 | 'lang' => $project->getLang(), |
||
140 | ]; |
||
141 | |||
142 | if ($page->getWikidataId()) { |
||
143 | $this->pageInfo['numWikidataItems'] = $this->getNumWikidataItems(); |
||
144 | } |
||
145 | |||
146 | // TODO: Adapted from legacy code; may be used to indicate how many dead ext links there are |
||
147 | // if ( isset( $basicInfo->extlinks ) ){ |
||
1 ignored issue
–
show
|
|||
148 | // foreach ( $basicInfo->extlinks as $i => $link ){ |
||
1 ignored issue
–
show
|
|||
149 | // $this->extLinks[] = array("link" => $link->{'*'}, "status" => "unchecked" ); |
||
1 ignored issue
–
show
|
|||
150 | // } |
||
151 | // } |
||
152 | |||
153 | $this->pageHistory = $page->getRevisions(); |
||
154 | $this->pageInfo['firstEdit'] = new Edit($this->pageInfo['page'], $this->pageHistory[0]); |
||
155 | $this->pageInfo['lastEdit'] = new Edit( |
||
156 | $this->pageInfo['page'], |
||
157 | $this->pageHistory[$page->getNumRevisions() - 1] |
||
158 | ); |
||
159 | |||
160 | // NOTE: bots are fetched first in case we want to restrict some stats to humans editors only |
||
161 | $this->pageInfo['bots'] = $this->getBotData(); |
||
162 | $this->pageInfo['general']['bot_count'] = count($this->pageInfo['bots']); |
||
163 | |||
164 | $this->pageInfo = array_merge($this->pageInfo, $this->parseHistory()); |
||
165 | $this->pageInfo['general']['top_ten_count'] = $this->getTopTenCount(); |
||
166 | $this->pageInfo['general']['top_ten_percentage'] = round( |
||
167 | ($this->pageInfo['general']['top_ten_count'] / $page->getNumRevisions()) * 100, |
||
168 | 1 |
||
169 | ); |
||
170 | $this->pageInfo = array_merge($this->pageInfo, $this->getLinksAndRedirects()); |
||
171 | $this->pageInfo['general']['pageviews_offset'] = 60; |
||
172 | $this->pageInfo['general']['pageviews'] = $this->ph->sumLastDays( |
||
173 | $this->pageInfo['project']->getDomain(), |
||
174 | $this->pageInfo['page']->getTitle(), |
||
175 | $this->pageInfo['general']['pageviews_offset'] |
||
176 | ); |
||
177 | $api = $this->get('app.api_helper'); |
||
178 | $assessments = $api->getPageAssessments($projectQuery, $pageQuery); |
||
179 | if ($assessments) { |
||
180 | $this->pageInfo['assessments'] = $assessments; |
||
181 | } |
||
182 | $this->setLogsEvents(); |
||
183 | |||
184 | $bugs = array_merge($this->getCheckWikiErrors(), $this->getWikidataErrors()); |
||
185 | if (!empty($bugs)) { |
||
186 | $this->pageInfo['bugs'] = $bugs; |
||
187 | } |
||
188 | |||
189 | $this->pageInfo['xtPage'] = 'articleinfo'; |
||
190 | $this->pageInfo['xtTitle'] = $this->pageInfo['page']->getTitle(); |
||
191 | |||
192 | return $this->render("articleInfo/result.html.twig", $this->pageInfo); |
||
193 | } |
||
194 | |||
195 | /** |
||
196 | * Get number of wikidata items (not just languages of sister projects) |
||
197 | * @return integer Number of items |
||
198 | */ |
||
199 | private function getNumWikidataItems() |
||
207 | |||
208 | /** |
||
209 | * Get info about bots that edited the page |
||
210 | * This also sets $this->pageInfo['bot_revision_count'] and $this->pageInfo['bot_percentage'] |
||
211 | * @return array Associative array containing the bot's username, edit count to the page |
||
212 | * and whether or not they are currently a bot |
||
213 | */ |
||
214 | private function getBotData() |
||
249 | |||
250 | /** |
||
251 | * Get the number of edits made to the page by the top 10% of editors |
||
252 | * This is ran *after* parseHistory() since we need the grand totals first. |
||
253 | * Various stats are also set for each editor in $this->pageInfo['editors'] |
||
254 | * and top ten editors are stored in $this->pageInfo['general']['top_ten'] |
||
255 | * to be used in the charts |
||
256 | * @return integer Number of edits |
||
257 | */ |
||
258 | private function getTopTenCount() |
||
326 | |||
327 | /** |
||
328 | * Get number of in and outgoing links and redirects to the page |
||
329 | * @return array Associative array containing counts |
||
330 | */ |
||
331 | private function getLinksAndRedirects() |
||
364 | |||
365 | /** |
||
366 | * Query for log events during each year of the article's history, |
||
367 | * and set the results in $this->pageInfo['year_count'] |
||
368 | */ |
||
369 | private function setLogsEvents() |
||
413 | |||
414 | /** |
||
415 | * Get any CheckWiki errors |
||
416 | * @return array Results from query |
||
417 | */ |
||
418 | private function getCheckWikiErrors() |
||
437 | |||
438 | /** |
||
439 | * Get basic wikidata on the page: label and description. |
||
440 | * Reported as "bugs" if they are missing. |
||
441 | * @return array Label and description, if present |
||
442 | */ |
||
443 | private function getWikidataErrors() |
||
501 | |||
502 | /** |
||
503 | * Get the size of the diff. |
||
504 | * @param int $revIndex The index of the revision within $this->pageHistory |
||
505 | * @return int Size of the diff |
||
506 | */ |
||
507 | private function getDiffSize($revIndex) |
||
525 | |||
526 | /** |
||
527 | * Parse the revision history, which should be at $this->pageHistory |
||
528 | * @return array Associative "master" array of metadata about the page |
||
529 | */ |
||
530 | private function parseHistory() |
||
780 | } |
||
781 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: