Completed
Push — master ( 2a128c...18787f )
by Alexey
02:20
created

Converter   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 94.59%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 21
c 2
b 0
f 0
lcom 0
cbo 2
dl 0
loc 71
ccs 35
cts 37
cp 0.9459
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C converToPostfix() 0 64 21
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 5
    public function converToPostfix(array $tokens)
30
    {
31 5
        $output = array();
32 5
        $stack = new SplStack;
33
34
        // Пока есть ещё токены для чтения - читаем очередной токен
35 5
        foreach ($tokens as $token) {
36
            // Если токен является числом, добавляем его к выходной строке
37 5
            if ($token->isNumber()) {
38 5
                $output[] = $token;
39
            // Если токен является функцией, помещаем его в стек
40 5
            } elseif ($token->isFunction()) {
41 4
                $stack->push($token);
42
            // Если токен является открывающей скобкой, помещаем его в стек
43 5
            } elseif ($token->isBracket() && $token->isOpen()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Sufir\Calc\Token\AbstractToken as the method isOpen() does only exist in the following sub-classes of Sufir\Calc\Token\AbstractToken: Sufir\Calc\Token\BracketToken. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

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

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
44 4
                $stack->push($token);
45
            // Если токен - разделитель аргументов функции
46 5
            } elseif ($token->isDelimiter()) {
47
                // До тех пор, пока верхним элементом стека не станет открывающая скобка,
48
                // выталкиваем элементы из стека в выход
49 2
                while (!$stack->top()->isBracket()) {
50
                    $output[] = $stack->pop();
51
                }
52
53
            // Если токен является закрывающей скобкой
54 5
            } elseif ($token->isBracket() && $token->isClose()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Sufir\Calc\Token\AbstractToken as the method isClose() does only exist in the following sub-classes of Sufir\Calc\Token\AbstractToken: Sufir\Calc\Token\BracketToken. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

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

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
55
                // До тех пор, пока верхним элементом стека не станет открывающая скобка,
56
                // выталкиваем элементы из стека в выход
57 4
                while (!$stack->top()->isBracket()) {
58 2
                    $output[] = $stack->pop();
59 2
                }
60
61
                // При этом открывающая скобка удаляется из стека, но в выходную строку не добавляется
62 4
                $stack->pop();
63
64
                // Если после этого шага на вершине стека оказывается токен функции, выталкиваем его в выход
65 4
                if (!$stack->isEmpty() && $stack->top()->isFunction()) {
66 4
                    $output[] = $stack->pop();
67 4
                }
68
69
            // Если токен - оператор, выталкиваем верхние элементы стека в выход,
70
            // пока верхним элементом является оператор
71 5
            } elseif ($token->isOperator()) {
72
                /* @var $token \Sufir\Calc\Token\OperatorToken */
73 4
                while (!$stack->isEmpty() &&
74 4
                    $stack->top()->isOperator() &&
75 2
                    (($token->isLeftAssoc() && $token->getPriority() <= $stack->top()->getPriority()) ||
76 2
                    ($token->isRightAssoc() && $token->getPriority() < $stack->top()->getPriority()))
77 4
                ) {
78 2
                    $output[] = $stack->pop();
79 2
                }
80
81
                // помещаем оператор в стек
82 4
                $stack->push($token);
83 4
            }
84 5
        }
85
86
        // выталкиваем все оставшиеся элементы из стека в выход
87 5
        while (!$stack->isEmpty()) {
88 4
            $output[] = $stack->pop();
89 4
        }
90
91 5
        return $output;
92
    }
93
}
94