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 Admin 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 Admin, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 26 | class Admin implements AdminInterface |
||
| 27 | { |
||
| 28 | use AdminTrait; |
||
| 29 | |||
| 30 | /** |
||
| 31 | * Entities collection. |
||
| 32 | * |
||
| 33 | * @var ArrayCollection |
||
| 34 | */ |
||
| 35 | protected $entities; |
||
| 36 | |||
| 37 | /** |
||
| 38 | * @var MessageHandlerInterface |
||
| 39 | */ |
||
| 40 | protected $messageHandler; |
||
| 41 | |||
| 42 | /** |
||
| 43 | * @var EntityManagerInterface |
||
| 44 | */ |
||
| 45 | protected $entityManager; |
||
| 46 | |||
| 47 | /** |
||
| 48 | * @var DataProviderInterface |
||
| 49 | */ |
||
| 50 | protected $dataProvider; |
||
| 51 | |||
| 52 | /** |
||
| 53 | * Admin configuration object |
||
| 54 | * |
||
| 55 | * @var AdminConfiguration |
||
| 56 | */ |
||
| 57 | protected $configuration; |
||
| 58 | |||
| 59 | /** |
||
| 60 | * Admin configured actions |
||
| 61 | * |
||
| 62 | * @var ActionInterface[] |
||
| 63 | */ |
||
| 64 | protected $actions = []; |
||
| 65 | |||
| 66 | /** |
||
| 67 | * Admin current action. It will be set after calling the handleRequest() |
||
| 68 | * |
||
| 69 | * @var ActionInterface |
||
| 70 | */ |
||
| 71 | protected $currentAction; |
||
| 72 | |||
| 73 | /** |
||
| 74 | * Admin name |
||
| 75 | * |
||
| 76 | * @var string |
||
| 77 | */ |
||
| 78 | protected $name; |
||
| 79 | |||
| 80 | /** |
||
| 81 | * Admin constructor. |
||
| 82 | * |
||
| 83 | * @param string $name |
||
| 84 | * @param DataProviderInterface $dataProvider |
||
| 85 | * @param AdminConfiguration $configuration |
||
| 86 | * @param MessageHandlerInterface $messageHandler |
||
| 87 | */ |
||
| 88 | 17 | public function __construct( |
|
| 89 | $name, |
||
| 90 | DataProviderInterface $dataProvider, |
||
| 91 | AdminConfiguration $configuration, |
||
| 92 | MessageHandlerInterface $messageHandler |
||
| 93 | ) { |
||
| 94 | 17 | $this->name = $name; |
|
| 95 | 17 | $this->dataProvider = $dataProvider; |
|
| 96 | 17 | $this->configuration = $configuration; |
|
| 97 | 17 | $this->messageHandler = $messageHandler; |
|
| 98 | 17 | $this->entities = new ArrayCollection(); |
|
| 99 | 17 | } |
|
| 100 | |||
| 101 | /** |
||
| 102 | * Load entities and set current action according to request |
||
| 103 | * |
||
| 104 | * @param Request $request |
||
| 105 | * @param null $user |
||
| 106 | * @return void |
||
| 107 | * @throws AdminException |
||
| 108 | */ |
||
| 109 | 5 | public function handleRequest(Request $request, $user = null) |
|
| 110 | { |
||
| 111 | // set current action |
||
| 112 | 5 | $this->currentAction = $this->getAction($request->get('_route_params')['_action']); |
|
| 113 | // check if user is logged have required permissions to get current action |
||
| 114 | 5 | $this->checkPermissions($user); |
|
| 115 | |||
| 116 | // criteria filter request |
||
| 117 | 5 | $filter = new RequestFilter($this->currentAction->getConfiguration()->getParameter('criteria')); |
|
| 118 | 5 | $criteriaFilter = $filter->filter($request); |
|
| 119 | |||
| 120 | // pager filter request |
||
| 121 | 5 | if ($this->currentAction->getConfiguration()->getParameter('pager') == 'pagerfanta') { |
|
| 122 | 5 | $filter = new PagerfantaFilter(); |
|
| 123 | 5 | $pagerFilter = $filter->filter($request); |
|
| 124 | } else { |
||
| 125 | // empty bag |
||
| 126 | $pagerFilter = new ParameterBag(); |
||
| 127 | } |
||
| 128 | |||
| 129 | // if load strategy is none, no entity should be loaded |
||
| 130 | 5 | if ($this->currentAction->getConfiguration()->getParameter('load_strategy') == Admin::LOAD_STRATEGY_NONE) { |
|
| 131 | 1 | return; |
|
| 132 | } |
||
| 133 | |||
| 134 | // load entities according to action and request |
||
| 135 | 5 | $this->load( |
|
| 136 | 5 | $criteriaFilter->all(), |
|
| 137 | 5 | $pagerFilter->get('order', []), |
|
| 138 | 5 | $this->configuration->getParameter('max_per_page'), |
|
| 139 | 5 | $pagerFilter->get('page', 1) |
|
| 140 | ); |
||
| 141 | 5 | } |
|
| 142 | |||
| 143 | /** |
||
| 144 | * Check if user is allowed to be here |
||
| 145 | * |
||
| 146 | * @param UserInterface|string $user |
||
| 147 | * @throws Exception |
||
| 148 | */ |
||
| 149 | 5 | public function checkPermissions($user) |
|
| 150 | { |
||
| 151 | 5 | if (!($user instanceof UserInterface)) { |
|
| 152 | 5 | return; |
|
| 153 | } |
||
| 154 | 1 | if ($this->currentAction === null) { |
|
| 155 | 1 | throw new Exception('Current action should be set before checking the permissions'); |
|
| 156 | } |
||
| 157 | 1 | $roles = $user->getRoles(); |
|
| 158 | $actionName = $this |
||
| 159 | 1 | ->getCurrentAction() |
|
| 160 | 1 | ->getName(); |
|
| 161 | |||
| 162 | 1 | if (!$this->isActionGranted($actionName, $roles)) { |
|
| 163 | 1 | $message = sprintf('User with roles %s not allowed for action "%s"', |
|
| 164 | 1 | implode(', ', $roles), |
|
| 165 | $actionName |
||
| 166 | ); |
||
| 167 | 1 | throw new NotFoundHttpException($message); |
|
| 168 | } |
||
| 169 | 1 | } |
|
| 170 | |||
| 171 | /** |
||
| 172 | * Create and return a new entity. |
||
| 173 | * |
||
| 174 | * @return object |
||
| 175 | */ |
||
| 176 | 3 | public function create() |
|
| 177 | { |
||
| 178 | // create an entity from the data provider |
||
| 179 | $entity = $this |
||
| 180 | 3 | ->dataProvider |
|
| 181 | 3 | ->create(); |
|
| 182 | |||
| 183 | // add it to the collection |
||
| 184 | $this |
||
| 185 | 3 | ->entities |
|
| 186 | 3 | ->add($entity); |
|
| 187 | |||
| 188 | 3 | return $entity; |
|
| 189 | } |
||
| 190 | |||
| 191 | /** |
||
| 192 | * Save entity via admin manager. Error are catch, logged and a flash message is added to session |
||
| 193 | * |
||
| 194 | * @return bool true if the entity was saved without errors |
||
| 195 | */ |
||
| 196 | 1 | View Code Duplication | public function save() |
| 197 | { |
||
| 198 | try { |
||
| 199 | 1 | foreach ($this->entities as $entity) { |
|
| 200 | $this |
||
| 201 | 1 | ->dataProvider |
|
| 202 | 1 | ->save($entity); |
|
| 203 | } |
||
| 204 | // inform user everything went fine |
||
| 205 | $this |
||
| 206 | 1 | ->messageHandler |
|
| 207 | 1 | ->handleSuccess('lag.admin.'.$this->name.'.saved'); |
|
| 208 | 1 | $success = true; |
|
| 209 | 1 | } catch (Exception $e) { |
|
| 210 | $this |
||
| 211 | 1 | ->messageHandler |
|
| 212 | 1 | ->handleError( |
|
| 213 | 1 | 'lag.admin.saved_errors', |
|
| 214 | 1 | "An error has occurred while saving an entity : {$e->getMessage()}, stackTrace: {$e->getTraceAsString()}" |
|
| 215 | ); |
||
| 216 | 1 | $success = false; |
|
| 217 | } |
||
| 218 | 1 | return $success; |
|
| 219 | } |
||
| 220 | |||
| 221 | /** |
||
| 222 | * Remove an entity with data provider |
||
| 223 | * |
||
| 224 | * @return bool true if the entity was saved without errors |
||
| 225 | */ |
||
| 226 | 1 | View Code Duplication | public function remove() |
| 227 | { |
||
| 228 | try { |
||
| 229 | 1 | foreach ($this->entities as $entity) { |
|
| 230 | $this |
||
| 231 | 1 | ->dataProvider |
|
| 232 | 1 | ->remove($entity); |
|
| 233 | } |
||
| 234 | // inform user everything went fine |
||
| 235 | $this |
||
| 236 | 1 | ->messageHandler |
|
| 237 | 1 | ->handleSuccess('lag.admin.'.$this->name.'.deleted'); |
|
| 238 | 1 | $success = true; |
|
| 239 | 1 | } catch (Exception $e) { |
|
| 240 | $this |
||
| 241 | 1 | ->messageHandler |
|
| 242 | 1 | ->handleError( |
|
| 243 | 1 | 'lag.admin.deleted_errors', |
|
| 244 | 1 | "An error has occurred while deleting an entity : {$e->getMessage()}, stackTrace: {$e->getTraceAsString()} " |
|
| 245 | ); |
||
| 246 | 1 | $success = false; |
|
| 247 | } |
||
| 248 | 1 | return $success; |
|
| 249 | } |
||
| 250 | |||
| 251 | /** |
||
| 252 | * Generate a route for admin and action name (like lag.admin.my_admin) |
||
| 253 | * |
||
| 254 | * @param $actionName |
||
| 255 | * |
||
| 256 | * @return string |
||
| 257 | * |
||
| 258 | * @throws Exception |
||
| 259 | */ |
||
| 260 | 8 | public function generateRouteName($actionName) |
|
| 261 | { |
||
| 262 | 8 | if (!array_key_exists($actionName, $this->getConfiguration()->getParameter('actions'))) { |
|
| 263 | 2 | throw new Exception( |
|
| 264 | 2 | sprintf('Invalid action name %s for admin %s (available action are: %s)', |
|
| 265 | $actionName, |
||
| 266 | 2 | $this->getName(), |
|
| 267 | 2 | implode(', ', $this->getActionNames())) |
|
| 268 | ); |
||
| 269 | } |
||
| 270 | // get routing name pattern |
||
| 271 | 8 | $routingPattern = $this->getConfiguration()->getParameter('routing_name_pattern'); |
|
| 272 | // replace admin and action name in pattern |
||
| 273 | 8 | $routeName = str_replace('{admin}', Container::underscore($this->getName()), $routingPattern); |
|
| 274 | 8 | $routeName = str_replace('{action}', $actionName, $routeName); |
|
| 275 | |||
| 276 | 8 | return $routeName; |
|
| 277 | } |
||
| 278 | |||
| 279 | /** |
||
| 280 | * Load entities manually according to criteria. |
||
| 281 | * |
||
| 282 | * @param array $criteria |
||
| 283 | * @param array $orderBy |
||
| 284 | * @param int $limit |
||
| 285 | * @param int $offset |
||
| 286 | * @throws Exception |
||
| 287 | */ |
||
| 288 | 5 | public function load(array $criteria, $orderBy = [], $limit = 25, $offset = 1) |
|
| 289 | { |
||
| 290 | $pager = $this |
||
| 291 | 5 | ->getCurrentAction() |
|
| 292 | 5 | ->getConfiguration() |
|
| 293 | 5 | ->getParameter('pager'); |
|
| 294 | |||
| 295 | 5 | if ($pager == 'pagerfanta') { |
|
| 296 | // adapter to pager fanta |
||
| 297 | 5 | $adapter = new PagerFantaAdminAdapter($this->dataProvider, $criteria, $orderBy); |
|
| 298 | // create pager |
||
| 299 | 5 | $this->pager = new Pagerfanta($adapter); |
|
| 300 | 5 | $this->pager->setMaxPerPage($limit); |
|
| 301 | 5 | $this->pager->setCurrentPage($offset); |
|
| 302 | |||
| 303 | $entities = $this |
||
| 304 | 5 | ->pager |
|
| 305 | 5 | ->getCurrentPageResults(); |
|
| 306 | } else { |
||
| 307 | $entities = $this |
||
| 308 | ->dataProvider |
||
| 309 | ->findBy($criteria, $orderBy, $limit, $offset); |
||
| 310 | } |
||
| 311 | 5 | if (!is_array($entities) && !($entities instanceof Collection)) { |
|
| 312 | 1 | throw new Exception('The data provider should return either a collection or an array. Got '.gettype($entities).' instead'); |
|
| 313 | } |
||
| 314 | |||
| 315 | 5 | if (is_array($entities)) { |
|
| 316 | 5 | $entities = new ArrayCollection($entities); |
|
| 317 | } |
||
| 318 | 5 | $this->entities = $entities; |
|
| 319 | 5 | } |
|
| 320 | |||
| 321 | /** |
||
| 322 | * Return loaded entities |
||
| 323 | * |
||
| 324 | * @return Collection |
||
| 325 | */ |
||
| 326 | 2 | public function getEntities() |
|
| 327 | { |
||
| 328 | 2 | return $this->entities; |
|
| 329 | } |
||
| 330 | |||
| 331 | /** |
||
| 332 | * Return entity for current admin. If entity does not exist, it throws an exception. |
||
| 333 | * |
||
| 334 | * @return mixed |
||
| 335 | * |
||
| 336 | * @throws Exception |
||
| 337 | */ |
||
| 338 | 1 | public function getUniqueEntity() |
|
| 339 | { |
||
| 340 | 1 | if ($this->entities->count() == 0) { |
|
| 341 | 1 | throw new Exception("Entity not found in admin \"{$this->getName()}\"."); |
|
| 342 | } |
||
| 343 | 1 | if ($this->entities->count() > 1) { |
|
| 344 | 1 | throw new Exception("Too much entities found in admin \"{$this->getName()}\"."); |
|
| 345 | } |
||
| 346 | 1 | return $this->entities->first(); |
|
| 347 | } |
||
| 348 | |||
| 349 | /** |
||
| 350 | * Return admin name |
||
| 351 | * |
||
| 352 | * @return string |
||
| 353 | */ |
||
| 354 | 14 | public function getName() |
|
| 358 | |||
| 359 | /** |
||
| 360 | * Return true if current action is granted for user. |
||
| 361 | * |
||
| 362 | * @param string $actionName Le plus grand de tous les héros |
||
| 363 | * @param array $roles |
||
| 364 | * |
||
| 365 | * @return bool |
||
| 366 | */ |
||
| 367 | 1 | public function isActionGranted($actionName, array $roles) |
|
| 368 | { |
||
| 369 | 1 | $isGranted = array_key_exists($actionName, $this->actions); |
|
| 370 | |||
| 371 | // if action exists |
||
| 372 | 1 | if ($isGranted) { |
|
| 373 | 1 | $isGranted = false; |
|
| 374 | /** @var ActionInterface $action */ |
||
| 375 | 1 | $action = $this->actions[$actionName]; |
|
| 376 | // checking roles permissions |
||
| 377 | 1 | foreach ($roles as $role) { |
|
| 378 | |||
| 379 | 1 | if ($role instanceof Role) { |
|
| 380 | $role = $role->getRole(); |
||
| 381 | } |
||
| 382 | 1 | if (in_array($role, $action->getPermissions())) { |
|
| 383 | 1 | $isGranted = true; |
|
| 384 | } |
||
| 385 | } |
||
| 386 | } |
||
| 387 | |||
| 388 | 1 | return $isGranted; |
|
| 389 | } |
||
| 390 | |||
| 391 | /** |
||
| 392 | * @return ActionInterface[] |
||
| 393 | */ |
||
| 394 | 6 | public function getActions() |
|
| 398 | |||
| 399 | /** |
||
| 400 | * @return integer[] |
||
| 401 | */ |
||
| 402 | 2 | public function getActionNames() |
|
| 403 | { |
||
| 404 | 2 | return array_keys($this->actions); |
|
| 405 | } |
||
| 406 | |||
| 407 | /** |
||
| 408 | * @param $name |
||
| 409 | * @return ActionInterface |
||
| 410 | * @throws Exception |
||
| 411 | */ |
||
| 412 | 5 | public function getAction($name) |
|
| 422 | |||
| 423 | /** |
||
| 424 | * Return if an action with specified name exists form this admin. |
||
| 425 | * |
||
| 426 | * @param $name |
||
| 427 | * @return bool |
||
| 428 | */ |
||
| 429 | public function hasAction($name) |
||
| 433 | |||
| 434 | /** |
||
| 435 | * @param ActionInterface $action |
||
| 436 | * @return void |
||
| 437 | */ |
||
| 438 | 12 | public function addAction(ActionInterface $action) |
|
| 442 | |||
| 443 | /** |
||
| 444 | * Return the current action or an exception if it is not set. |
||
| 445 | * |
||
| 446 | * @return ActionInterface |
||
| 447 | 5 | * @throws Exception |
|
| 448 | */ |
||
| 449 | 5 | public function getCurrentAction() |
|
| 460 | |||
| 461 | /** |
||
| 462 | * Return if the current action has been initialized and set. |
||
| 463 | * |
||
| 464 | 14 | * @return boolean |
|
| 465 | */ |
||
| 466 | 14 | public function isCurrentActionDefined() |
|
| 470 | |||
| 471 | /** |
||
| 472 | * Return admin configuration object |
||
| 473 | * |
||
| 474 | * @return AdminConfiguration |
||
| 475 | */ |
||
| 476 | public function getConfiguration() |
||
| 480 | } |
||
| 481 |