1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Converter.php |
5
|
|
|
* |
6
|
|
|
* @date 29.03.2015 0:22:18 |
7
|
|
|
* @copyright Sklyarov Alexey <[email protected]> |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Sufir\Calc; |
11
|
|
|
|
12
|
|
|
use SplStack; |
13
|
|
|
use Sufir\Calc\Token\AbstractToken; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Converter |
17
|
|
|
* |
18
|
|
|
* Description of Converter |
19
|
|
|
* |
20
|
|
|
* @author Sklyarov Alexey <[email protected]> |
21
|
|
|
* @package Sufir\Calc |
22
|
|
|
*/ |
23
|
|
|
final class Converter |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* @param AbstractToken[] $tokens |
27
|
|
|
* @return AbstractToken[] |
28
|
|
|
*/ |
29
|
25 |
|
public function converToPostfix(array $tokens) |
30
|
|
|
{ |
31
|
25 |
|
$output = array(); |
32
|
25 |
|
$stack = new SplStack; |
33
|
|
|
|
34
|
25 |
|
foreach ($tokens as $token) { |
35
|
25 |
|
if ($token->isNumber() || $token->isVariable()) { |
36
|
25 |
|
$output[] = $token; |
37
|
|
|
|
38
|
25 |
|
} elseif ($token->isFunction()) { |
39
|
15 |
|
$stack->push($token); |
40
|
|
|
|
41
|
25 |
|
} elseif ($token->isBracket() && $token->isOpen()) { |
|
|
|
|
42
|
18 |
|
$stack->push($token); |
43
|
|
|
|
44
|
25 |
|
} elseif ($token->isDelimiter()) { |
45
|
|
|
|
46
|
6 |
|
while (!$stack->top()->isBracket()) { |
47
|
|
|
$output[] = $stack->pop(); |
48
|
|
|
} |
49
|
|
|
|
50
|
25 |
|
} elseif ($token->isBracket() && $token->isClose()) { |
|
|
|
|
51
|
|
|
|
52
|
18 |
|
while (!$stack->top()->isBracket()) { |
53
|
7 |
|
$output[] = $stack->pop(); |
54
|
7 |
|
} |
55
|
|
|
|
56
|
18 |
|
$stack->pop(); |
57
|
|
|
|
58
|
18 |
|
if (!$stack->isEmpty() && $stack->top()->isFunction()) { |
59
|
15 |
|
$output[] = $stack->pop(); |
60
|
15 |
|
} |
61
|
|
|
|
62
|
25 |
|
} elseif ($token->isOperator()) { |
63
|
|
|
/* @var $token \Sufir\Calc\Token\OperatorToken */ |
64
|
21 |
|
while (!$stack->isEmpty() && |
65
|
21 |
|
$stack->top()->isOperator() && |
66
|
17 |
|
(($token->isLeftAssoc() && $token->getPriority() <= $stack->top()->getPriority()) || |
67
|
11 |
|
($token->isRightAssoc() && $token->getPriority() < $stack->top()->getPriority())) |
68
|
21 |
|
) { |
69
|
13 |
|
$output[] = $stack->pop(); |
70
|
13 |
|
} |
71
|
|
|
|
72
|
21 |
|
$stack->push($token); |
73
|
21 |
|
} |
74
|
25 |
|
} |
75
|
|
|
|
76
|
25 |
|
while (!$stack->isEmpty()) { |
77
|
21 |
|
$output[] = $stack->pop(); |
78
|
21 |
|
} |
79
|
|
|
|
80
|
25 |
|
return $output; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
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 sub-classes 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 parent class: