Completed
Pull Request — master (#8)
by Emily
02:26
created

PropertyAccessor::setValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 6
cts 8
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 2
crap 2.0625
1
<?php
2
/**
3
 * This file is part of the Composite Utils package.
4
 *
5
 * (c) Emily Shepherd <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the
8
 * LICENSE.md file that was distributed with this source code.
9
 *
10
 * @package spaark/composite-utils
11
 * @author Emily Shepherd <[email protected]>
12
 * @license MIT
13
 */
14
15
namespace Spaark\CompositeUtils\Service;
16
17
use Spaark\CompositeUtils\Model\Reflection\ReflectionComposite;
18
use Spaark\CompositeUtils\Model\Reflection\ReflectionProperty;
19
use Spaark\CompositeUtils\Model\Reflection\Type\ObjectType;
20
use Spaark\CompositeUtils\Model\Reflection\Type\MixedType;
21
use Spaark\CompositeUtils\Model\Reflection\Type\StringType;
22
use Spaark\CompositeUtils\Model\Reflection\Type\IntegerType;
23
use Spaark\CompositeUtils\Model\Reflection\Type\BooleanType;
24
use Spaark\CompositeUtils\Model\Reflection\Type\CollectionType;
25
use Spaark\CompositeUtils\Model\Reflection\Type\ScalarType;
26
use Spaark\CompositeUtils\Model\Reflection\Type\AbstractType;
27
use Spaark\CompositeUtils\Exception\CannotWritePropertyException;
28
use Spaark\CompositeUtils\Exception\IllegalPropertyTypeException;
29
use Spaark\CompositeUtils\Exception\MissingRequiredParameterException;
30
use Spaark\CompositeUtils\Factory\Reflection\TypeParser;
31
use Spaark\CompositeUtils\Service\TypeComparator;
32
use Spaark\CompositeUtils\Traits\Generic;
33
34
/**
35
 * This class is used to access properties of a composite and enforce
36
 * data type requirements
37
 */
38
class PropertyAccessor extends RawPropertyAccessor
39
{
40
    /**
41
     * Reflection information about the composite being accessed
42
     *
43
     * @var ReflectionComposite
44
     */
45
    protected $reflect;
46
47
    /**
48
     * Creates the PropertyAccessor for the given object, using the
49
     * given reflection information
50
     *
51
     * @param object $object The object to access
52
     * @param ReflectionComposite $reflect Reflection information about
53
     *     the composite
54
     */
55 30
    public function __construct($object, ReflectionComposite $reflect)
56
    {
57 30
        parent::__construct($object);
58
59 30
        $this->reflect = $reflect;
60 30
    }
61
62
    /**
63
     * Initializes the given object with the given parameters, enforcing
64
     * the constructor requirements and auto building any left overs
65
     */
66 13
    public function constructObject(...$args)
67
    {
68 13
        $i = 0;
69 13
        foreach ($this->reflect->requiredProperties as $property)
70
        {
71 13
            if (!isset($args[$i]))
72
            {
73 2
                throw new MissingRequiredParameterException
74
                (
75 2
                    get_class($this->object),
76 2
                    $property->name
77
                );
78
            }
79
80 11
            $this->setAnyValue($property, $args[$i]);
81
82 11
            $i++;
83
        }
84
85 11
        $building = false;
86 11
        foreach ($this->reflect->optionalProperties as $property)
87
        {
88 4
            if ($building)
89
            {
90 2
                $this->buildProperty($property);
91
            }
92
            else
93
            {
94 4
                if (isset($args[$i]))
95
                {
96 2
                    $this->setAnyValue($property, $args[$i]);
97 2
                    $i++;
98
                }
99
                else
100
                {
101 2
                    $building = true;
102 4
                    $this->buildProperty($property);
103
                }
104
            }
105
        }
106
107 11
        foreach ($this->reflect->builtProperties as $property)
108
        {
109 4
            $this->buildProperty($property);
110
        }
111 11
    }
112
113
    /**
114
     * Builds a property automatically
115
     *
116
     * @param ReflectionProperty $property The property to build
117
     */
118 4
    protected function buildProperty(ReflectionProperty $property)
119
    {
120 4
        if (!$property->type instanceof ObjectType)
121
        {
122 3
            $this->setAnyValue($property, 0);
123
        }
124 3
        elseif ($property->builtInConstructor)
125
        {
126 2
            $class = (string)$property->type->classname;
127 2
            $this->setRawValue($property->name, new $class());
128
        }
129 4
    }
130
131
    /**
132
     * Returns the value of the property
133
     *
134
     * @param string $property The name of the property to get
135
     * @return mixed The value of the property
136
     */
137 9
    public function getValue(string $property)
138
    {
139 9
        return $this->getRawValue($property);
140
    }
141
142
    /**
143
     * Sets the value of a property, enforcing datatype requirements
144
     *
145
     * @param string $property The name of the property to set
146
     * @param mixed $value The value to set
147
     */
148 11
    public function setValue(string $property, $value)
149
    {
150 11
        if (!$this->reflect->properties->containsKey($property))
0 ignored issues
show
Documentation introduced by
$property is of type string, but the function expects a object<Spaark\CompositeU...Collection\Map\KeyType>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
151
        {
152
            throw new CannotWritePropertyException
153
            (
154
                get_class($this->object), $property
155
            );
156
        }
157
158 11
        $this->setAnyValue
159
        (
160 11
            $this->reflect->properties[$property],
161 11
            $value
162
        );
163 6
    }
164
165
    /**
166
     * Sets the value of a property, enforcing datatype requirements
167
     *
168
     * @param ReflectionProperty $property The property to set
169
     * @param mixed $value The value to set
170
     */
171 17
    protected function setAnyValue(ReflectionProperty $property, $value)
172
    {
173 17
        $comparator = new TypeComparator();
174
175 17
        if ($value instanceof Generic)
176
        {
177 2
            $valueType = $value->getObjectType();
178
        }
179
        else
180
        {
181 17
            $valueType = (new TypeParser())->parseFromType($value);
182
        }
183
184 17
        if ($comparator->compatible($property->type, $valueType))
185
        {
186 15
            $this->setRawValue($property->name, $value);
187
        }
188 6
        elseif ($property->type instanceof ScalarType)
189
        {
190 4
            $this->setScalarValue($property, $valueType, $value);
0 ignored issues
show
Compatibility introduced by
$valueType of type object<Spaark\CompositeU...tion\Type\AbstractType> is not a sub-type of object<Spaark\CompositeU...ection\Type\ScalarType>. It seems like you assume a child class of the class Spaark\CompositeUtils\Mo...ction\Type\AbstractType 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...
191
        }
192
        else
193
        {
194 2
            $this->throwError($property, $valueType);
195
        }
196 16
    }
197
198
    /**
199
     * Attempts to set a property which expects a scalar value
200
     *
201
     * @param ReflectionProperty $property The property to set
202
     * @param ScalarType $valueType The scalar type
203
     * @param mixed $value The value to set
204
     */
205 4
    private function setScalarValue
206
    (
207
        ReflectionProperty $property,
208
        ScalarType $valueType,
209
        $value
210
    )
211
    {
212 4
        $method = '__to' . $valueType;
213
214 4
        if (is_scalar($value))
215
        {
216 4
            $this->setRawValue
217
            (
218 4
                $property->name,
219 4
                $property->type->cast($value)
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Spaark\CompositeUtils\Mo...ction\Type\AbstractType as the method cast() does only exist in the following sub-classes of Spaark\CompositeUtils\Mo...ction\Type\AbstractType: Spaark\CompositeUtils\Mo...ection\Type\BooleanType, Spaark\CompositeUtils\Mo...flection\Type\FloatType, Spaark\CompositeUtils\Mo...ection\Type\IntegerType, Spaark\CompositeUtils\Mo...lection\Type\ScalarType, Spaark\CompositeUtils\Mo...lection\Type\StringType. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
220
            );
221
        }
222
        elseif (is_object($value) && method_exists([$value, $method]))
223
        {
224
            $this->setScalarValue
225
            (
226
                $property,
227
                $valueType,
228
                $value->$method()
229
            );
230
        }
231
        else
232
        {
233
            $this->throwError($property, $valueType);
234
        }
235 4
    }
236
237
    /**
238
     * Throws an IlleglPropertyTypeException
239
     *
240
     * @param ReflectionProperty $property The property being set
241
     * @param AbstractType $valueType The value being set
242
     */
243 2
    private function throwError
244
    (
245
        ReflectionProperty $property,
246
        AbstractType $valueType
247
    )
248
    {
249 2
        throw new IllegalPropertyTypeException
250
        (
251 2
            get_class($this->object),
252 2
            $property->name,
253 2
            $property->type,
254 2
            $valueType
255
        );
256
    }
257
}
258