| Conditions | 12 |
| Paths | 17 |
| Total Lines | 51 |
| Code Lines | 34 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 78 | public function calculate( |
||
| 79 | array $tokens, |
||
| 80 | array $variables, |
||
| 81 | ?callable $variableNotFoundHandler = null |
||
| 82 | ): mixed { |
||
| 83 | /** @var Token[] $stack */ |
||
| 84 | $stack = []; |
||
| 85 | foreach ($tokens as $token) { |
||
| 86 | if (in_array($token->getType(), [Token::LITERAL, Token::STRING])) { |
||
| 87 | $stack[] = $token; |
||
| 88 | } elseif (Token::VARIABLE === $token->getType()) { |
||
| 89 | $variable = $token->getValue(); |
||
| 90 | $value = null; |
||
| 91 | if (array_key_exists($variable, $variables)) { |
||
| 92 | $value = $variables[$variable]; |
||
| 93 | } elseif ($variableNotFoundHandler !== null) { |
||
| 94 | $value = call_user_func($variableNotFoundHandler, $variable); |
||
| 95 | } else { |
||
| 96 | throw new UnknownVariableException(sprintf( |
||
| 97 | 'Unknown variable [%s]', |
||
| 98 | $variable |
||
| 99 | )); |
||
| 100 | } |
||
| 101 | $stack[] = new Token(Token::LITERAL, $value, $variable); |
||
| 102 | } elseif (Token::FUNCTION === $token->getType()) { |
||
| 103 | if (! array_key_exists($token->getValue(), $this->functions)) { |
||
| 104 | throw new UnknownFunctionException(sprintf( |
||
| 105 | 'Unknown function [%s]', |
||
| 106 | $token->getValue() |
||
| 107 | )); |
||
| 108 | } |
||
| 109 | $stack[] = $this->functions[$token->getValue()]->execute( |
||
| 110 | $stack, |
||
| 111 | $token->getParamCount() |
||
| 112 | ); |
||
| 113 | } elseif (Token::OPERATOR === $token->getType()) { |
||
| 114 | if (! array_key_exists($token->getValue(), $this->operators)) { |
||
| 115 | throw new UnknownOperatorException(sprintf( |
||
| 116 | 'Unknown operator [%s]', |
||
| 117 | $token->getValue() |
||
| 118 | )); |
||
| 119 | } |
||
| 120 | $stack[] = $this->operators[$token->getValue()]->execute($stack); |
||
| 121 | } |
||
| 122 | } |
||
| 123 | $result = array_pop($stack); |
||
| 124 | if ($result === null || count($stack) > 0) { |
||
| 125 | throw new IncorrectExpressionException('Expression stack is not empty'); |
||
| 126 | } |
||
| 127 | |||
| 128 | return $result->getValue(); |
||
| 129 | } |
||
| 149 |