Passed
Push — master ( 0a4514...70449d )
by Vincent
04:28
created

StringElement::tryCast()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.6111
cc 5
nc 3
nop 1
crap 5
1
<?php
2
3
namespace Bdf\Form\Leaf;
4
5
use TypeError;
6
use function Webmozart\Assert\Tests\StaticAnalysis\string;
7
8
/**
9
 * Element for a simple string field
10
 *
11
 * @see StringElementBuilder for build the element
12
 *
13
 * @extends LeafElement<string>
14
 */
15
class StringElement extends LeafElement
16
{
17
    /**
18
     * {@inheritdoc}
19
     */
20 185
    protected function toPhp($httpValue): ?string
21
    {
22 185
        if (!is_scalar($httpValue)) {
23 27
            return null;
24
        }
25
26 162
        return (string) $httpValue;
0 ignored issues
show
Bug Best Practice introduced by
The expression return (string)$httpValue returns the type string which is incompatible with the return type mandated by Bdf\Form\Leaf\LeafElement::toPhp() of Bdf\Form\Leaf\T|null.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 37
    protected function toHttp($phpValue): ?string
33
    {
34 37
        return $phpValue;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 81
    protected function tryCast($value): ?string
41
    {
42 81
        if ($value === null) {
43 7
            return null;
44
        }
45
46 79
        if (!is_scalar($value) && (!is_object($value) || !method_exists($value, '__toString'))) {
47 3
            throw new TypeError('The import()\'ed value of a '.static::class.' must be stringable or null');
48
        }
49
50 76
        return (string) $value;
51
    }
52
}
53