Completed
Push — master ( 7510c8...82c7bd )
by Kirill
08:19
created

SchemaBuilder::buildSchemaFields()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 2
dl 0
loc 24
ccs 0
cts 20
cp 0
crap 30
rs 9.2248
c 0
b 0
f 0
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\SDL\Compiler\Builder\Definition;
11
12
use Railt\Parser\Ast\RuleInterface;
13
use Railt\Reflection\Contracts\Definition;
14
use Railt\Reflection\Definition\SchemaDefinition;
15
use Railt\SDL\Compiler\Ast\Definition\SchemaDefinitionNode;
16
use Railt\SDL\Compiler\Ast\Dependent\SchemaFieldDefinitionNode;
17
use Railt\SDL\Compiler\Ast\TypeHintNode;
18
use Railt\SDL\Compiler\Builder\Builder;
19
use Railt\SDL\Compiler\Renderer;
20
use Railt\SDL\Exception\TypeConflictException;
21
22
/**
23
 * Class SchemaBuilder
24
 */
25
class SchemaBuilder extends Builder
26
{
27
    /**
28
     * @var string
29
     */
30
    private const FIELD_QUERY = 'query';
31
32
    /**
33
     * @var string
34
     */
35
    private const FIELD_MUTATION = 'mutation';
36
37
    /**
38
     * @var string
39
     */
40
    private const FIELD_SUBSCRIPTION = 'subscription';
41
42
    /**
43
     * @param RuleInterface|SchemaDefinitionNode $rule
44
     * @param Definition $parent
45
     * @return Definition
46
     * @throws \Railt\Io\Exception\ExternalFileException
47
     */
48
    public function build(RuleInterface $rule, Definition $parent): Definition
49
    {
50
        $schema = new SchemaDefinition($parent->getDocument(), $rule->getTypeName());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\Parser\Ast\RuleInterface as the method getTypeName() does only exist in the following implementations of said interface: Railt\SDL\Compiler\Ast\D...DirectiveDefinitionNode, Railt\SDL\Compiler\Ast\D...tion\EnumDefinitionNode, Railt\SDL\Compiler\Ast\D...ion\InputDefinitionNode, Railt\SDL\Compiler\Ast\D...nputUnionDefinitionNode, Railt\SDL\Compiler\Ast\D...InterfaceDefinitionNode, Railt\SDL\Compiler\Ast\D...on\ObjectDefinitionNode, Railt\SDL\Compiler\Ast\D...on\ScalarDefinitionNode, Railt\SDL\Compiler\Ast\D...on\SchemaDefinitionNode, Railt\SDL\Compiler\Ast\D...tion\TypeDefinitionNode, Railt\SDL\Compiler\Ast\D...ion\UnionDefinitionNode, Railt\SDL\Compiler\Ast\TypeHintNode, Railt\SDL\Compiler\Ast\TypeNameNode.

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...
Compatibility introduced by
$parent->getDocument() of type object<Railt\Reflection\Contracts\Document> is not a sub-type of object<Railt\Reflection\Document>. It seems like you assume a concrete implementation of the interface Railt\Reflection\Contracts\Document to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
51
        $schema->withOffset($rule->getOffset());
52
        $schema->withDescription($rule->getDescription());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\Parser\Ast\RuleInterface as the method getDescription() does only exist in the following implementations of said interface: Railt\SDL\Compiler\Ast\D...DirectiveDefinitionNode, Railt\SDL\Compiler\Ast\D...tion\EnumDefinitionNode, Railt\SDL\Compiler\Ast\D...ion\InputDefinitionNode, Railt\SDL\Compiler\Ast\D...nputUnionDefinitionNode, Railt\SDL\Compiler\Ast\D...InterfaceDefinitionNode, Railt\SDL\Compiler\Ast\D...on\ObjectDefinitionNode, Railt\SDL\Compiler\Ast\D...on\ScalarDefinitionNode, Railt\SDL\Compiler\Ast\D...on\SchemaDefinitionNode, Railt\SDL\Compiler\Ast\D...tion\TypeDefinitionNode, Railt\SDL\Compiler\Ast\D...ion\UnionDefinitionNode, Railt\SDL\Compiler\Ast\D...\ArgumentDefinitionNode, Railt\SDL\Compiler\Ast\D...EnumValueDefinitionNode, Railt\SDL\Compiler\Ast\D...ent\FieldDefinitionNode, Railt\SDL\Compiler\Ast\D...nputFieldDefinitionNode.

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...
53
54
        foreach ($rule->getDirectives() as $ast) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\Parser\Ast\RuleInterface as the method getDirectives() does only exist in the following implementations of said interface: Railt\SDL\Compiler\Ast\D...DirectiveDefinitionNode, Railt\SDL\Compiler\Ast\D...tion\EnumDefinitionNode, Railt\SDL\Compiler\Ast\D...ion\InputDefinitionNode, Railt\SDL\Compiler\Ast\D...nputUnionDefinitionNode, Railt\SDL\Compiler\Ast\D...InterfaceDefinitionNode, Railt\SDL\Compiler\Ast\D...on\ObjectDefinitionNode, Railt\SDL\Compiler\Ast\D...on\ScalarDefinitionNode, Railt\SDL\Compiler\Ast\D...on\SchemaDefinitionNode, Railt\SDL\Compiler\Ast\D...tion\TypeDefinitionNode, Railt\SDL\Compiler\Ast\D...ion\UnionDefinitionNode, Railt\SDL\Compiler\Ast\D...\ArgumentDefinitionNode, Railt\SDL\Compiler\Ast\D...EnumValueDefinitionNode, Railt\SDL\Compiler\Ast\D...ent\FieldDefinitionNode, Railt\SDL\Compiler\Ast\D...nputFieldDefinitionNode.

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...
55
            $schema->withDirective($this->dependent($ast, $schema));
56
        }
57
58
        $this->buildSchemaFields($rule, $schema);
0 ignored issues
show
Compatibility introduced by
$rule of type object<Railt\Parser\Ast\RuleInterface> is not a sub-type of object<Railt\SDL\Compile...n\SchemaDefinitionNode>. It seems like you assume a concrete implementation of the interface Railt\Parser\Ast\RuleInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
59
60
        return $schema;
61
    }
62
63
    /**
64
     * @param SchemaDefinitionNode $rule
65
     * @param SchemaDefinition $schema
66
     * @throws \Railt\Io\Exception\ExternalFileException
67
     */
68
    private function buildSchemaFields(SchemaDefinitionNode $rule, SchemaDefinition $schema): void
69
    {
70
        foreach ($rule->getSchemaFields() as $ast) {
71
            $name = $ast->getFieldName();
72
            $hint = $ast->getTypeHint();
73
74
            $this->validateModifiers($name, $hint, $schema);
75
            $this->validateFieldName($name, $ast, $schema);
76
77
            switch ($name) {
78
                case self::FIELD_QUERY:
79
                    $schema->withQuery($hint->getTypeName());
80
                    break;
81
82
                case self::FIELD_MUTATION:
83
                    $schema->withMutation($hint->getTypeName());
84
                    break;
85
86
                case self::FIELD_SUBSCRIPTION:
87
                    $schema->withSubscription($hint->getTypeName());
88
                    break;
89
            }
90
        }
91
    }
92
93
    /**
94
     * @param string $field
95
     * @param TypeHintNode $hint
96
     * @param SchemaDefinition $schema
97
     * @throws \Railt\Io\Exception\ExternalFileException
98
     */
99
    private function validateModifiers(string $field, TypeHintNode $hint, SchemaDefinition $schema): void
100
    {
101
        if ($hint->getModifiers() !== 0) {
102
            $error = 'Schema field "%s" should be a nullable and non-list type, but "%s" given';
103
            $indication = Renderer::typeIndication($hint->getTypeName(), $hint->getModifiers());
104
105
            throw (new TypeConflictException(\sprintf($error, $field, $indication)))->throwsIn($schema->getFile(),
106
                $hint->getOffset());
107
        }
108
    }
109
110
    /**
111
     * @param string $field
112
     * @param SchemaFieldDefinitionNode $rule
113
     * @param SchemaDefinition $schema
114
     * @throws \Railt\Io\Exception\ExternalFileException
115
     */
116
    private function validateFieldName(string $field, SchemaFieldDefinitionNode $rule, SchemaDefinition $schema): void
117
    {
118
        if (! \in_array($field, [self::FIELD_QUERY, self::FIELD_MUTATION, self::FIELD_SUBSCRIPTION], true)) {
119
            $error = \sprintf('Invalid %s field name "%s"', $schema, $field);
120
121
            throw (new TypeConflictException($error))->throwsIn($schema->getFile(), $rule->getOffset());
122
        }
123
    }
124
}
125