1

I have Cyclomatic Complexity issue with a switch case statement, so I need to refactor switch/case block of code.

I trying to create an array with keys and as value to set method call i.e $this->authChecker->isGranted(User::ROLE_ADMIN)

$attributeResolver = [
            self::OPEN_FORM => '$this->authChecker->isGranted(User::ROLE_USER)',
            self::CREATE => '$this->authChecker->isGranted(User::ROLE_ADMIN)',
            self::EDIT => '...',
            self::DISABLE => '...',
        ];

And for a call to use something like this,

return $attributeResolver[$attribute];

I want to store method call in the string to avoid unnecessary service calls.

Is this is posible?

Stevan Tosic
  • 6,561
  • 10
  • 55
  • 110
  • you want to treat a piece of string as PHP code, have a look [here](http://php.net/manual/en/function.eval.php) – jagad89 Dec 04 '18 at 12:08
  • I'm trying to understand what problem you're trying to solve? Do you have an example of your current switch/case code that you want to change and explain a bit more why you need to change it? – M. Eriksson Dec 04 '18 at 12:11
  • @MagnusEriksson I think your previous comment was perfect that you deleted. Edit: As per me, that should be accepted answer. – jagad89 Dec 04 '18 at 12:12
  • This looks like it would make a lot more sense as a map from your class constants directly to the User role constants, with a single call to the `isGranted` method when you actually resolve it. – iainn Dec 04 '18 at 12:13

1 Answers1

3

You thought of a solution and you are asking about that solution. This is called an XY problem which makes it hard to find an answer about the main problem. With current requirements (which may not be precise) you may want to re-construct the $attributeResolver as such:

$attributeResolver = [
    self::OPEN_FORM => User::ROLE_USER,
    self::CREATE => User::ROLE_ADMIN,
    .
    .
    .
];

and while returning do the call to the isGranted method as the following:

return $this->authChecker->isGranted($attributeResolver[$attribute]);
revo
  • 47,783
  • 14
  • 74
  • 117