Completed
Push — master ( 69b695...671bd7 )
by Kirill
06:49
created

BaseRules::add()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 9
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 6
nop 1
crap 20
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\Compiler\Reader;
11
12
use Railt\Compiler\Exception\GrammarException;
13
use Railt\Io\Readable;
14
use Railt\Parser\Ast\Delegate;
15
use Railt\Parser\Ast\Rule;
16
use Railt\Parser\Rule\Production;
17
use Railt\Parser\Rule\Symbol;
18
use Railt\Parser\Rule\Terminal;
19
20
/**
21
 * Class BaseRules
22
 */
23
abstract class BaseRules implements ProvideRules
24
{
25
    /**
26
     * @var array|Symbol[]
27
     */
28
    private $rules = [];
29
30
    /**
31
     * @var array
32
     */
33
    private $mappings = [];
34
35
    /**
36
     * @var array
37
     */
38
    private $delegates = [];
39
40
    /**
41
     * @var array|Readable[]
42
     */
43
    private $files = [];
44
45
    /**
46
     * @param Symbol $symbol
47
     */
48
    protected function add(Symbol $symbol): void
49
    {
50
        $this->rules[$symbol->getId()] = $symbol;
51
52
        $providesName = $symbol instanceof Terminal ||
53
            ($symbol instanceof Production && $symbol->getName());
0 ignored issues
show
Bug Best Practice introduced by
The expression $symbol->getName() of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
54
55
        if ($providesName) {
56
            $this->mappings[$symbol->getName()] = $symbol->getId();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\Parser\Rule\Symbol as the method getName() does only exist in the following implementations of said interface: Railt\Parser\Rule\Alternation, Railt\Parser\Rule\BaseProduction, Railt\Parser\Rule\Concatenation, Railt\Parser\Rule\Repetition, Railt\Parser\Rule\Token.

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...
57
        }
58
    }
59
60
    /**
61
     * @param string $rule
62
     * @param string $delegate
63
     * @throws GrammarException
64
     */
65
    protected function addDelegate(string $rule, string $delegate): void
66
    {
67
        if (! \class_exists($delegate)) {
68
            $error = 'Could not found delegate class "%s"';
69
            throw new GrammarException(\sprintf($error, $delegate));
70
        }
71
72
        if (! \is_subclass_of($delegate, Delegate::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Railt\Parser\Ast\Delegate::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
73
            $error = 'Delegate should be an instance of %s, but %s given';
74
            throw new GrammarException(\sprintf($error, Delegate::class, $delegate));
75
        }
76
77
        $this->delegates[$rule] = $delegate;
78
    }
79
80
    /**
81
     * @param string $rule
82
     * @param Readable $grammar
83
     */
84
    protected function addFile(string $rule, Readable $grammar): void
85
    {
86
        $this->files[$rule] = $grammar;
87
    }
88
89
    /**
90
     * @return array
91
     */
92
    public function all(): array
93
    {
94
        return $this->rules;
95
    }
96
97
    /**
98
     * @param string $rule
99
     * @return bool
100
     */
101
    public function hasDelegate(string $rule): bool
102
    {
103
        return \array_key_exists($rule, $this->delegates);
104
    }
105
106
    /**
107
     * @param string $rule
108
     * @return string
109
     */
110
    public function getDelegate(string $rule): string
111
    {
112
        return $this->delegates[$rule] ?? Rule::class;
113
    }
114
115
    /**
116
     * @param string $rule
117
     * @return Readable
118
     */
119
    public function getFile(string $rule): Readable
120
    {
121
        return $this->files[$rule];
122
    }
123
}
124