Completed
Push — master ( 296743...12eab9 )
by Kirill
36:17
created

ArgumentCoercion::normalizeDefinedValue()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 42
ccs 7
cts 7
cp 1
rs 8.6257
c 0
b 0
f 0
cc 6
nc 8
nop 1
crap 6
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\Reflection\Coercion;
11
12
use Railt\SDL\Base\Dependent\BaseArgument;
13
use Railt\SDL\Contracts\Definitions\TypeDefinition;
14
use Railt\SDL\Contracts\Dependent\ArgumentDefinition;
15
16
/**
17
 * Class ArgumentCoercion
18
 */
19
class ArgumentCoercion extends BaseTypeCoercion
20
{
21
    /**
22
     * @param TypeDefinition $type
23
     * @return bool
24
     */
25 6571
    public function match(TypeDefinition $type): bool
26
    {
27 6571
        return $type instanceof ArgumentDefinition;
28
    }
29
30
    /**
31
     * @param TypeDefinition|ArgumentDefinition $type
32
     */
33 5545
    public function apply(TypeDefinition $type): void
34
    {
35 5545
        if ($type->hasDefaultValue()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\SDL\Contracts\Definitions\TypeDefinition as the method hasDefaultValue() does only exist in the following implementations of said interface: Railt\SDL\Base\Dependent\BaseArgument, Railt\SDL\Reflection\Bui...pendent\ArgumentBuilder, Railt\SDL\Standard\Directives\Deprecation\Reason.

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...
36 5320
            $this->normalizeDefinedValue($type);
0 ignored issues
show
Compatibility introduced by
$type of type object<Railt\SDL\Contrac...nitions\TypeDefinition> is not a sub-type of object<Railt\SDL\Contrac...ent\ArgumentDefinition>. It seems like you assume a child interface of the interface Railt\SDL\Contracts\Definitions\TypeDefinition 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...
37 5320
            return;
38
        }
39
40 5535
        if (! $type->hasDefaultValue()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Railt\SDL\Contracts\Definitions\TypeDefinition as the method hasDefaultValue() does only exist in the following implementations of said interface: Railt\SDL\Base\Dependent\BaseArgument, Railt\SDL\Reflection\Bui...pendent\ArgumentBuilder, Railt\SDL\Standard\Directives\Deprecation\Reason.

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...
41 5535
            $this->inferenceValue($type);
0 ignored issues
show
Compatibility introduced by
$type of type object<Railt\SDL\Contrac...nitions\TypeDefinition> is not a sub-type of object<Railt\SDL\Contrac...ent\ArgumentDefinition>. It seems like you assume a child interface of the interface Railt\SDL\Contracts\Definitions\TypeDefinition 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...
42 5535
            return;
43
        }
44
    }
45
46
    /**
47
     * @param ArgumentDefinition|BaseArgument $argument
48
     */
49 5320
    private function normalizeDefinedValue(ArgumentDefinition $argument): void
50
    {
51 5320
        $value = $argument->getDefaultValue();
52
53
        /**
54
         * The value can be automatically adjusted without loss of meaning:
55
         *
56
         * <code>
57
         *      # Will transforms to List:
58
         *      field(arg: [Int]    = 23)      → field(arg: [Int]    = [23])
59
         *      field(arg: [String] = "s")     → field(arg: [String] = ["s"])
60
         *      field(arg: [ID]     = "id")    → field(arg: [ID]     = ["id"])
61
         *      field(arg: [Float]  = 4.2)     → field(arg: [Float]  = [4.2])
62
         *      field(arg: [Input]  = {a: 23}) → field(arg: [Input]  = [{a: 23}])
63
         *      # etc...
64
         *
65
         *      # Excluding "NULL":
66
         *      field(arg: [Float]  = null)    → field(arg: [Float]  = null)
67
         * </code>
68
         */
69 5320
        $isListDefinedByNonList = ($value !== null && ! \is_array($value));
70
71
        /**
72
         * The allowable conversion method for NULL:
73
         * <code>
74
         *      # As it is while Nullable type initialized by NULL:
75
         *      field(arg: [ID] = null)      →   field(arg: [ID] = null)
76
         *
77
         *      # But apply coercion while NonNull type initialized by NULL:
78
         *      field(arg: [ID]! = null)     →   field(arg: [ID]! = [null])
79
         * </code>
80
         */
81 5320
        $isNonNullListDefinedByNull = ($argument->isNonNull() && $value === null);
82
83 5320
        if (($isListDefinedByNonList || $isNonNullListDefinedByNull) && $argument->isList()) {
84
            /**
85
             * Warn: Do not change to `(array)$value` since leads
86
             * to the destructuring of some iterators (like instance of InputInvocation::class).
87
             */
88 307
            $this->set($argument, [$value]);
0 ignored issues
show
Compatibility introduced by
$argument of type object<Railt\SDL\Contrac...ent\ArgumentDefinition> is not a sub-type of object<Railt\SDL\Base\Dependent\BaseArgument>. It seems like you assume a concrete implementation of the interface Railt\SDL\Contracts\Dependent\ArgumentDefinition 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...
89
        }
90 5320
    }
91
92
    /**
93
     * @param ArgumentDefinition|BaseArgument $argument
94
     */
95 5535
    private function inferenceValue(ArgumentDefinition $argument): void
96
    {
97
        /**
98
         * Any code initialization like:
99
         * <code>
100
         *      field(argument: [Type]): Type
101
         * </code>
102
         *
103
         * Will transform to:
104
         * <code>
105
         *      field(argument: [Type] = []): Type
106
         * </code>
107
         */
108 5535
        if ($argument->isList()) {
109 18
            $this->set($argument, []);
0 ignored issues
show
Compatibility introduced by
$argument of type object<Railt\SDL\Contrac...ent\ArgumentDefinition> is not a sub-type of object<Railt\SDL\Base\Dependent\BaseArgument>. It seems like you assume a concrete implementation of the interface Railt\SDL\Contracts\Dependent\ArgumentDefinition 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...
110 18
            return;
111
        }
112
113
        /**
114
         * Any code initialization like:
115
         * <code>
116
         *      field(argument: Type): Type
117
         * </code>
118
         *
119
         * Will transform to:
120
         * <code>
121
         *      field(argument: Type = NULL): Type
122
         * </code>
123
         */
124 5517
        if (! $argument->isNonNull()) {
125 5509
            $this->set($argument, null);
0 ignored issues
show
Compatibility introduced by
$argument of type object<Railt\SDL\Contrac...ent\ArgumentDefinition> is not a sub-type of object<Railt\SDL\Base\Dependent\BaseArgument>. It seems like you assume a concrete implementation of the interface Railt\SDL\Contracts\Dependent\ArgumentDefinition 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...
126 5509
            return;
127
        }
128 40
    }
129
130
    /**
131
     * @param BaseArgument $argument
132
     * @param $value
133
     */
134
    private function set(BaseArgument $argument, $value): void
135
    {
136 5528
        $invocation = function ($value): void {
137
            /** @var BaseArgument $this */
138 5528
            $this->defaultValue    = $value;
0 ignored issues
show
Bug introduced by
The property defaultValue does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
139 5528
            $this->hasDefaultValue = true;
0 ignored issues
show
Bug introduced by
The property hasDefaultValue does not seem to exist. Did you mean defaultValue?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
140 5528
        };
141
142 5528
        $invocation->call($argument, $value);
143 5528
    }
144
}
145