GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 05dd66...ce9b2d )
by
unknown
03:03
created

ExpressionLanguage::evaluate()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
rs 6.6037
cc 8
eloc 15
nc 5
nop 2
1
<?php
2
/**
3
 * See class comment
4
 *
5
 * PHP Version 5
6
 *
7
 * @category   Netresearch
8
 * @package    Netresearch\Kite
9
 * @subpackage ExpressionLanguage
10
 * @author     Christian Opitz <[email protected]>
11
 * @license    http://www.netresearch.de Netresearch Copyright
12
 * @link       http://www.netresearch.de
13
 */
14
15
namespace Netresearch\Kite\ExpressionLanguage;
16
use Netresearch\Kite\Task;
17
18
use Symfony\Component\Console\Question\ChoiceQuestion;
19
use Symfony\Component\Console\Question\ConfirmationQuestion;
20
use Symfony\Component\Console\Question\Question;
21
use Symfony\Component\ExpressionLanguage\ParserCache\ParserCacheInterface;
22
23
/**
24
 * Extension of Symfonies expression language to inject our custom
25
 * lexer and register some functions
26
 *
27
 * @category   Netresearch
28
 * @package    Netresearch\Kite
29
 * @subpackage ExpressionLanguage
30
 * @author     Christian Opitz <[email protected]>
31
 * @license    http://www.netresearch.de Netresearch Copyright
32
 * @link       http://www.netresearch.de
33
 */
34
class ExpressionLanguage extends \Symfony\Component\ExpressionLanguage\ExpressionLanguage
35
{
36
    /**
37
     * @var array
38
     */
39
    protected $expressionResults = [];
40
41
    /**
42
     * @var string
43
     */
44
    const VARIABLES_KEY = 'variables';
45
46
    /**
47
     * ExpressionLanguage constructor.
48
     *
49
     * @param ParserCacheInterface|null $cache     The cache
50
     * @param array                     $providers Providers
51
     */
52
    public function __construct(ParserCacheInterface $cache = null, array $providers = array())
53
    {
54
        parent::__construct($cache, $providers);
55
56
        $reflectionProperty = new \ReflectionProperty('\Symfony\Component\ExpressionLanguage\ExpressionLanguage', 'lexer');
57
        $reflectionProperty->setAccessible(true);
58
        $reflectionProperty->setValue($this, new Lexer());
59
    }
60
61
    /**
62
     * Reevaluate parents evaluation results as expressions could be nested
63
     *
64
     * Don't parse expression strings which were the final result of an evaluation
65
     * ( As for example, given a variable "char" that is "\{",
66
     *   the result of "{char}" would be "{". Reevaluating this is 1. not intended
67
     *   and would 2. lead to an error )
68
     *
69
     * @param string|\Symfony\Component\ExpressionLanguage\Expression $expression The expression
70
     * @param array                                                   $values     The values
71
     *
72
     * @return string|mixed
73
     */
74
    public function evaluate($expression, $values = [])
75
    {
76
        if (is_string($expression)
77
            && !in_array($expression, $this->expressionResults, true)
78
            && preg_match($couldBeExpressionPattern = '/(^|[^\\\\])\{/', $expression)
79
        ) {
80
            do {
81
                $expression = parent::evaluate($expression, $values);
82
                if (!is_string($expression)) {
83
                    break;
84
                }
85
                if (!preg_match($couldBeExpressionPattern, $expression)) {
86
                    $expression = str_replace(['\\{', '\\}'], ['{', '}'], $expression);
87
                    if (strpos($expression, '{') !== false) {
88
                        $this->expressionResults[] = $expression;
89
                    }
90
                    break;
91
                }
92
            } while (true);
93
        }
94
        return $expression;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $expression; (array|string|Symfony\Com...sionLanguage\Expression) is incompatible with the return type of the parent method Symfony\Component\Expres...ssionLanguage::evaluate of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
95
    }
96
97
98
    /**
99
     * Ask a question
100
     *
101
     * @param Task     $task     The task on which the question was asked
102
     * @param Question $question The question
103
     *
104
     * @return mixed The answer
105
     */
106
    protected function ask(Task $task, $question)
107
    {
108
        $console = $task->console;
109
        return $console->getHelper('question')->ask(
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\DialogHelper, Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
110
            $console->getInput(),
111
            $console->getOutput(),
112
            $question
113
        );
114
    }
115
116
    /**
117
     * Register functions
118
     *
119
     * @return void
120
     */
121
    protected function registerFunctions()
122
    {
123
        parent::registerFunctions();
124
        $this->register(
125
            'confirm',
126
            function ($question) {
0 ignored issues
show
Unused Code introduced by
The parameter $question is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
127
            },
128
            function (array $values, $question) {
129
                return $this->ask($values[self::VARIABLES_KEY], new ConfirmationQuestion("<question>$question</question> [y] "));
130
            }
131
        );
132
        $this->register(
133
            'answer',
134
            function ($question) {
0 ignored issues
show
Unused Code introduced by
The parameter $question is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
135
            },
136
            function (array $values, $question) {
137
                return $this->ask($values[self::VARIABLES_KEY], new Question("<question>$question</question> "));
138
            }
139
        );
140
        $this->register(
141
            'choose',
142
            function ($question) {
0 ignored issues
show
Unused Code introduced by
The parameter $question is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
143
            },
144
            function (array $values, $question, array $choices) {
145
                return $this->ask($values[self::VARIABLES_KEY], new ChoiceQuestion("<question>$question</question> ", $choices));
146
            }
147
        );
148
        $this->register(
149
            'isset',
150
            function ($var) {
0 ignored issues
show
Unused Code introduced by
The parameter $var is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
151
            },
152
            function (array $values, $var) {
153
                return $values[self::VARIABLES_KEY]->has($var);
154
            }
155
        );
156
        $this->register(
157
            'empty',
158
            function ($var) {
0 ignored issues
show
Unused Code introduced by
The parameter $var is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
159
            },
160
            function (array $values, $var) {
161
                return $values[self::VARIABLES_KEY]->has($var) && $values[self::VARIABLES_KEY]->get($var);
162
            }
163
        );
164
        $this->register(
165
            'get',
166
            function () {
167
            },
168
            function (array $values, $var) {
169
                return $values[self::VARIABLES_KEY]->get($var);
170
            }
171
        );
172
        $this->register(
173
            'set',
174
            function () {
175
            },
176
            function (array $values, $var, $value) {
177
                $values[self::VARIABLES_KEY]->set($var, $value);
178
                return $value;
179
            }
180
        );
181
        $this->register(
182
            'replace',
183
            function () {
184
            },
185
            function (array $values, $search, $replace, $subject, $regex = false) {
186
                if ($regex) {
187
                    return preg_replace($search, $replace, $subject);
188
                } else {
189
                    return str_replace($search, $replace, $subject);
190
                }
191
            }
192
        );
193
    }
194
}
195
?>
1 ignored issue
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...
196