Passed
Push — master ( f8eb54...68901a )
by Kirill
04:07
created

BaseRules::getFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
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 dd($this->rules);
95
    }
96
97
    /**
98
     * @param string $rule
99
     * @return bool
100
     */
101
    public function has(string $rule): bool
102
    {
103
        return \array_key_exists($rule, $this->rules);
104
    }
105
106
    /**
107
     * @return iterable
108
     */
109
     public function getDelegates(): iterable
110
     {
111
         return $this->delegates;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->delegates; (array) is incompatible with the return type declared by the interface Railt\Compiler\Reader\ProvideRules::getDelegates of type Railt\Compiler\Reader\iterable.

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...
112
     }
113
114
    /**
115
     * @param string $rule
116
     * @return Readable
117
     */
118
    public function getFile(string $rule): Readable
119
    {
120
        return $this->files[$rule];
121
    }
122
}
123