Completed
Push — master ( 8afd90...4bf010 )
by Kirill
03:48
created

SchemaBuilder::buildSchemaFields()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
nc 2
nop 2
dl 0
loc 34
ccs 0
cts 28
cp 0
crap 42
rs 8.7537
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\Exception\TypeConflictException;
20
21
/**
22
 * Class SchemaBuilder
23
 */
24
class SchemaBuilder extends Builder
25
{
26
    /**
27
     * @var string
28
     */
29
    private const FIELD_QUERY = 'query';
30
31
    /**
32
     * @var string
33
     */
34
    private const FIELD_MUTATION = 'mutation';
35
36
    /**
37
     * @var string
38
     */
39
    private const FIELD_SUBSCRIPTION = 'subscription';
40
41
    /**
42
     * @param RuleInterface|SchemaDefinitionNode $rule
43
     * @param Definition $parent
44
     * @return Definition
45
     * @throws \Railt\Io\Exception\ExternalFileException
46
     */
47
    public function build(RuleInterface $rule, Definition $parent): Definition
48
    {
49
        $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...
50
        $schema->withOffset($rule->getOffset());
51
        $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...
52
53
        $this->when->runtime(function () use ($rule, $schema) {
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
59
        $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...
60
61
        return $schema;
62
    }
63
64
    /**
65
     * @param SchemaDefinitionNode $rule
66
     * @param SchemaDefinition $schema
67
     * @throws \Railt\Io\Exception\ExternalFileException
68
     */
69
    private function buildSchemaFields(SchemaDefinitionNode $rule, SchemaDefinition $schema): void
70
    {
71
        foreach ($rule->getSchemaFields() as $ast) {
72
            $name = $ast->getFieldName();
73
            $hint = $ast->getTypeHint();
74
75
            $this->validateModifiers($name, $hint, $schema);
76
            $this->validateFieldName($name, $ast, $schema);
77
78
            $this->when->resolving(function () use ($name, $schema, $hint) {
79
                $type = $this->load($hint->getTypeName(), $schema);
80
81
                if (! ($type instanceof Definition\ObjectDefinition)) {
82
                    $error = 'Schema field %s<SchemaField> should return Object type, but %s given';
83
                    throw (new TypeConflictException(\sprintf($error, $name, $type)))
84
                        ->throwsIn($schema->getFile(), $hint->getOffset());
85
                }
86
87
                switch ($name) {
88
                    case self::FIELD_QUERY:
89
                        $schema->withQuery($type);
90
                        break;
91
92
                    case self::FIELD_MUTATION:
93
                        $schema->withMutation($type);
94
                        break;
95
96
                    case self::FIELD_SUBSCRIPTION:
97
                        $schema->withSubscription($type);
98
                        break;
99
                }
100
            });
101
        }
102
    }
103
104
    /**
105
     * @param string $field
106
     * @param TypeHintNode $hint
107
     * @param SchemaDefinition $schema
108
     * @throws \Railt\Io\Exception\ExternalFileException
109
     */
110
    private function validateModifiers(string $field, TypeHintNode $hint, SchemaDefinition $schema): void
111
    {
112
        if ($hint->getModifiers() !== 0) {
113
            $error = 'Schema field %s<SchemaField> should be a Nullable and Non-List';
114
            throw (new TypeConflictException(\sprintf($error, $field)))
115
                ->throwsIn($schema->getFile(), $hint->getOffset());
116
        }
117
    }
118
119
    /**
120
     * @param string $field
121
     * @param SchemaFieldDefinitionNode $rule
122
     * @param SchemaDefinition $schema
123
     * @throws \Railt\Io\Exception\ExternalFileException
124
     */
125
    private function validateFieldName(string $field, SchemaFieldDefinitionNode $rule, SchemaDefinition $schema): void
126
    {
127
        if (! \in_array($field, [self::FIELD_QUERY, self::FIELD_MUTATION, self::FIELD_SUBSCRIPTION], true)) {
128
            $error = \sprintf('Invalid %s schema field name "%s"', $schema, $field);
129
130
            throw (new TypeConflictException($error))->throwsIn($schema->getFile(), $rule->getOffset());
131
        }
132
    }
133
}
134