Completed
Push — master ( 5fca22...233410 )
by Emily
01:43
created

PropertyAccessor::buildProperty()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 3
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
33
/**
34
 * This class is used to access properties of a composite and enforce
35
 * data type requirements
36
 */
37
class PropertyAccessor extends RawPropertyAccessor
38
{
39
    /**
40
     * Reflection information about the composite being accessed
41
     *
42
     * @var ReflectionComposite
43
     */
44
    protected $reflect;
45
46
    /**
47
     * Creates the PropertyAccessor for the given object, using the
48
     * given reflection information
49
     *
50
     * @param object $object The object to access
51
     * @param ReflectionComposite $reflect Reflection information about
52
     *     the composite
53
     */
54 23
    public function __construct($object, ReflectionComposite $reflect)
55
    {
56 23
        parent::__construct($object);
57
58 23
        $this->reflect = $reflect;
59 23
    }
60
61
    /**
62
     * Initializes the given object with the given parameters, enforcing
63
     * the constructor requirements and auto building any left overs
64
     */
65 6
    public function constructObject(...$args)
66
    {
67 6
        $i = 0;
68 6
        foreach ($this->reflect->requiredProperties as $property)
69
        {
70 6
            if (!isset($args[$i]))
71
            {
72 2
                throw new MissingRequiredParameterException
73
                (
74 2
                    get_class($this->object),
75 2
                    $property->name
76
                );
77
            }
78
79 4
            $this->setAnyValue($property, $args[$i]);
80
81 4
            $i++;
82
        }
83
84 4
        $building = false;
85 4
        foreach ($this->reflect->optionalProperties as $property)
86
        {
87 4
            if ($building)
88
            {
89 2
                $this->buildProperty($property);
90
            }
91
            else
92
            {
93 4
                if (isset($args[$i]))
94
                {
95 2
                    $this->setAnyValue($property, $args[$i]);
96 2
                    $i++;
97
                }
98
                else
99
                {
100 2
                    $building = true;
101 4
                    $this->buildProperty($property);
102
                }
103
            }
104
        }
105
106 4
        foreach ($this->reflect->builtProperties as $property)
107
        {
108 4
            $this->buildProperty($property);
109
        }
110 4
    }
111
112
    /**
113
     * Builds a property automatically
114
     *
115
     * @param ReflectionProperty $property The property to build
116
     */
117 4
    protected function buildProperty(ReflectionProperty $property)
118
    {
119 4
        if (!$property->type instanceof ObjectType)
120
        {
121 3
            $this->setAnyValue($property, 0);
122
        }
123 3
        elseif ($property->builtInConstructor)
124
        {
125 2
            $class = (string)$property->type->classname;
126 2
            $this->setRawValue($property->name, new $class());
127
        }
128 4
    }
129
130
    /**
131
     * Returns the value of the property
132
     *
133
     * @param string $property The name of the property to get
134
     * @return mixed The value of the property
135
     */
136 6
    public function getValue(string $property)
137
    {
138 6
        return $this->getRawValue($property);
139
    }
140
141
    /**
142
     * Sets the value of a property, enforcing datatype requirements
143
     *
144
     * @param string $property The name of the property to set
145
     * @param mixed $value The value to set
146
     */
147 9
    public function setValue(string $property, $value)
148
    {
149 9
        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...
150
        {
151
            throw new CannotWritePropertyException
152
            (
153
                get_class($this->object), $property
154
            );
155
        }
156
157 9
        $this->setAnyValue
158
        (
159 9
            $this->reflect->properties[$property],
160 9
            $value
161
        );
162 5
    }
163
164
    /**
165
     * Sets the value of a property, enforcing datatype requirements
166
     *
167
     * @param ReflectionProperty $property The property to set
168
     * @param mixed $value The value to set
169
     */
170 10
    protected function setAnyValue(ReflectionProperty $property, $value)
171
    {
172 10
        $comparator = new TypeComparator();
173
174 10
        $valueType = (new TypeParser())->parseFromType($value);
175
176 10
        if ($comparator->compatible($property->type, $valueType))
177
        {
178 8
            $this->setRawValue($property->name, $value);
179
        }
180 5
        elseif ($property->type instanceof ScalarType)
181
        {
182 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...
183
        }
184
        else
185
        {
186 1
            $this->throwError($property, $valueType);
187
        }
188 9
    }
189
190
    /**
191
     * Attempts to set a property which expects a scalar value
192
     *
193
     * @param ReflectionProperty $property The property to set
194
     * @param ScalarType $valueType The scalar type
195
     * @param mixed $value The value to set
196
     */
197 4
    private function setScalarValue
198
    (
199
        ReflectionProperty $property,
200
        ScalarType $valueType,
201
        $value
202
    )
203
    {
204 4
        $method = '__to' . $valueType;
205
206 4
        if (is_scalar($value))
207
        {
208 4
            $this->setRawValue
209
            (
210 4
                $property->name,
211 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...
212
            );
213
        }
214
        elseif (is_object($value) && method_exists([$value, $method]))
215
        {
216
            $this->setScalarValue
217
            (
218
                $property,
219
                $valueType,
220
                $value->$method()
221
            );
222
        }
223
        else
224
        {
225
            $this->throwError($property, $valueType);
226
        }
227 4
    }
228
229
    /**
230
     * Throws an IlleglPropertyTypeException
231
     *
232
     * @param ReflectionProperty $property The property being set
233
     * @param AbstractType $valueType The value being set
234
     */
235 1
    private function throwError
236
    (
237
        ReflectionProperty $property,
238
        AbstractType $valueType
239
    )
240
    {
241 1
        throw new IllegalPropertyTypeException
242
        (
243 1
            get_class($this->object),
244 1
            $property->name,
245 1
            $property->type,
246 1
            $valueType
247
        );
248
    }
249
}
250