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 |
||
| 25 | class Admin implements AdminInterface |
||
| 26 | { |
||
| 27 | use AdminTrait; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * Entities collection. |
||
| 31 | * |
||
| 32 | * @var ArrayCollection |
||
| 33 | */ |
||
| 34 | protected $entities; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @var MessageHandlerInterface |
||
| 38 | */ |
||
| 39 | protected $messageHandler; |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @var EntityManagerInterface |
||
| 43 | */ |
||
| 44 | protected $entityManager; |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @var DataProviderInterface |
||
| 48 | */ |
||
| 49 | protected $dataProvider; |
||
| 50 | |||
| 51 | /** |
||
| 52 | * Admin configuration object |
||
| 53 | * |
||
| 54 | * @var AdminConfiguration |
||
| 55 | */ |
||
| 56 | protected $configuration; |
||
| 57 | |||
| 58 | /** |
||
| 59 | * Admin configured actions |
||
| 60 | * |
||
| 61 | * @var ActionInterface[] |
||
| 62 | */ |
||
| 63 | protected $actions = []; |
||
| 64 | |||
| 65 | /** |
||
| 66 | * Admin current action. It will be set after calling the handleRequest() |
||
| 67 | * |
||
| 68 | * @var ActionInterface |
||
| 69 | */ |
||
| 70 | protected $currentAction; |
||
| 71 | |||
| 72 | /** |
||
| 73 | * Admin name |
||
| 74 | * |
||
| 75 | * @var string |
||
| 76 | */ |
||
| 77 | protected $name; |
||
| 78 | |||
| 79 | /** |
||
| 80 | * @var EventDispatcherInterface |
||
| 81 | */ |
||
| 82 | protected $eventDispatcher; |
||
| 83 | |||
| 84 | /** |
||
| 85 | * @var RequestFilterInterface |
||
| 86 | */ |
||
| 87 | protected $requestFilter; |
||
| 88 | |||
| 89 | /** |
||
| 90 | * Admin constructor. |
||
| 91 | * |
||
| 92 | * @param string $name |
||
| 93 | * @param DataProviderInterface $dataProvider |
||
| 94 | * @param AdminConfiguration $configuration |
||
| 95 | 27 | * @param MessageHandlerInterface $messageHandler |
|
| 96 | * @param EventDispatcherInterface $eventDispatcher |
||
| 97 | * @param RequestFilterInterface $requestFilter |
||
| 98 | */ |
||
| 99 | public function __construct( |
||
| 115 | |||
| 116 | /** |
||
| 117 | * Load entities and set current action according to request. |
||
| 118 | 9 | * |
|
| 119 | * @param Request $request |
||
| 120 | * @param null $user |
||
| 121 | 9 | * @return void |
|
| 122 | * @throws AdminException |
||
| 123 | 9 | */ |
|
| 124 | public function handleRequest(Request $request, $user = null) |
||
| 158 | 9 | ||
| 159 | /** |
||
| 160 | 9 | * Check if user is allowed to be here |
|
| 161 | 9 | * |
|
| 162 | * @param UserInterface|string $user |
||
| 163 | 1 | * @throws Exception |
|
| 164 | 1 | */ |
|
| 165 | public function checkPermissions($user) |
||
| 197 | |||
| 198 | /** |
||
| 199 | 5 | * Create and return a new entity. |
|
| 200 | * |
||
| 201 | 5 | * @return object |
|
| 202 | */ |
||
| 203 | public function create() |
||
| 204 | 5 | { |
|
| 205 | // create an entity from the data provider |
||
| 206 | 5 | $entity = $this |
|
| 207 | ->dataProvider |
||
| 208 | 5 | ->create(); |
|
| 209 | |||
| 210 | // add it to the collection |
||
| 211 | $this |
||
| 212 | ->entities |
||
| 213 | ->add($entity); |
||
| 214 | |||
| 215 | return $entity; |
||
| 216 | 2 | } |
|
| 217 | |||
| 218 | /** |
||
| 219 | 2 | * Save entity via admin manager. Error are catch, logged and a flash message is added to session |
|
| 220 | 2 | * |
|
| 221 | * @return bool true if the entity was saved without errors |
||
| 222 | 2 | */ |
|
| 223 | 1 | View Code Duplication | public function save() |
| 224 | { |
||
| 225 | 1 | try { |
|
| 226 | foreach ($this->entities as $entity) { |
||
| 227 | 1 | $this |
|
| 228 | 1 | ->dataProvider |
|
| 229 | 2 | ->save($entity); |
|
| 230 | 1 | } |
|
| 231 | // inform the user that the entity is saved |
||
| 232 | 1 | $this |
|
| 233 | 1 | ->messageHandler |
|
| 234 | 1 | ->handleSuccess($this->generateMessageTranslationKey('saved')); |
|
| 235 | 1 | $success = true; |
|
| 236 | 1 | } catch (Exception $e) { |
|
| 237 | $this |
||
| 238 | 2 | ->messageHandler |
|
| 239 | ->handleError( |
||
| 240 | $this->generateMessageTranslationKey('lag.admin.saved_errors'), |
||
| 241 | "An error has occurred while saving an entity : {$e->getMessage()}, stackTrace: {$e->getTraceAsString()}" |
||
| 242 | ); |
||
| 243 | $success = false; |
||
| 244 | } |
||
| 245 | return $success; |
||
| 246 | 2 | } |
|
| 247 | |||
| 248 | /** |
||
| 249 | 2 | * Remove an entity with data provider |
|
| 250 | 2 | * |
|
| 251 | * @return bool true if the entity was saved without errors |
||
| 252 | 2 | */ |
|
| 253 | 1 | View Code Duplication | public function remove() |
| 254 | { |
||
| 255 | 1 | try { |
|
| 256 | foreach ($this->entities as $entity) { |
||
| 257 | 1 | $this |
|
| 258 | 1 | ->dataProvider |
|
| 259 | 2 | ->remove($entity); |
|
| 260 | 1 | } |
|
| 261 | // inform the user that the entity is removed |
||
| 262 | 1 | $this |
|
| 263 | 1 | ->messageHandler |
|
| 264 | 1 | ->handleSuccess($this->generateMessageTranslationKey('deleted')); |
|
| 265 | 1 | $success = true; |
|
| 266 | 1 | } catch (Exception $e) { |
|
| 267 | $this |
||
| 268 | 2 | ->messageHandler |
|
| 269 | ->handleError( |
||
| 270 | $this->generateMessageTranslationKey('lag.admin.deleted_errors'), |
||
| 271 | "An error has occurred while deleting an entity : {$e->getMessage()}, stackTrace: {$e->getTraceAsString()} " |
||
| 272 | ); |
||
| 273 | $success = false; |
||
| 274 | } |
||
| 275 | return $success; |
||
| 276 | } |
||
| 277 | |||
| 278 | /** |
||
| 279 | * Generate a route for admin and action name (like lag.admin.my_admin) |
||
| 280 | 16 | * |
|
| 281 | * @param $actionName |
||
| 282 | 16 | * |
|
| 283 | 2 | * @return string |
|
| 284 | 2 | * |
|
| 285 | 2 | * @throws Exception |
|
| 286 | 2 | */ |
|
| 287 | 2 | public function generateRouteName($actionName) |
|
| 288 | 2 | { |
|
| 289 | if (!array_key_exists($actionName, $this->getConfiguration()->getParameter('actions'))) { |
||
| 290 | throw new Exception( |
||
| 291 | 15 | sprintf('Invalid action name %s for admin %s (available action are: %s)', |
|
| 292 | $actionName, |
||
| 293 | 15 | $this->getName(), |
|
| 294 | 15 | implode(', ', $this->getActionNames())) |
|
| 295 | ); |
||
| 296 | 15 | } |
|
| 297 | // get routing name pattern |
||
| 298 | $routingPattern = $this->getConfiguration()->getParameter('routing_name_pattern'); |
||
| 299 | // replace admin and action name in pattern |
||
| 300 | $routeName = str_replace('{admin}', Container::underscore($this->getName()), $routingPattern); |
||
| 301 | $routeName = str_replace('{action}', $actionName, $routeName); |
||
| 302 | |||
| 303 | return $routeName; |
||
| 304 | } |
||
| 305 | |||
| 306 | /** |
||
| 307 | * Load entities manually according to criteria. |
||
| 308 | 9 | * |
|
| 309 | * @param array $criteria |
||
| 310 | 9 | * @param array $orderBy |
|
| 311 | 9 | * @param int $limit |
|
| 312 | 9 | * @param int $offset |
|
| 313 | 9 | * @throws Exception |
|
| 314 | 9 | */ |
|
| 315 | 9 | public function load(array $criteria, $orderBy = [], $limit = 25, $offset = 1) |
|
| 316 | 9 | { |
|
| 317 | $actionConfiguration = $this |
||
| 318 | 9 | ->getCurrentAction() |
|
| 319 | ->getConfiguration(); |
||
| 320 | 1 | $pager = $actionConfiguration->getParameter('pager'); |
|
| 321 | $requirePagination = $this |
||
| 322 | 1 | ->getCurrentAction() |
|
| 323 | 1 | ->isPaginationRequired(); |
|
| 324 | 1 | ||
| 325 | if ($pager == 'pagerfanta' && $requirePagination) { |
||
| 326 | 1 | // adapter to pagerfanta |
|
| 327 | $adapter = new PagerFantaAdminAdapter($this->dataProvider, $criteria, $orderBy); |
||
| 328 | 1 | // create pager |
|
| 329 | 1 | $this->pager = new Pagerfanta($adapter); |
|
| 330 | $this->pager->setMaxPerPage($limit); |
||
| 331 | 8 | $this->pager->setCurrentPage($offset); |
|
| 332 | 7 | ||
| 333 | 7 | $entities = $this |
|
| 334 | 8 | ->pager |
|
| 335 | ->getCurrentPageResults(); |
||
| 336 | 8 | } else { |
|
| 337 | // if the current action should retrieve only one entity, the offset should be zero |
||
| 338 | 9 | if ($actionConfiguration->getParameter('load_strategy') !== AdminInterface::LOAD_STRATEGY_MULTIPLE) { |
|
| 339 | 1 | $offset = 0; |
|
| 340 | } |
||
| 341 | $entities = $this |
||
| 342 | 8 | ->dataProvider |
|
| 343 | 8 | ->findBy($criteria, $orderBy, $limit, $offset); |
|
| 344 | 8 | } |
|
| 345 | 8 | if (!is_array($entities) && !($entities instanceof Collection)) { |
|
| 346 | 8 | throw new Exception('The data provider should return either a collection or an array. Got '.gettype($entities).' instead'); |
|
| 347 | } |
||
| 348 | |||
| 349 | if (is_array($entities)) { |
||
| 350 | $entities = new ArrayCollection($entities); |
||
| 351 | } |
||
| 352 | $this->entities = $entities; |
||
| 353 | 2 | } |
|
| 354 | |||
| 355 | 2 | /** |
|
| 356 | * Return loaded entities |
||
| 357 | * |
||
| 358 | * @return Collection |
||
| 359 | */ |
||
| 360 | public function getEntities() |
||
| 361 | { |
||
| 362 | return $this->entities; |
||
| 363 | } |
||
| 364 | |||
| 365 | 1 | /** |
|
| 366 | * Return entity for current admin. If entity does not exist, it throws an exception. |
||
| 367 | 1 | * |
|
| 368 | 1 | * @return mixed |
|
| 369 | * |
||
| 370 | 1 | * @throws Exception |
|
| 371 | 1 | */ |
|
| 372 | public function getUniqueEntity() |
||
| 373 | 1 | { |
|
| 374 | if ($this->entities->count() == 0) { |
||
| 375 | throw new Exception("Entity not found in admin \"{$this->getName()}\"."); |
||
| 376 | } |
||
| 377 | if ($this->entities->count() > 1) { |
||
| 378 | throw new Exception("Too much entities found in admin \"{$this->getName()}\"."); |
||
| 379 | } |
||
| 380 | return $this->entities->first(); |
||
| 381 | 20 | } |
|
| 382 | |||
| 383 | 20 | /** |
|
| 384 | * Return admin name |
||
| 385 | * |
||
| 386 | * @return string |
||
| 387 | */ |
||
| 388 | public function getName() |
||
| 389 | { |
||
| 390 | return $this->name; |
||
| 391 | } |
||
| 392 | |||
| 393 | /** |
||
| 394 | 2 | * Return true if current action is granted for user. |
|
| 395 | * |
||
| 396 | 2 | * @param string $actionName Le plus grand de tous les héros |
|
| 397 | * @param array $roles |
||
| 398 | * |
||
| 399 | 2 | * @return bool |
|
| 400 | 2 | */ |
|
| 401 | public function isActionGranted($actionName, array $roles) |
||
| 402 | 2 | { |
|
| 403 | $isGranted = array_key_exists($actionName, $this->actions); |
||
| 404 | 2 | ||
| 405 | // if action exists |
||
| 406 | 2 | if ($isGranted) { |
|
| 407 | 2 | $isGranted = false; |
|
| 408 | 2 | /** @var ActionInterface $action */ |
|
| 409 | 2 | $action = $this->actions[$actionName]; |
|
| 410 | 2 | // checking roles permissions |
|
| 411 | 2 | foreach ($roles as $role) { |
|
| 412 | 2 | ||
| 413 | 2 | if ($role instanceof Role) { |
|
| 414 | $role = $role->getRole(); |
||
| 415 | 2 | } |
|
| 416 | if (in_array($role, $action->getPermissions())) { |
||
| 417 | $isGranted = true; |
||
| 418 | } |
||
| 419 | } |
||
| 420 | } |
||
| 421 | 10 | ||
| 422 | return $isGranted; |
||
| 423 | 10 | } |
|
| 424 | |||
| 425 | /** |
||
| 426 | * @return ActionInterface[] |
||
| 427 | */ |
||
| 428 | public function getActions() |
||
| 429 | 2 | { |
|
| 430 | return $this->actions; |
||
| 431 | 2 | } |
|
| 432 | |||
| 433 | /** |
||
| 434 | * @return integer[] |
||
| 435 | */ |
||
| 436 | public function getActionNames() |
||
| 440 | |||
| 441 | 9 | /** |
|
| 442 | 1 | * @param $name |
|
| 443 | 1 | * @return ActionInterface |
|
| 444 | 1 | * @throws Exception |
|
| 445 | */ |
||
| 446 | public function getAction($name) |
||
| 447 | 9 | { |
|
| 448 | if (!array_key_exists($name, $this->getActions())) { |
||
| 449 | throw new Exception( |
||
| 450 | "Invalid action name \"{$name}\" for admin '{$this->getName()}'. Check your configuration" |
||
| 451 | ); |
||
| 452 | } |
||
| 453 | |||
| 454 | return $this->actions[$name]; |
||
| 455 | } |
||
| 456 | 1 | ||
| 457 | /** |
||
| 458 | 1 | * Return if an action with specified name exists form this admin. |
|
| 459 | * |
||
| 460 | * @param $name |
||
| 461 | * @return bool |
||
| 462 | */ |
||
| 463 | public function hasAction($name) |
||
| 467 | 15 | ||
| 468 | 15 | /** |
|
| 469 | * @param ActionInterface $action |
||
| 470 | * @return void |
||
| 471 | */ |
||
| 472 | public function addAction(ActionInterface $action) |
||
| 473 | { |
||
| 474 | $this->actions[$action->getName()] = $action; |
||
| 475 | } |
||
| 476 | 10 | ||
| 477 | /** |
||
| 478 | 10 | * Return the current action or an exception if it is not set. |
|
| 479 | * |
||
| 480 | 1 | * @return ActionInterface |
|
| 481 | * @throws Exception |
||
| 482 | 1 | */ |
|
| 483 | public function getCurrentAction() |
||
| 484 | { |
||
| 485 | 9 | if ($this->currentAction === null) { |
|
| 486 | // current action should be defined |
||
| 487 | throw new Exception( |
||
| 488 | 'Current action is null. You should initialize it (with handleRequest method for example)' |
||
| 489 | ); |
||
| 490 | } |
||
| 491 | |||
| 492 | return $this->currentAction; |
||
| 493 | 1 | } |
|
| 494 | |||
| 495 | 1 | /** |
|
| 496 | * Return if the current action has been initialized and set. |
||
| 497 | * |
||
| 498 | * @return boolean |
||
| 499 | */ |
||
| 500 | public function isCurrentActionDefined() |
||
| 504 | |||
| 505 | 20 | /** |
|
| 506 | * Return admin configuration object. |
||
| 507 | * |
||
| 508 | * @return AdminConfiguration |
||
| 509 | */ |
||
| 510 | public function getConfiguration() |
||
| 511 | { |
||
| 512 | return $this->configuration; |
||
| 513 | } |
||
| 514 | 4 | ||
| 515 | /** |
||
| 516 | 4 | * Return a translation key for a message according to the Admin's translation pattern. |
|
| 517 | 4 | * |
|
| 518 | 4 | * @param string $message |
|
| 519 | 4 | * @return string |
|
| 520 | 4 | */ |
|
| 521 | protected function generateMessageTranslationKey($message) |
||
| 529 | } |
||
| 530 |